Differences Between var, let and const
In JavaScript there are three keywords for declaring variables: var, let and const. They differ in scope, ability to redefine values and hoisting mechanism.
var
- Scope: Function scope. Variables declared with
varare accessible throughout the function, even if declared inside a block. - Hoisting:
varvariables are hoisted — their declaration is moved to top of function, but initialization remains in place. - Redefinition: Can redefine and redeclare the same variable in same scope.
Example with var:
function example() {
console.log(a); // undefined, variable hoisted but value not assigned yet
var a = 10;
if (true) {
var a = 20; // redefining variable in same function
console.log(a); // 20
}
console.log(a); // 20
}
example();
let
-
Scope: Block scope. Variables declared with
letare only accessible inside the block where they're declared (e.g., inside curly braces{}). -
Hoisting:
letis also hoisted but stays in "Temporal Dead Zone" until initialization. -
Redefinition: Cannot redeclare variable with same name in same scope.
Example with let:
function example() {
// console.log(b); // Error: cannot access before initialization (ReferenceError)
let b = 10;
if (true) {
let b = 20; // new variable, local to if block
console.log(b); // 20
}
console.log(b); // 10
}
example();
const
- Scope: Block scope, like let.
- Hoisting: const is also subject to hoisting and temporal dead zone until initialization.
- Redefinition: Variables declared with const cannot be redefined or redeclared. However, an object declared with const can be mutated if its structure allows changes.
Example with const:
function example() {
const c = 10;
// c = 20; // Error: Assignment to constant variable.
if (true) {
const c = 30; // new variable in local scope
console.log(c); // 30
}
console.log(c); // 10
const obj = { name: "Alice" };
obj.name = "Bob"; // Allowed: object property changes
console.log(obj.name); // "Bob"
// obj = {}; // Error: cannot reassign variable
}
example();
Main Differences
| Characteristic | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Hoisted with undefined | Temporal Dead Zone until initialization | Temporal Dead Zone until initialization |
| Redeclaration | Allowed | Forbidden in same scope | Forbidden in same scope |
| Value change | Allowed | Allowed | Reassignment forbidden (but object mutation possible) |