There are three ways to declare variables in JavaScript:
var
let
const
The main differences relate to scope, reassignment, and hoisting.
Feature | var | let | const |
---|---|---|---|
Scope | Function | Block | Block |
Reassignment | Yes | Yes | No |
Redeclaration | Yes | No | No |
Hoisting | Yes (uninitialized) | Yes (but in TDZ) | Yes (but in TDZ) |
Initialization | Can be later | Can be later | Must be immediate |
Temporal Dead Zone is the period between variable creation and its initialization when accessing the variable throws an error.
console.log(a); // ReferenceError
let a = 10;
var
— outdated but still worksfunction testVar() {
if (true) {
var message = "Hello from if";
}
console.log(message); // works! → "Hello from if"
}
let
— preferred for mutable valuesfunction testLet() {
if (true) {
let message = "Hello from if";
console.log(message); // "Hello from if"
}
// console.log(message); // ReferenceError
}
const
— for constantsconst PI = 3.14;
PI = 3.1415; // TypeError: Assignment to constant variable.
Important: const
prohibits changing the reference, not the object it points to:
const user = { name: "Alex" };
user.name = "Ivan"; // This works!
const
by default.let
if you expect to reassign.var
unless maintaining legacy code.function test() {
console.log(a);
var a = 5;
}
test();
{
console.log(b);
let b = 10;
}
let x = 10;
{
let x = 20;
console.log(x);
}
console.log(x);
console.log(typeof undeclaredVar);
console.log(undeclaredVar);
var undeclaredVar = 42;
if (true) {
const a = 5;
}
console.log(a);
let name = "Aleksandr";
let name = "Evgeniya";
Questions about var
, let
, and const
are a classic in interviews.
It’s important not just to memorize but to understand the differences in scope, reassignment, and hoisting.
In real-world development, prefer const
and let
, and avoid var
.
Want more interview prep articles?
Follow EasyAdvice, bookmark the site, and level up every day 💪