Hoisting

Published by Brayan K

Ever called a function above where you wrote it and wondered why it still worked? Or logged a var before assigning it and gotten undefined instead of an error? That's hoisting — JavaScript's two-phase way of preparing each scope before running it.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Ask what exists before the first statement runs

Hoisting is a name for observable declaration behaviour, not a command that moves lines in your file. A scope prepares its bindings before its statements run, but different declarations make different things available. Keep three questions separate: does the name belong to this scope, has it been initialised, and what value does it currently hold?

console.log(double(4));
function double(value) {
  return value * 2;
}

// ✅ Expected output:
// 8

The function declaration makes its function value available before the earlier call. Its body still runs only when called. This is a rule you can use to read the program; it is not a claim that every JavaScript engine literally executes a simple two-pass implementation. Functions owns parameters, return values and function syntax.

A var binding exists before its initializer runs

A var declaration prepares a binding with undefined. Its initializer is evaluated when execution reaches that statement. The value you assign later is not available early just because the declaration is.

console.log(quantity);
var quantity = 4;
console.log(quantity);

// ✅ Expected output:
// undefined
// 4
function initialQuantity() {
  console.log("initializer ran");
  return 4;
}
console.log("before", quantity);
var quantity = initialQuantity();
console.log("after", quantity);

// ✅ Expected output:
// before undefined
// initializer ran
// after 4

The call in the initializer stays at its written execution point. If an earlier calculation reads the undefined value, JavaScript may continue with an unwanted result instead of throwing a declaration error.

var total = quantity * 3;
var quantity = 4;
console.log(total);
console.log(quantity * 3);

// ✅ Expected output:
// NaN
// 12

Put the required initialization before the calculation. Hoisting explains why the mistaken program runs; it does not make the earlier total update when quantity changes. A plain variable holds its assigned value, not a live formula.

Uninitialised let and const bindings reject early reads

Let and const also establish bindings for their scope, but those bindings cannot be read before their declaration is evaluated. That interval is the temporal dead zone. An early access throws a ReferenceError instead of returning undefined.

console.log(quantity);
let quantity = 4;

// ✅ Expected error:
// ReferenceError: Cannot access 'quantity' before initialization
console.log(unitPrice);
const unitPrice = 3;

// ✅ Expected error:
// ReferenceError: Cannot access 'unitPrice' before initialization
let quantity;
console.log(quantity);
quantity = 4;
console.log(quantity);

// ✅ Expected output:
// undefined
// 4

There is a difference between an uninitialised binding and an initialised binding whose value is undefined. The declaration without an initializer completes initialization when reached. Const requires an initializer; Variables and Data Types owns choosing declarations for ordinary values.

typeof cannot bypass the temporal dead zone

The typeof operator has a special case for a name that has no binding: it can report a type string without throwing. That exception does not apply to an existing lexical binding that is still uninitialised.

console.log(typeof missingQuantity);

// ✅ Expected output:
// undefined
console.log(typeof quantity);
let quantity = 4;

// ✅ Expected error:
// ReferenceError: Cannot access 'quantity' before initialization

Check for a same-named declaration in the surrounding scope when typeof unexpectedly throws. Changing a direct read into typeof will not fix initialization order. The wider rules for which binding a name refers to belong to Scope & var/let/const (TDZ).

A function value assigned to a variable follows that variable

A function declaration and a variable initialized with a function expression are different forms. In the second form, the function value is created and assigned when execution reaches the initializer. With var, an early call tries to call undefined.

console.log(typeof double);
console.log(double(4));
var double = function (value) {
  return value * 2;
};

// ✅ Expected output:
// undefined

// ✅ Expected error:
// TypeError: double is not a function

With const or let, the early read of the variable fails before JavaScript can even attempt the call. The error tells you which stage was reached.

console.log(double(4));
const double = value => value * 2;

// ✅ Expected error:
// ReferenceError: Cannot access 'double' before initialization
const double = value => value * 2;
const triple = function (value) {
  return value * 3;
};
console.log(double(4));
console.log(triple(4));

// ✅ Expected output:
// 8
// 12

Choose a form for its clarity and behaviour, then respect its initialization rules. Replacing function with an arrow during a refactor can change whether an earlier call is valid, even if the body calculates the same result.

A ready function can still read a value too early

Preparing a function does not initialize every variable that its body might read. The relevant moment is when the function body executes. An early call can reach a later const while that binding is still in its temporal dead zone.

console.log(totalFor(2));
const unitPrice = 3;
function totalFor(quantity) {
  return quantity * unitPrice;
}

// ✅ Expected error:
// ReferenceError: Cannot access 'unitPrice' before initialization
const unitPrice = 3;
console.log(totalFor(2));
function totalFor(quantity) {
  return quantity * unitPrice;
}

// ✅ Expected output:
// 6

