Skip to the solution
EasyPhone Screen7 min read

What are let, const, and var? What are their differences?

614 views

The problem

Question presented to candidate: "Walk me through var, let, and const -- what does each one actually do differently in terms of scope, hoisting, and reassignment?"

What a strong answer should cover:

  • var is function-scoped (or global at the top level) and ignores block boundaries like if and for; let and const are block-scoped, confined to the nearest curly-brace block.
  • All three are hoisted, but var is initialized to undefined immediately, while let and const are hoisted into the temporal dead zone and throw ReferenceError if read before their declaration line.
  • var can be redeclared in the same scope without error; let and const throw a SyntaxError on redeclaration in the same scope.
  • let allows reassignment; const throws TypeError on any reassignment of the binding, but does not make the referenced value itself immutable -- a const array or object can still be mutated.
  • At the top level of a script (not a module), var attaches itself as a property of the global object; let and const do not.

Clarifying questions expected:

  • "Should I also cover the temporal dead zone in detail, or just the block-versus-function scope distinction?"
  • "Do you want the classic var-in-a-loop-closure example as part of this?"

Code / implementation expected: Yes -- a short, runnable snippet demonstrating hoisting, the TDZ, redeclaration rules, and reassignment rules for all three.

  • variables
  • scope
  • es6
  • hoisting

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read Β· 8 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptvar, let, const: hoisting, TDZ, redeclaration, and reassignment (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 18 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What is the difference between null and undefined?

Continue