Var vs Let vs Const in JavaScript: When to Use Each
var for function-scoped variables but avoid it due to hoisting and scope confusion. Use let for block-scoped variables that can change, and const for block-scoped variables that should not be reassigned after initialization.Quick Comparison
Here is a quick table comparing var, let, and const on key factors.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Hoisting | Yes, initialized as undefined | Yes, but in temporal dead zone | Yes, but in temporal dead zone |
| Reassignment | Allowed | Allowed | Not allowed |
| Redeclaration | Allowed in same scope | Not allowed in same scope | Not allowed in same scope |
| Use case | Legacy code, avoid new code | Variables that change | Constants or fixed references |
Key Differences
var is function-scoped, meaning it is visible throughout the function it is declared in, regardless of block boundaries like loops or if statements. It is hoisted and initialized as undefined, which can cause bugs if you use it before declaration.
let and const are block-scoped, so they only exist inside the nearest curly braces {}. They are hoisted but not initialized, causing a temporal dead zone that throws an error if accessed before declaration.
The main difference between let and const is that let allows reassignment of the variable, while const does not allow changing the binding after initialization. However, objects declared with const can still have their properties changed.
Code Comparison
function testVar() { console.log(x); // undefined due to hoisting var x = 5; if (true) { var x = 10; // same variable, re-declared console.log(x); // 10 } console.log(x); // 10 } testVar();
let and const Equivalent
function testLetConst() { // console.log(y); // ReferenceError: Cannot access 'y' before initialization let y = 5; if (true) { let y = 10; // different variable, block scoped console.log(y); // 10 } console.log(y); // 5 const z = 20; // z = 30; // TypeError: Assignment to constant variable. console.log(z); // 20 } testLetConst();
When to Use Which
Choose const by default for variables that should not be reassigned. This helps prevent bugs and makes your code easier to understand.
Use let when you need to change the value of a variable, such as counters in loops or values that update.
Avoid var in modern JavaScript because its function scope and hoisting behavior can cause confusing bugs. It is mainly kept for legacy code compatibility.
Key Takeaways
const for variables that never change after assignment.let for variables that need to be reassigned within a block.var due to its function scope and hoisting pitfalls.let and const are block-scoped, making code safer and clearer.const prevents reassignment but does not make objects immutable.