var, let, and const in JavaScript
Understanding the differences between var
, let
, and const
is fundamental to writing modern JavaScript. This knowledge is essential for interviews and daily development.
Variable Declarations Overview
JavaScript provides three ways to declare variables:
var
- Function-scoped, hoisted, can be redeclaredlet
- Block-scoped, hoisted but not initialized, cannot be redeclaredconst
- Block-scoped, hoisted but not initialized, cannot be redeclared or reassigned
Scope Differences
Function Scope (var)
function example() {
if (true) {
var x = 1;
}
console.log(x); // 1 - accessible outside the block
}
// Global scope
var globalVar = 'I am global';
Block Scope (let/const)
function example() {
if (true) {
let x = 1;
const y = 2;
}
console.log(x); // ReferenceError: x is not defined
console.log(y); // ReferenceError: y is not defined
}
// Block scope in loops
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 3, 3, 3
}
Hoisting Behavior
Var Hoisting
console.log(x); // undefined (not ReferenceError)
var x = 5;
console.log(x); // 5
// Equivalent to:
var x;
console.log(x); // undefined
x = 5;
console.log(x); // 5
Let/Const Hoisting (Temporal Dead Zone)
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;
console.log(y); // ReferenceError: Cannot access 'y' before initialization
const y = 10;
Redeclaration
Var - Can be redeclared
var name = 'John';
var name = 'Jane'; // No error
console.log(name); // 'Jane'
Let/Const - Cannot be redeclared
let name = 'John';
let name = 'Jane'; // SyntaxError: Identifier 'name' has already been declared
const age = 25;
const age = 30; // SyntaxError: Identifier 'age' has already been declared
Reassignment
Var/Let - Can be reassigned
var count = 0;
count = 1; // OK
let total = 0;
total = 1; // OK
Const - Cannot be reassigned
const PI = 3.14159;
PI = 3.14; // TypeError: Assignment to constant variable
Const with Objects and Arrays
const person = { name: 'John', age: 30 };
person.age = 31; // OK - modifying property
person.city = 'NYC'; // OK - adding property
// person = { name: 'Jane' }; // Error - cannot reassign
const numbers = [1, 2, 3];
numbers.push(4); // OK - modifying array
numbers[0] = 10; // OK - modifying element
// numbers = [4, 5, 6]; // Error - cannot reassign
Global Object Properties
Var creates global object properties
var globalVar = 'I am global';
console.log(window.globalVar); // 'I am global' (in browser)
console.log(global.globalVar); // 'I am global' (in Node.js)
Let/Const do not create global object properties
let globalLet = 'I am not global';
const globalConst = 'I am not global';
console.log(window.globalLet); // undefined (in browser)
console.log(global.globalConst); // undefined (in Node.js)
Practical Examples
Loop with Closures
// Problem with var
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 3, 3, 3
}
// Solution with let
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
// Alternative solution with var (IIFE)
for (var i = 0; i < 3; i++) {
(function(j) {
setTimeout(() => console.log(j), 100); // 0, 1, 2
})(i);
}
Switch Statement
function getValue(type) {
switch (type) {
case 'A':
let result = 'Type A';
break;
case 'B':
let result = 'Type B'; // SyntaxError with let
break;
default:
let result = 'Unknown'; // SyntaxError with let
}
return result;
}
// Solution: Use block scope
function getValue(type) {
let result;
switch (type) {
case 'A':
result = 'Type A';
break;
case 'B':
result = 'Type B';
break;
default:
result = 'Unknown';
}
return result;
}
Best Practices
1. Use const by default
// Good
const API_URL = 'https://api.example.com';
const user = { name: 'John', age: 30 };
// Only use let when you need to reassign
let count = 0;
count++; // Reassignment needed
2. Avoid var in modern JavaScript
// Avoid
var oldStyle = 'deprecated';
// Prefer
let modernStyle = 'preferred';
const constantValue = 'immutable';
3. Use meaningful names
// Good
const MAX_RETRY_ATTEMPTS = 3;
const userPreferences = { theme: 'dark' };
// Avoid
const x = 3;
const data = { theme: 'dark' };
Common Interview Questions
- What's the difference between
var
andlet
? - What is the Temporal Dead Zone?
- Can you reassign a
const
variable? - What happens when you declare a variable without
var
,let
, orconst
? - How does hoisting work with different variable declarations?
- What's the scope of variables declared in different ways?
Related Topics
- Closures
- Scope Chain
- Temporal Dead Zone
- Hoisting
- Global Object
- Block Scope vs Function Scope