So I know the difference between LET and VAR is that var keyword/statement declares function scoped variables, while let declares block scoped variables, but when mixed with hoisting mechanism, it turns out that var is limited ONLY to function-scope hardcore.
Is my understanding correct?
Code example:
var x = 100; //or 'let', this line doesn't affect the output.
function hoist() {
if (false) {
var x = 200; //this 'x' is INTERRUPTING the variable declaration of the outer scope OR re-declaring it.
}
console.log(x);
}
hoist(); //prints out undefined.
VS when let is used even inside blocks “}” of the if statement… in my own words: “X will be declared to the top of the global context, but initialized(/defined), of course, upon that particular function’s call”. Am I correct?
Code modified:
var x = 100; //or 'let', this line doesn't affect the output.
function hoist() {
if (false) {
let x = 200; //modified 'var' into 'let'.
}
console.log(x);
}
hoist(); //prints: 100
WoW, ok so I dived so deep (adele is rolling here) which is beyond what juniors out there working in a company rn know, and should perhaps just refer to let over var.
…
Which also means prior to ES6 (introduction to let and const) CLOSURE was not a thing ?
Since it will cause weird errors as:
function parent() {
var x = 100;
function child() {
if (false) {
var x = 200;
}
console.log(x);
}
child()
}
parent(); //prints undefined
Ok, I am at Adele’s concert on Titanic.