JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 10: Scope and JavaScript BehaviorLesson 49 of 150About 40 minutes

Lesson 49: Hoisting and the temporal dead zone

01Opening question

You can call a function declared at the bottom of a file from the top, but using a const before its line throws. Why the difference?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Function declarations are ready before any code runs; const and let are not usable until their line.

console.log(add(2, 3));
function add(a, b) {
  return a + b;
}
try {
  console.log(total);
} catch (e) {
  console.log(e.message);
}
const total = 10;

03Objective and prerequisites

Learning objective: Explain hoisting for function declarations, var, let, const and function expressions, and recognise the temporal dead zone.

You need: Lesson 46: Global, function and block scope, Lesson 16: For loops

Skills practised: Hoisting and the TDZ.

04Explanation

Before running a scope, JavaScript first registers every declaration in it. This is called hoisting.

Function declarations are hoisted completely, so you can call them before the line where they are written.

var variables are hoisted but start as undefined, so reading one early gives undefined instead of an error.

let and const are hoisted too, but cannot be used before their declaration line. The time between the start of the scope and that line is the temporal dead zone (TDZ); touching the variable there throws a ReferenceError.

05Definitions

Hoisting
Declarations being registered at the start of their scope before code runs.
Temporal dead zone
The period before a let, const or class declaration runs, when accessing it throws a ReferenceError.
Function declaration
A statement starting with function name(...) { }, hoisted with its body.
Function expression
A function created as a value, e.g. const f = function () {}, which follows the variable's hoisting rules.

Open the full glossary

06Visual learning object

Hoisting and temporal dead zone explorer. Step through a script and see each name's state: ready, undefined, or in the temporal dead zone.

Loading the interactive object…

Open the full Hoisting and temporal dead zone explorer page with its guided experiment.

07Examples

ex-049-01Function declarations are hoisted Browser-executable JavaScript

You can call them before their line.

console.log(formatPrice(4.5));
function formatPrice(n) {
  return `$${n.toFixed(2)}`;
}
Sample input
None
Expected output
$4.50
Common mistake
Assuming every function can be called early; only declarations can.
Try this
Change it to a const arrow function and run again.
Source
examples/ex-049-01-function-hoisting.js (repository pending publication)

ex-049-02var starts as undefined Browser-executable JavaScript

The declaration is hoisted; the assignment is not.

console.log(stock);
var stock = 12;
console.log(stock);
Sample input
None
Expected output
undefined 12
Common mistake
Relying on this behaviour; it hides ordering mistakes.
Try this
Replace var with let and observe the error.
Source
examples/ex-049-02-var-undefined.js (repository pending publication)

ex-049-03The temporal dead zone Browser-executable JavaScript

let and const throw if used before their line.

try {
  console.log(discount);
} catch (e) {
  console.log(e.name + ": " + e.message);
}
const discount = 0.1;
console.log(discount);
Sample input
None
Expected output
ReferenceError: Cannot access 'discount' before initialization 0.1
Common mistake
Moving code around and accidentally reading a const before it is declared.
Try this
Use typeof discount inside the try and see that it still throws.
Source
examples/ex-049-03-tdz.js (repository pending publication)

ex-049-04Function expressions are not hoisted as functions Browser-executable JavaScript

With var, the name exists but is undefined.

try {
  greet();
} catch (e) {
  console.log(e.name + ": " + e.message);
}
var greet = function () {
  return "hi";
};
console.log(greet());
Sample input
None
Expected output
TypeError: greet is not a function hi
Common mistake
Expecting a function assigned to var to be callable early.
Try this
Change var to const and compare the error.
Source
examples/ex-049-04-expression-early.js (repository pending publication)

ex-049-05The TDZ is about time Browser-executable JavaScript

A function may mention a const declared later, as long as it is called after.

function showLimit() {
  return `Limit: ${limit}`;
}
const limit = 5;
console.log(showLimit());
Sample input
None
Expected output
Limit: 5
Common mistake
Calling showLimit() above the const line, which throws.
Try this
Move the console.log above the const and predict the result.
Source
examples/ex-049-05-tdz-is-time.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the early call

