Variables, Scope, and Hoisting

Beginner · 10 min

The real differences between `var`, `let`, and `const`, function vs block scope, and why the temporal dead zone throws instead of returning `undefined`.

Before thisHow JavaScript Code Is Parsed and Executed

Entangled Worlds · 10 min

Variables, Scope, and Hoisting

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Entangled WorldsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `var` is function-scoped (or global if declared outside any function), while `let` and `const` are block-scoped — confined to the nearest `{}` — which is why a `var` declared inside an `if` block leaks out of it, but a `let` declared the same way doesn't.
  • Hoisting means declarations are processed before any code in that scope actually runs — function declarations are hoisted whole and callable before their line in the file, while `var` is hoisted and pre-initialized to `undefined`.
  • `let` and `const` are hoisted too, but without that pre-initialization — the binding exists, but reading it before its declaration line throws a `ReferenceError` instead of quietly returning `undefined`, as a `var` would.
  • The gap between a `let`/`const` binding being hoisted and the line where it's actually initialized is called the temporal dead zone (TDZ) — it exists specifically to turn a likely bug (using a variable before it's meant to exist) into a loud error instead of a silent one.
  • `const` doesn't make a value immutable — it only locks the binding itself against reassignment. A `const` array or object can still have its contents changed; what you can't do is point that same name at a different array or object.

Why scope needs rules at all

Every variable has to live somewhere, and “somewhere” has to have edges — some code that can see it, and some code that can’t. Without that, every variable in a program would be visible to every other line, and a loop counter in one function could silently collide with a loop counter in another. Scope is the answer: the set of rules that decide where a variable is visible from the moment it’s declared. JavaScript’s scoping story is also where its history shows — var reflects an older, looser model, and let/const were added later specifically to tighten it.

Function scope versus block scope

var is scoped to the nearest function (or to the whole script, if it’s declared outside any function). Critically, it does not care about {} on their own — a var declared inside an if block, a for loop, or any other block is still visible throughout the entire enclosing function, not just inside that block. That surprises people who expect curly braces to always mean “contained in here.”

let and const fix that by being block-scoped — genuinely confined to the nearest pair of {}, whatever kind of block that is. This is most of the practical reason modern code reaches for let/const over var: a block-scoped loop variable, an if-only temporary, a try/catch binding — all stay exactly where you’d expect, instead of leaking into code that has no business seeing them.

Hoisting: the engine already knew you declared that

From the previous lesson, you know the engine builds an execution context for each scope before running any code in it. Hoisting is the visible result of that setup phase: the engine scans a scope for every declaration in it before executing a single line, and registers each one. That’s why a function declaration can be called from a line above where it’s written in the file — by the time execution starts, the whole function already exists in that scope, body and all.

var gets the same early treatment, but only partially: the engine registers the name and initializes it to undefined immediately, so reading it early doesn’t throw — it just gives you a placeholder you probably didn’t want.

The temporal dead zone

let and const are hoisted too — the engine knows the name exists before execution reaches it — but they skip the “initialize to undefined” step var gets. Between the top of the scope and the actual declaration line, the binding exists but is deliberately inaccessible; touching it throws a ReferenceError instead of handing back undefined. That window is the temporal dead zone, and it’s a deliberate safety net: using a variable before its declaration is almost always a mistake, and a loud error catches it immediately instead of letting a silent undefined cause a confusing bug three lines later. The video walks through this exact mechanism visually — the creation phase, the TDZ, and how var/let/const diverge inside it — which is why it’s the pick here over a shorter clip that only covers the “let throws, var doesn’t” surface behavior without the execution-context reasoning behind it.

const locks the binding, not the value

“Constant” is a slightly misleading name. const only prevents the name from being reassigned to point at something else — it says nothing about whether the thing it points at can change. A const array can still have elements pushed onto it; a const object can still have its properties updated. What throws is only numbers = [] — rebinding the name itself — never numbers.push(4).

Where this fits

This lesson is what strict mode builds on next — several of strict mode’s behavior changes exist specifically to catch scope-related mistakes (like assigning to an undeclared variable) that non-strict JavaScript would otherwise allow silently. It also sets up closures later in the roadmap, since a closure is really just a function that keeps a live reference to variables from a scope that, by the rules covered here, should otherwise have disappeared.

Check yourself

  1. 01A `var` is declared inside an `if` block. Can you read it right after the block, outside the `{}`? What about a `let` declared the same way?

    Yes for `var` — it's function-scoped (or global), so the block's curly braces don't contain it; it's visible anywhere in the enclosing function. A `let` declared the same way is block-scoped, so it only exists inside that `if` block's `{}` and referencing it afterward throws a `ReferenceError` because the name doesn't exist in that outer scope at all.

  2. 02Why does reading a `let` variable before its declaration line throw an error, while reading a `var` the same way just gives you `undefined`?

    Both are hoisted — the engine knows about the declaration before it runs that line. But `var` is hoisted *and* initialized to `undefined` immediately, so reading it early just gets that placeholder value. `let` and `const` are hoisted without being initialized; the time between the hoist and the actual declaration line is the temporal dead zone, and accessing the binding during that window throws rather than returning a placeholder.

  3. 03Can you call a function before the line where it's declared in the file? Does the same thing work for a function expression assigned to a `const`?

    A function *declaration* (`function greet() {}`) is hoisted whole — not just its name but its entire body — so it's fully callable from anywhere in its scope, even before its line in the file. A function *expression* assigned to a `const` or `let` (`const greet = function() {}`) only has the variable binding hoisted, not the assignment, so calling it before that line throws — either a TDZ error (`let`/`const`) or a "not a function" error if it were `var` (since the variable would just be `undefined` at that point).

  4. 04Does `const numbers = [1, 2, 3]; numbers.push(4);` throw an error? Why or why not?

    No — it works fine, and `numbers` ends up as `[1, 2, 3, 4]`. `const` only prevents *reassigning* the binding `numbers` to point at a different array entirely (`numbers = []` would throw). It says nothing about mutating the contents of whatever that binding currently points at, so pushing to the array, or changing a property on a `const` object, is completely legal.

  5. 05What has to happen in a scope before any of its code actually executes, and why does that matter for hoisting?

    The engine runs a creation phase for that scope first — scanning it for declarations and setting up bindings for every `var`, `let`, `const`, and function before executing a single statement. Hoisting is just the visible effect of that phase: declarations appear to be "moved to the top" because the engine already registered them before execution began, even though nothing in the source was physically relocated.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark