JavaScript Variables .. Var vs Let
he var and let keywords in JavaScript are used to declare variables, but they have some important differences in terms of scope, hoisting, and re-declaration. Here's a detailed comparison:
1. Scope
var
- Function Scope: Variables declared with
varare function-scoped. This means they are only accessible within the function they are declared in. - Global Scope: If declared outside of a function, they become properties of the global object (window in browsers).
function varTest() { var x = 1; if (true) { var x = 2; // same variable console.log(x); // 2 } console.log(x); // 2 } varTest();
let
- Block Scope: Variables declared with
letare block-scoped. They are only accessible within the block they are declared in (e.g., inside{}braces).
function letTest() { let x = 1; if (true) { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 } letTest();
2. Hoisting
var
- Hoisting: Variables declared with
varare hoisted to the top of their scope, but their initialization is not hoisted. This means the declaration is moved to the top, but the assignment stays in place.
console.log(y); // undefined var y = 5;
let
- Temporal Dead Zone (TDZ): Variables declared with
letare also hoisted, but they are not initialized until their definition is evaluated. Accessing them before the declaration results in aReferenceError.
console.log(z); // ReferenceError: z is not defined let z = 5;
3. Re-declaration
var
- Re-declaration Allowed: Variables declared with
varcan be re-declared within the same scope.
var a = 1; var a = 2; console.log(a); // 2
let
- No Re-declaration: Variables declared with
letcannot be re-declared within the same scope. This prevents accidental re-declarations and potential bugs.
let b = 1; let b = 2; // SyntaxError: Identifier 'b' has already been declared
4. Use in Loops
var
- When used in loops,
vardoes not create a new scope for each iteration. All iterations share the same variable.
for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); // 3, 3, 3 }, 1000); }
let
- When used in loops,
letcreates a new scope for each iteration, capturing the current value of the variable.
for (let j = 0; j < 3; j++) { setTimeout(function() { console.log(j); // 0, 1, 2 }, 1000); }
Summary
- Scope:
varis function-scoped, whileletis block-scoped. - Hoisting: Both are hoisted, but
varinitializes toundefined, andletthrows aReferenceErrorif accessed before declaration. - Re-declaration:
varallows re-declaration within the same scope, butletdoes not. - Loops:
letcreates a new scope for each iteration in loops, whilevardoes not.
In modern JavaScript development, it is generally recommended to use let (and const for constants) instead of var due to its more predictable scoping and behavior.
