<aside>
💡 This document covers understanding var, let, and const in JavaScript. It includes the concepts of variable shadowing, illegal shadowing, hoisting, and the temporal dead zone.
</aside>
Notes:
let a inside the if block shadows the outer let a, and they are two separate variables despite having the same name.Example:
function test() {
let a = "Hello"; // Outer variable
if (true) {
let a = "Hello World"; // Inner variable shadows the outer one
console.log(a); // Prints "Hello World"
}
console.log(a); // Prints "Hello"
}
test();
Explanation:
test, a variable a is declared and assigned the value "Hello".if block, another variable a is declared with let, which is only accessible within the block. This shadows the outer a.console.log(a) inside the block prints "Hello World" because it refers to the inner a.console.log(a) outside the block prints "Hello" because it refers to the outer a.Notes:
var within the same scope where that variable is already defined using let or const.var b = "Bye"; is illegal shadowing because b is already declared using let in the same scope.