JavaScript provides three ways to declare variables: var, let, and const. Understanding their differences is crucial for writing clean, bug-free code.
var – function-scoped, can be re-declared and updated, and is hoisted.let – block-scoped, can be updated but not re-declared in the same scope.const – block-scoped, cannot be re-assigned or re-declared. Commonly used for constants.var → function scope.let and const → block scope ({ }).var can be re-declared in the same scope.let and const cannot be re-declared in the same scope.var and let can be re-assigned.const cannot be re-assigned.var is hoisted and initialized with undefined.let and const are hoisted but stay in the “temporal dead zone” until the declaration line.All three keywords follow the basic pattern:
var name = value;let name = value;const NAME = value;In modern JavaScript, you will mostly use let and const. var mainly appears in older codebases or when you specifically need function-scoped behavior.
var is function-scoped and allows re-declaration within the same function. Changes inside a block like if affect the same variable.
function testVar() {
var x = 10;
if (true) {
var x = 20; // same variable!
console.log(x); // 20
}
console.log(x); // 20
}
testVar();
let creates a new variable for each block. An inner let does not overwrite the outer one.
function testLet() {
let x = 10;
if (true) {
let x = 20; // new variable, separate from the outer one
console.log(x); // 20
}
console.log(x); // 10
}
testLet();
const must be initialized and cannot be re-assigned. It is still block-scoped like let.
const PI = 3.14;
PI = 3.14159; // ❌ Error: Assignment to constant variable
When the value is an object or array, the binding is constant, but the contents are still mutable.
const person = { name: "Alice" };
person.name = "Bob"; // ✅ Allowed
console.log(person.name); // Bob
testVar():
if block, x becomes 20 and logs 20.x is still 20, so it logs 20 again.testLet():
if block, the inner x is 20, so it logs 20.x is still 10, so it logs 10.const PI:
PI causes a runtime error: “Assignment to constant variable”.const person object:
person still refers to the same object.person.name from "Alice" to "Bob" is allowed and logs Bob.const by default. Switch to let only when you truly need to reassign a variable.var in modern code unless necessary for legacy browser support.let and const) to avoid accidental leaks into outer scopes.const values that never change (for example, MAX_USERS, API_URL).let and try to re-declare it in the same scope. Observe the error you get.var inside a function and see how it behaves across if blocks.const to declare an object and try changing one of its properties.var and let. Compare the results.