Javascript let declaration in for loops

Introduction

We can use var to define loop controlling variable.

The variable defined by var would available outside the loop body:

for (var i = 0; i < 5; ++i) { 
   // do loop things 
} 
console.log(i);  // 5 

let declarations does not have this problem.

The iterator variable will be scoped only to the for loop block:

for (let i = 0; i < 5; ++i) { 
   // do loop things 
} 
console.log(i);  // ReferenceError: i is not defined 



PreviousNext

Related