Skip to content
IT glossary
FrontendUpdated December 3, 2026

Hoisting

JavaScript declarations can affect code that runs before the line where they appear. This is called hoisting. A function declaration can already be called, a new `var` reads as `undefined`, and reading a `let` or `const` too early causes an error.

Also known as: поднятие

What hoisting means

If a JavaScript function call works even though its declaration appears later in the file, that's hoisting at work. The engine doesn't move lines of source code. Instead, it sets up names for a scope before running the statements in it. Whether you can use a name right away depends on what kind of declaration introduced it and when it gets its value.

Which declarations can you use early?

  • A function declaration such as function greet() {…} gets its function value during scope setup. Code in that scope can call it before reaching the declaration in the source.
  • A new var variable starts out as undefined. The expression after = isn't evaluated until execution reaches that statement. Inside a function, a var belongs to the function's scope, even if it's written inside an if or for block.
  • let, const, and class introduce names that are already in scope but cannot be accessed until initialized. Access during that interval, known as the temporal dead zone (TDZ), throws a ReferenceError. Even typeof throws when applied to a name in the TDZ.

Example: a declaration versus an expression

function run() {
  greet();                  // logs "Hello"
  console.log(handler);     // undefined
  // handler();             // would throw TypeError

  function greet() {
    console.log('Hello');
  }
  var handler = () => greet();
  handler();                // logs "Hello"
}
run();

The declaration makes greet callable from the start. The arrow function, on the other hand, is created only when the expression on the right of = runs. Before then, handler is readable but isn't callable. If you replace var with const, even the early console.log(handler) fails: reading the name now throws ReferenceError before console.log runs.

In everyday code and interviews

Hoisting lets you put a file's main flow first and define helper functions below it. For variables, initialize them before the first use: that keeps readers from having to work out whether an early read gets a value, returns undefined, or throws.

A common interview question is what happens in let x = 1; { console.log(x); let x = 2; }. It throws ReferenceError rather than logging 1. The inner declaration shadows the outer x throughout the block, including while the inner x is still uninitialized. When tracing examples like this, ask two questions in order: which declaration does the name refer to, and has that declaration been initialized yet?