Javascript Scope: Var, Let and Const

Javascript Scope: Var, Let and Const

Variable shadowing:

In JavaScript, variable shadowing occurs when a variable with the same name as a variable in a higher scope is declared in a lower scope, potentially causing confusion;

let a = 10; 
if (true) { 
let a = 20; 
console.log(a); 
} 

// Output: 20

Illegal shadowing:

This happens when attempting to shadow a variable using var within the same scope where it's already defined using let or const;


let b = "Hi"; 

{ var b = "Bye"; 

} // SyntaxError: Identifier 'b' has already been declared

Hoisting:

JavaScript's behavior where variable and function declarations are moved to the top of their scope during compilation, without initializing them;

console.log(a); 

var a = 10; // Output: undefined

Temporal Dead Zone (TDZ):

A specific behavior for let and const variables, referring to the period between block scope start and variable declaration, causing a ReferenceError if accessed in this zone;

console.log(a); 

let a = 10; // ReferenceError: Cannot access 'a' before initialization

📒