Although i understand that let
allows you to declare variables that are limited in scope to the block, I encountered a strange difference between let
and var
while using it with javascript closures. Here is my example:
With let
:
function buildFunction() {
var arr = [];
for(var i = 0; i < 3; i++) {
let j = i; //Using let to assign j
arr.push(
function(){
console.log(j);
}
)
}
return arr;
}
var fs = buildFunction();
fs[0]();
fs[1]();
fs[2]();
The above code snippet outputs:
0
1
2
With var
:
function buildFunction() {
var arr = [];
for(var i = 0; i < 3; i++) {
var j = i; //Using var to assign j
arr.push(
function(){
console.log(j);
}
)
}
return arr;
}
var fs = buildFunction();
fs[0]();
fs[1]();
fs[2]();
The above code snippet outputs the following:
2
2
2
My question is:
If U am using
var
inside a block and assigning it a value during execution, shouldn't it work exactly like let and store different copies of j in memory ?Does javascript handle
let
andvar
differently within a closure ?
Any clarifications on this would be highly appreciated.