What is hoisting in JavaScript?

Hoisting is the effect of JavaScript creating every declaration in a scope before running that scope's code, so names exist from the top of the scope even though the code that sets them comes later.

Nothing is physically moved. When the engine enters a scope it first does a setup pass and registers all declarations. What differs is how each kind is initialised:

  • Function declarations are fully initialised with their body. You can call them before the line where they appear.
  • var is initialised to undefined. Reading it early gives undefined, not an error.
  • let, const and class are registered but left uninitialised. Touching them before the declaration line throws a ReferenceError. This window is the temporal dead zone (TDZ).
  • Function expressions and arrow functions follow the rules of the variable that holds them, so var fn = () => {} is undefined early and const fn = ... is in the TDZ.

Why it matters

  • Calling a function declaration before it is defined is legitimate and common (e.g. helper functions at the bottom of a file).
  • Relying on var being undefined early hides bugs. The TDZ exists to turn those silent bugs into loud errors.

Interview tip

Say "declarations are processed before execution" rather than "moved to the top", and explain the TDZ for let/const.

Code example

js
1console.log(sayHi()); // "hi" - function declarations are fully hoisted
2function sayHi() {
3 return "hi";
4}
5
6console.log(count); // undefined - var is hoisted and set to undefined
7var count = 5;
8
9try {
10 console.log(total); // ReferenceError: in the temporal dead zone
11} catch (e) {
12 console.log(e.name); // ReferenceError
13}
14let total = 10;
15
16try {
17 greet(); // TypeError: greet is not a function (it's undefined right now)
18} catch (e) {
19 console.log(e.name); // TypeError
20}
21var greet = function () {
22 return "hello";
23};
24console.log(greet()); // "hello"

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app