0

The difference between let and var is related to the lexical scoping and variable hoisting. But I have never seen how the values of variables change when passed as a parameter. Example below:

for(let i =1; i<=5; i++){
  setTimeout(
    ()=>{ console.log(i) }, 
    i*1000)
}

prints the output [1,2,3,4,5] every second.

But when using var

for(var i =1; i<=5; i++){
  setTimeout(
    ()=>{ console.log(i) }, 
    i*1000)
}

prints [6, 6, 6, 6, 6] every second.

vincent mathew
  • 4,278
  • 3
  • 27
  • 34
  • When using `let` in `for(let i =1; i<=5; i++)`, it creates a new `i` for each iteration of the loop that is scoped to just that iteration of the `for` block. When using `var`, there is only one variable `i` that is shared by all iterations. This is especially important when you insert a closure inside the loop and that closure executes later AFTER the `for` loop index has changed. With `var`, the `setTimeout()` only sees the terminal value of `i` which is `6` in your example. With `let`, each call to `setTimeout()` has it's own value of `i` that is not affected by the rest of the iteration. – jfriend00 Dec 31 '16 at 10:09
  • @jfriend00 Thanks for the answer/comment. This is what I was looking for. But how is this question exact duplicate of http://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable where only scope, hoisting and redeclaration is discussed? – vincent mathew Dec 31 '16 at 10:14
  • 1
    It's just a question about scope which is the fundamental difference between `let` and `var` which is all explained in that other answer. `let` creates a block scoped variable (inside the `for` loop). `var` creates a function scoped variable (one variable for the whole function). – jfriend00 Dec 31 '16 at 10:22

0 Answers0