ES6+easy

`var` vs `let` vs `const`

What are the differences between `var`, `let`, and `const`? Cover scoping, hoisting, re-declaration, and the temporal dead zone.

Asked at Amazon, Apple

#var#let#const#scope#tdz

Answer

// Usage
//           var           let             const
// ─────────────────────────────────────────────────────────
// Scope     function      block           block
// Hoisted   yes (undef)   yes (TDZ err)   yes (TDZ err)
// Re-decl   yes           no              no
// Re-assign yes           yes             no (binding)

// var — function scoped, leaks out of blocks
function example() {
  if (true) {
    var x = 1    // accessible outside the if block
    let y = 2    // block-scoped
  }
  console.log(x) // 1
  console.log(y) // ReferenceError
}

// const — binding is constant, object properties can change
const arr = [1, 2, 3]
arr.push(4)   // ✅ mutating is fine
arr = []      // ❌ TypeError: assignment to constant variable

// Temporal Dead Zone (TDZ)
console.log(a) // undefined (var hoisted + init'd)
console.log(b) // ReferenceError (let in TDZ)
var a = 1
let b = 2

// Best practice: default to const, use let when reassignment
// is needed, avoid var in modern code.

Practise more ES6+ questions →