0

The question pop up in my head when I read example 6 in this post https://stackoverflow.com/a/111111/6359753

Will there ever be a difference between

// Example 1
let i;
var arr = [1,2,3]
for (i=0; i<arr.length; i++){
 // do stuff
}

and

// Example 2
var arr = [1,2,3]
for (let i=0; i<arr.length; i++){
 // do stuff
}

If they are the same, why are they the same?

In other words, I don't really understand let's scope. If declared outside the loop, are they scoped outside the loop? example 2's let clearly are scoped inside the for loop, but example 1 I'm not so sure.

Henry Yang
  • 2,283
  • 3
  • 21
  • 38
  • let is used to assign variable temp, they only work in that scope. eg. if you use let i=0 in a for loop, it only works inside that loop. – Akhil Aravind May 24 '18 at 07:23

3 Answers3

1

If it is declared in the for loop, it is visible only in the loop's body. Outside of loop i is not visible.

var arr = [1,2,3];

for (let i=0; i<arr.length; i++) {
 
}

console.log(i);

If it is declared outside the for loop, the scope of the variable is the closest surrounded block {}.

let i;
var arr = [1,2,3];

for (i = 0; i < arr.length; i++) {

}

console.log(i);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

No, scope wise they are not same.

In the first example, variable i is the global variable and can be accessed throughout the program. But in the second example the scope of i is local to the for loop only, thus i can not be accessed from outside of for loop.

Mamun
  • 66,969
  • 9
  • 47
  • 59
-2

Here is an article that explains the difference between var, let and const.

I gives a great overview of how JS handles variables behind the scenes.

It explains hoisting of variables, scope(which was your question) and how to avoid some pitfalls when using let and const.

Domenik Reitzner
  • 1,583
  • 1
  • 12
  • 21
  • While this link might provide some limited, immediate help, an answer [should include sufficient context around the link](//meta.stackoverflow.com/a/8259) so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, to make it more useful to future readers with other, similar questions. In addition, other users tend to respond negatively to answers which are [barely more than a link to an external site](//meta.stackexchange.com/q/225370), and they [might be deleted](//stackoverflow.com/help/deleted-answers). – Cerbrus May 24 '18 at 07:29
  • @Cerbrus duly noted. – Domenik Reitzner May 24 '18 at 07:33