var, let, and const

easy

Complete guide with examples and interview questions · 25 min

Definition

Say it out loud in an interview — clear, simple, no textbook wording.

If someone asks the difference between var, let, and const, I'd say var is the old one — it ignores blocks and leaks to the whole function, and it's initialized to undefined even before its line runs. let and const are block-scoped and were added to fix exactly that.

The trap interviewers love is the temporal dead zone: let and const are hoisted too, but reading them before the declaration line throws a ReferenceError. "It's hoisted, just uninitialized" is the senior version of the answer.

Senior rounds also probe the loop trap — for (var i ...) with async callbacks sees the final value every time, because closures capture the variable, not a copy of its value. Swapping to let gives each iteration its own binding. That's the one to have rehearsed.

Quick Stats
25
Minutes
easy
Difficulty
4
Interview Q's

Key takeaways

  • var is function-scoped and initialized to undefined on hoist; let and const are block-scoped and throw in the temporal dead zone
  • Reading a let or const before its declaration throws a ReferenceError — that is the TDZ, not "not hoisted"
  • Closures capture the variable, not its value — the var loop plus setTimeout prints the final value every time
  • const locks the binding, not the contents — push into a const array all day, but never reassign it
  • Default to const, reach for let when the value genuinely changes, and don't write new var

Track your mastery

Sign in to save Q&A scores, coding challenge progress, points, and streaks across devices.

Sign in to save progress