What is the Difference Between let
, const
, and var
in JavaScript?
When preparing for JavaScript interviews, one of the most common questions you’ll encounter is about the differences between let
, const
, and var
. Understanding these variable declarations is crucial for writing clean, efficient, and bug-free code.
1. Scope
var
: Function-scoped (visible within the entire function).
let
& const
: Block-scoped (visible only within {}
blocks like if
, for
, etc.).
Example:
if (true) {
var varVar = "I'm var";
let letVar = "I'm let";
}
console.log(varVar); // Works (function-scoped)
console.log(letVar); // Error (block-scoped)
2. Hoisting
var
: Hoisted and initialized as undefined
.
let
& const
: Hoisted but not initialized (Temporal Dead Zone error if accessed early).
Example:
console.log(a); // undefined (var)
console.log(b); // ReferenceError (let/const)
var a = 10;
let b = 20;
3. Reassignment & Redeclaration
var
: Can be redeclared and updated.
let
: Can be updated but not redeclared.
const
: Cannot be updated or redeclared (must be initialized).
Example:
var x = 1; var x = 2; // Allowed
let y = 1; let y = 2; // Error
const z = 1; z = 2; // Error
4. Best Practices
- Use
const
by default (for immutable values).
- Use
let
for variables that need reassignment.
- Avoid
var
(legacy, prone to scope leaks).
Interview Tip
Interviewers often ask: "Why should you avoid var
?"
Answer: Due to function-scoping and hoisting quirks, var
can lead to unintended bugs, especially in loops and closures.