Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Function

Hoisting

Reference for JavaScript hoisting: how function, var, let, const and class declarations are processed before code runs, and the temporal dead zone.

Hoisting describes how JavaScript processes declarations before it runs any code in a scope. Before execution, the engine scans the scope and creates bindings for the names that are declared there. That is why you can call some functions before the line where they are written, and why using a variable too early gives surprising results.

The code is not physically moved. What differs between declaration kinds is how far the binding is initialized at that moment.

Try it

JS Functions and var

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS let, const and the temporal dead zone

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What gets hoisted

Declaration Binding exists early? Value before the line runs
function name() {} Yes The complete function, so you can call it early.
var x Yes undefined. Only the declaration is hoisted, not the assignment.
let / const Yes, but uninitialized Reading it throws a ReferenceError.
class Yes, but uninitialized Using it throws a ReferenceError.
import Yes Imports are hoisted and resolved before the module body runs.
Function expression (var f = function () {}) As var undefined, so calling it throws a TypeError.

The temporal dead zone

For let, const and class, the time between entering the scope and reaching the declaration is called the temporal dead zone (TDZ). In that period the name exists but cannot be read or written. The last example shows that the binding is hoisted: the inner level shadows the outer one for the whole block, so the early console.log(level) does not print "outer"; it throws.

Usage notes

  • Function declarations in blocks have different rules in sloppy mode and strict mode. In strict mode and modules they are block scoped. Avoid depending on this.
  • A function declaration beats var with the same name during hoisting, but a later assignment overwrites it.
  • Parameters are initialized before the body runs, so a var of the same name in the body starts with the parameter's value.
  • typeof is not always safe: typeof undeclared is "undefined", but typeof on a TDZ binding throws.
  • Style advice: declare variables at the top of their scope, prefer const and let, and write function declarations before use for readability, even though hoisting lets you reorder them.
  • Strict mode does not change hoisting, but it forbids undeclared assignments that would otherwise create globals.

Browser support

Hoisting is core language behavior and is the same in every engine. The TDZ for let, const and class is available in all current browsers.