var vs let vs const — JS Technical Interview Questions & Answers

Scope, hoisting and re-assignment differences.

var vs let vs const

  • Scope, hoisting and re-assignment differences.
  • let can be reassigned. const cannot be reassigned (objects inside const can still change fields). var is old: function-scoped, hoisted in a messy way — don’t use it in new code.
  • let marks = 40; marks = 72; const name = 'Asha'; // name = 'Kabir' throws. Prefer const until you must reassign.
  • Trap: const arr = []; arr.push(1) is allowed (the array changed, the binding didn’t). Trap: var in a for-loop with listeners.

Technical Interview Tip: const name = 'Asha'; let marks = 40; no var.

Code Examples for var vs let vs const

var vs let vs const — working example

function demo() {
  if (true) {
    var a = 1;
    let b = 2;
    const c = 3;
    console.log(b, c);
  }
  console.log(a); // 1 — var is function-scoped
  // console.log(b); // ReferenceError — let is block-scoped
}
demo();
console.log(typeof undeclaredVar); // undefined (never declared with let/const)

var vs let vs const — var is function-scoped and hoisted; let/const are block-scoped. Prefer const, then let.

How to Explain var vs let vs const to an Interviewer

let vs const vs var?

let reassign const no reassign var = don’t in new code