Every now and then I see this keyword and it surprizes me about its scope. I hope and pray I will never use it anywhere. But understanding legacy code is also my job sometimes. So here goes my effort to understand this shit.
var scope is immediate function. let scope is immediate curly braces
function prog() {
for (var i = 1; i < 4; i++) {
console.log(i);
} // 1 2 3
console.log(i); // 4
}
prog();
function prog() {
for (let i = 1; i < 4; i++) {
console.log(i);
} // 1 2 3
console.log(i); // error
}
prog();
if you have used var you don't nee to declare it before using it. If you declare it even at end it will be considered declared with undefined
console.log(a); //undefined
var a = 1;
console.log(a); // 1
console.log(a); //ReferenceError:: Cannot access 'a' before initialization
let a = 1;
console.log(a);
for (let i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
// output: 0 1 2 3 4
I hope you don't use var :(
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
// output: 5 5 5 5 5
There are some other weird behaviors but I don't want to get overloaded understanding all of these cases: Just read them here https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var
