Problem Statement
Explain the differences between var, let, and const with examples. When should you use each?
Explanation
Variable declared with var Has function scope. Accessible anywhere within the function, even outside blocks. This causes variable leaking.
Is hoisted and initialized as undefined. You can access it before declaration.
Can be redeclared in the same scope without errors.
Variable declared with let:
Has block scope. Only exists within curly braces. This prevents variable leaking.
Is hoisted but not initialized. Stays in Temporal Dead Zone. Accessing before declaration throws ReferenceError.
Cannot be redeclared in the same scope. Prevents accidental overwrites.
Variable declared with const:
Has block scope, just like let.
Is hoisted but not initialized, stays in Temporal Dead Zone.
Cannot be redeclared or reassigned. Value is locked.
Important: You can modify properties of const objects or add elements to const arrays. Const prevents reassignment, not mutation.
When to use each:
Use const by default for 90 percent of variables. This includes objects and arrays whose contents you will modify.
Use let when the value will change, like loop counters or calculations that update.
Never use var in modern JavaScript. It causes problems and is banned in many companies.
Code Solution
SolutionRead Only
// VAR - function scoped (old way, avoid this)
function testVar() {
console.log(x); // undefined (hoisted)
var x = 10;
if (true) {
var x = 20; // Same variable! (overwrites)
}
console.log(x); // 20 (changed everywhere)
}
// LET - block scoped (modern way)
function testLet() {
// console.log(y); // ReferenceError (TDZ)
let y = 10;
if (true) {
let y = 20; // Different variable (block scoped)
console.log(y); // 20
}
console.log(y); // 10 (unchanged)
}
// CONST - cannot reassign
const PI = 3.14;
// PI = 3.15; // Error! Cannot reassign
// But can modify object contents
const person = { name: 'John' };
person.name = 'Jane'; // OK! Modifying property
person.age = 30; // OK! Adding property
// person = {}; // Error! Cannot reassign
const numbers = [1, 2, 3];
numbers.push(4); // OK! Modifying array
// numbers = []; // Error! Cannot reassign
// WHEN TO USE WHAT
// Use const (default choice)
const API_URL = 'https://api.example.com';
const users = [];
const config = { timeout: 5000 };
// Use let (when value changes)
let score = 0;
score += 10;
score -= 5;
for (let i = 0; i < 5; i++) {
console.log(i);
}
// NEVER use var (causes problems)
if (true) {
var leaked = 'I escaped!';
}
console.log(leaked); // Works but BAD
// Loop problem with var
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3 (all share same i)
// Fixed with let
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 0, 1, 2 (each has own i)