Functions and scope

What is hoisting in JavaScript?

Learn what hoisting means in JavaScript: how the engine moves declarations into memory, and why function declarations can be called before they are defined.

Before JavaScript runs your code, it scans it and registers declarations in memory. That registration step is hoisting.

Function declarations and function expressions behave differently. My advice is still the same: define things before you use them so the source order matches what you expect.

Suppose you have this function:

function bark() {
  alert('wof!')
}

Because of hoisting, you can call it above its definition in the file:

bark()
function bark() {
  alert('wof!')
}

That works for function declarations only.

This is a function expression assigned to var:

bark()
var bark = function() {
  alert('wof!')
}

The name bark hoists as undefined, so the call throws TypeError: bark is not a function. The engine effectively does:

var bark = undefined
bark()
bark = function() {
  alert('wof!')
}

With const or let, the binding hoists but stays uninitialized until its line:

const bark = function() {
  alert('wof!')
}

Calling bark() before that line gives ReferenceError: Cannot access 'bark' before initialization.

The same pattern applies to class declarations. Using a class before its declaration raises ReferenceError.

Run the three bark examples in order in the console. The three different errors tell you which kind of declaration you are dealing with.

Hoisting explains odd undefined reads with var, but it is not an excuse to write code out of order. I still declare before use so the file reads the way it runs.

Class declarations follow the same temporal dead zone rules as const and let.

Import declarations are hoisted too, but that matters mostly when you split modules across files. In a single script, function declarations are the hoisting example people notice first.

Run the three bark examples in order in the console. The three different errors tell you which kind of declaration you are dealing with.

Lesson completed