Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 156 ยท Functions

Scope and Hoisting

Learn where JavaScript variables are visible, how global, function and block scope work, what hoisting really does and why let and const have a TDZ.

Every variable lives somewhere. Its scope is the region of code where the name can be used. Outside that region, the name either means something else or doesn't exist at all. Understanding scope tells you why a variable is "not defined" in one place but fine in another, and it is the foundation for the next lesson, Closures.

This lesson also explains hoisting: JavaScript sets up all the declarations in a scope before it runs any of the code in it. That is why you can call some functions before the line where they are written, and why using a let variable too early throws an error instead of quietly giving you undefined.

The three kinds of scope

JavaScript has three everyday kinds of scope:

  • Global scope โ€” names declared at the top level of a script. Every part of the program can see them.
  • Function scope โ€” names declared inside a function, including its parameters. Only code inside that function can see them.
  • Block scope โ€” names declared with let, const or class inside a pair of curly braces: an if block, a loop body, or a bare { โ€ฆ }. Only code inside that block can see them.

Modules add a fourth: each module file has its own top-level scope, so its variables don't leak into other files.

JS Global, function and block scope

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

No output.

typeof is used here because it is the one way to touch an undeclared name without an error: it just returns "undefined". Writing console.log(note) outside the block would throw ReferenceError: note is not defined.

Lexical scope and the scope chain

JavaScript uses lexical scope: what a piece of code can see is decided by where it is written, not where it is called from. Scopes nest like boxes. When code uses a name, JavaScript looks in the innermost scope first, then the one around it, and so on, out to the global scope. This path is the scope chain. If the name isn't found anywhere, you get a ReferenceError.

JS Looking up the scope chain

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

No output.

report() prints global even though caller() has its own level. The function was written at the top level, so its scope chain goes straight from its own body to the global scope; the caller's variables are not part of it.

Shadowing

When an inner scope declares a name that already exists outside, the inner one shadows the outer one: inside the inner scope, the name refers to the new variable, and the outer one is untouched. Shadowing is legal and sometimes useful, but it can also hide bugs. If you see the same name declared at two levels, consider renaming one.

var ignores blocks

let and const are block-scoped. The older var is function-scoped: it ignores every block except a function body. A var declared inside an if or a loop is visible throughout the whole function.

JS var leaks out of blocks

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

No output.

The loop counter surviving after the loop is a classic source of bugs; you will see the worst version of it in the Closures lesson. This is one of the reasons the Variables lesson recommends never using var in new code.

Globals and the window object

In a classic script (not a module), top-level var declarations and function declarations become properties of the global object, window in browsers. Top-level let, const and class are global variables too, but they are not attached to window:

JS Which globals land on window?

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

No output.

Putting things on window means any other script on the page can overwrite them, and some names (like name, status or top) are already taken by the browser. Fewer globals means fewer collisions. Modules avoid the problem completely, because their top-level variables are private to the file.

Accidental globals. In sloppy (non-strict) code, assigning to a name that was never declared โ€” total = 5 with no let โ€” silently creates a global variable. In strict mode, which modules and classes use automatically, the same line throws a ReferenceError. Always declare your variables.

Hoisting

Before JavaScript runs the code in a scope, it scans that scope for declarations and creates the names up front. This is called hoisting. What a name holds before its declaration line runs depends on how it was declared:

Declaration Hoisted? Value before the declaration line runs
function name() {} Yes The complete function โ€” you can call it
var name Yes undefined
let / const Yes None โ€” reading it throws a ReferenceError
class Name {} Yes None โ€” using it throws a ReferenceError
const f = function () {} or () => {} The variable is (as a const) None โ€” the function isn't assigned yet
JS Hoisting in action

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

No output.

Function declaration hoisting is genuinely useful: you can put the main logic at the top of a file and the helper functions below it. var hoisting, on the other hand, mostly produces confusing undefined values, which is why let and const were designed to fail loudly instead.

The temporal dead zone (TDZ)

A let, const or class name exists from the start of its scope, but it can't be used until the declaration line has run. The stretch in between is called the temporal dead zone. Any access inside it โ€” reading, writing, even typeof โ€” throws a ReferenceError:

JS The temporal dead zone

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

No output.

Notice that the outer theme doesn't help. The inner const theme is hoisted to the top of render(), so from the very first line of the function, theme means the inner variable โ€” which is still in its dead zone. The error message in Chromium-based browsers is "Cannot access 'theme' before initialization"; Firefox and Safari word it differently, but the error type is the same.

The word "temporal" matters: the zone is about time, not position. A function written above a let can safely use it, as long as the function is called after the declaration has run:

JavaScript
function show() {
  console.log(score); // fine when called later
}

let score = 42;
show(); // 42

Simple habits that avoid every hoisting surprise: declare variables with const (or let when you must reassign), declare them at the top of the block where you need them, and don't rely on a variable before its declaration line.

Function declarations inside blocks

A function declaration inside an if block is block-scoped in strict mode and in modules. In sloppy scripts, browsers apply old compatibility rules that also make the function visible outside the block in some cases. The behavior is confusing enough that the best advice is simple: if you need a function only inside a block, write it as const fn = () => { โ€ฆ } in that block.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? if (true) { var a = 1; let b = 2; } console.log(typeof a, typeof b);

    var ignores the block, so a is visible outside it. b is block-scoped, and typeof of an undeclared name is "undefined".
  2. 2. What is printed by console.log(x); var x = 5;?

    The var declaration is hoisted and initialized to undefined; the assignment of 5 only happens when its line runs.
  3. 3. Which of these can you safely call before the line where it is written?

    Only function declarations are hoisted with their body. The var version exists but holds undefined, and the let/const versions are in the TDZ.
  4. 4. JavaScript uses lexical scope. What decides which variables a function can see?

    A function's scope chain is fixed by its position in the code. The caller's local variables are not visible to it.
  5. 5. Which top-level declaration in a classic script creates a property on window?

    Top-level var and function declarations become properties of the global object. let, const and class create globals that are not attached to it.

Summary

  • Scope is where a name is visible: global, function, block, or module scope.
  • Lookups walk outward through nested scopes (the scope chain); scope is decided by where code is written.
  • let, const and class are block-scoped; var is function-scoped and leaks out of blocks.
  • Hoisting creates names before code runs: function declarations are fully usable, var starts as undefined, and let/const/class sit in the temporal dead zone until their line runs.
  • Top-level var and function declarations in classic scripts become window properties; modules keep everything private.

Next: Closures โ€” functions that remember the scope they were created in.