Order code so a const function is defined before use.

console.log(double(21));
const double = (n) => n * 2;

Predict the hoisting

Record what each early access produces.

function early() { return "declaration"; }
var v = "var";
let l = "let";
// TODO: set answers to what these early accesses would produce:
// console.log(early())  before its line -> ?
// console.log(v)        before its line -> ?
// console.log(l)        before its line -> ?
const answers = ["?", "?", "?"];
console.log(answers.join(" | "));

Safe initialisation order

Structure code so nothing is used in its TDZ.

// Write the program described in the instructions

09Prediction

Commit to an answer first, then run the real code to compare.

console.log(typeof a, typeof b);
var a = 1;
function b() {}

What is printed?

10Debugging investigation

The page fails after moving start-up code

After moving start() to the top of the file, loading fails with "Cannot access 'TITLE' before initialization".

const message = start();
function start() {
  return `Welcome to ${TITLE}`;
}
const TITLE = "Shop";
console.log(message);

More cases in the Debugging Detective Laboratory

11Practical scenario

Reordering a file

During a refactor, a developer moves a block of start-up code to the top of a file. Function declarations still work, but a const helper is now used inside its temporal dead zone and the page fails to load. Declaring before use keeps refactors safe.

function start() {
  return render("Home");
}
const render = (page) => `<h1>${page}</h1>`;
console.log(start());

12Knowledge check

1. What is printed?

console.log(f());
function f() { return "ok"; }
  • ok
  • undefined
  • A ReferenceError
  • A TypeError

2. What is printed?

console.log(x);
var x = 5;
  • 5
  • undefined
  • A ReferenceError
  • null

3. What is the temporal dead zone?

  • Code after a return
  • The time before a let/const/class declaration runs
  • A scope with no variables
  • Variables that were deleted

4. Why does this throw TypeError: init is not a function?

init();
var init = () => "ready";
  • init is a var holding undefined until its line
  • init is misspelled
  • Functions cannot be called at the top
  • Arrow functions need return

5. What is printed?

function show() { return "Limit " + max; }
const max = 3;
console.log(show());
  • Limit 3
  • A ReferenceError
  • Limit undefined
  • undefined

6. Which habit avoids hoisting surprises?

  • Use var everywhere
  • Declare variables and functions before using them
  • Call every function before declaring it
  • Wrap everything in try/catch

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the early call: Prints 42; Still an arrow const
  • Predict the hoisting: Prints the answers
  • Safe initialisation order: Prints both; Uses DEFAULTS; Function declaration
  • ex-049-01: output matches the documented expected output
  • ex-049-02: output matches the documented expected output
  • ex-049-03: output matches the documented expected output
  • ex-049-04: output matches the documented expected output
  • ex-049-05: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-10-scope-and-javascript-behavior/lesson-049-hoisting-and-the-temporal-dead-zone/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Declarations are registered before code runs.
  • Function declarations are fully hoisted.
  • var is hoisted as undefined.
  • let, const and class throw in their temporal dead zone.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation hoisting and the temporal dead zone
Context: I am learning hoisting and the temporal dead zone in JavaScript.
Task: Explain hoisting for function declarations, var, let and const, and the temporal dead zone, with short examples.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction hoisting and the temporal dead zone drill
Context: I have practised hoisting and the temporal dead zone.
Task: Give me six snippets that use names before their declarations and ask what each prints or throws.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging hoisting and the temporal dead zone bug
Context: I get ReferenceError: Cannot access before initialization after moving code.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation hoisting and the temporal dead zone practice
Context: I finished the hoisting and the temporal dead zone exercises.
Task: Create three exercises about declaration order.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review hoisting and the temporal dead zone review
Context: Here is my code that uses hoisting and the temporal dead zone.
Task: Review my file for code that depends on hoisting and suggest a clearer order.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.