The function declaration can stay below the call because its value is prepared in advance. The const initializer must execute before the body reads it. Closures and Scope owns how functions retain access to surrounding bindings after creation.

Check which binding an early read actually targets

A declaration can change name resolution throughout its scope, including before its initializer. In this example, the function-local var hides the outer value; the early read uses the local binding. Scope & var/let/const (TDZ) owns shadowing, block scope and function scope in detail.

const label = "outer";
function inspectLabel() {
  console.log(label);
  var label = "local";
  console.log(label);
}
inspectLabel();
console.log(label);

// ✅ Expected output:
// undefined
// local
// outer

When an early value is surprising, identify the binding first and its initialization point second. Do not infer that an outer value is being used merely because the local declaration appears further down the function.

A duplicate declaration can prevent execution entirely

Some declaration mistakes are syntax errors rather than failures at an executed read. Two let declarations for the same name in the same scope are rejected before this complete program starts, so even the first log does not run.

console.log("starting");
let quantity = 2;
let quantity = 3;

// ✅ Expected error:
// SyntaxError: Identifier 'quantity' has already been declared

Correct the declaration conflict before investigating runtime order. These examples keep declarations inside one program; separate browser scripts, modules and developer-console entries have additional context. JavaScript Modules: ES6 Imports, Exports, Bundling owns module boundaries.

Complete the initialization order

The function declaration is already available to the call, but the data it reads must be initialized first. Fill the two blanks so the call uses a unit price of three and a quantity of four.

const unitPrice = ___; // 👉 replace ___ with 3
console.log(totalFor(___)); // 👉 replace ___ with 4
function totalFor(quantity) {
  return quantity * unitPrice;
}

// ✅ Expected output:
// 12

Repair a call that runs before configuration is ready

A program needs a prefix of "Order" and an order number of 17. Write those constants, call makeLabel with the number, and place the function declaration below the call. The function should join the prefix, a space and the number. Keep the data initialization before the call, then explain why moving only the function declaration would not repair an early read of prefix.

const prefix = "Order";
const orderNumber = 17;
console.log(makeLabel(orderNumber));
function makeLabel(number) {
  return prefix + " " + number;
}

// ✅ Expected output:
// Order 17

To diagnose a use-before-initialization error, trace the call that first reads the binding, not only the location of the function text. Moving a call below its required data often expresses the dependency more clearly than changing a declaration to var.

References: MDN describes hoisting terminology, var initialization, and the temporal dead zone.

Practice quiz

What does this complete program print? console.log(count); var count = 7; console.log(count);

  • undefined 7
  • 7 7
  • ReferenceError: count is not defined
  • undefined undefined

Answer: undefined 7. The var binding starts as undefined; the initializer runs only when execution reaches it.

What does this complete program print? console.log(double(3)); function double(value) { return value * 2; }

  • undefined
  • 6
  • TypeError: double is not a function
  • ReferenceError: double is not defined

Answer: 6. The function declaration makes the function value available before the earlier call.

Which error ends this program? console.log(count); let count = 7;

  • ReferenceError: count is not defined
  • TypeError: count is not a function
  • ReferenceError: Cannot access 'count' before initialization
  • SyntaxError: Missing initializer in const declaration

Answer: ReferenceError: Cannot access 'count' before initialization. The binding exists but is uninitialised, so the early read is a temporal-dead-zone error.

Which error ends this program? console.log(typeof count); const count = 7;

  • ReferenceError: count is not defined
  • TypeError: Assignment to constant variable.
  • SyntaxError: Identifier 'count' has already been declared
  • ReferenceError: Cannot access 'count' before initialization

Answer: ReferenceError: Cannot access 'count' before initialization. typeof does not bypass the temporal dead zone of an existing lexical binding.

What does this complete program print? let count; console.log(count);

  • undefined
  • 0
  • ReferenceError: count is not defined
  • null

Answer: undefined. Once the let declaration has executed without an initializer, its value is undefined.

Which error ends this program? console.log(double(3)); var double = value => value * 2;

  • ReferenceError: double is not defined
  • TypeError: double is not a function
  • ReferenceError: Cannot access 'double' before initialization
  • SyntaxError: Unexpected token '='

Answer: TypeError: double is not a function. The var binding currently holds undefined, so attempting to call it throws a TypeError.

What does this complete program print? const unit = 4; console.log(total(2)); function total(count) { return count * unit; }

  • undefined
  • NaN
  • 8
  • ReferenceError: Cannot access 'unit' before initialization

Answer: 8. The function is available early and its required unit value is initialized before the call.

What does this complete program print? const label = "outside"; function inspect() { console.log(label); var label = "inside"; } inspect();

  • outside
  • inside
  • ReferenceError: label is not defined
  • undefined

Answer: undefined. The local var binding shadows the outer binding for the function and begins as undefined.

Continue this course

Related lessons