0
0
JavascriptComparisonBeginner · 4 min read

Var vs Let vs Const in JavaScript: When to Use Each

Use 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.

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
HoistingYes, initialized as undefinedYes, but in temporal dead zoneYes, but in temporal dead zone
ReassignmentAllowedAllowedNot allowed
RedeclarationAllowed in same scopeNot allowed in same scopeNot allowed in same scope
Use caseLegacy code, avoid new codeVariables that changeConstants 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

javascript
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();
Output
undefined 10 10
↔️

let and const Equivalent

javascript
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();
Output
10 5 20
🎯

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

Use const for variables that never change after assignment.
Use let for variables that need to be reassigned within a block.
Avoid 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.