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
📒
Subscribe to my newsletter
Read articles from Abhishek Dandriyal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Abhishek Dandriyal
Abhishek Dandriyal
Frontend Developer , I design and code user-friendly and responsive web applications and projects using,HTML5 , React /Redux MUI . I collaborate with backend developer, UI/UX designers, and project managers to deliver high-quality products that meet the clients' needs and expectations.