Skip to the solution
EasyPhone Screen8 min read

What is hoisting in JavaScript?

944 views

The problem

Question presented to candidate: "What is hoisting in JavaScript, and how does it actually behave differently for var, let, const, function declarations, and class declarations?"

What a strong answer should cover:

  • Hoisting means the engine registers every declared name in a scope before executing any code in that scope -- the name exists from the top, even though source reads top to bottom.
  • var declarations are hoisted AND initialized to undefined immediately, so reading a var before its declaration line returns undefined rather than throwing.
  • let, const, and class declarations are hoisted but left uninitialized in the temporal dead zone (TDZ) -- reading any of them before their own declaration line throws a ReferenceError, not undefined.
  • function declarations are hoisted completely, including their body, so they are callable even before the line they are written on; a function EXPRESSION assigned to a var only hoists the var itself (as undefined), never the assignment.
  • Real motivation to state clearly: hoisting is not "moving code around" -- the engine does a scope-analysis pass first, and each declaration form reacts differently to being read before its own line actually runs.

Clarifying questions expected:

  • "Do you want me to also cover class hoisting and the TDZ specifically, or keep this to var versus let and const?"

Code / implementation expected: Yes -- a short, runnable snippet demonstrating each hoisting behavior side by side.

  • hoisting
  • scope
  • variables
  • functions

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

8 min read Β· 8 sections

Run the code

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

JavaScriptHoisting across var, let, function declaration, function expression, and class (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 10 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 are static methods and properties?

Continue