Skip to the page

Scope, hoisting and closures · core

Scope, the scope chain and strict mode

Scope is decided by where code is written (lexical scope): a variable lookup starts in the current block or function and walks outward through the enclosing scopes to the global scope, and strict mode turns silent mistakes into errors.

The notes

What you must know

  • Kinds of scope: global, module, function and block. let, const and class are block-scoped; var ignores blocks and is function-scoped.
  • A lookup walks the scope chain outward from where the function was written, not from where it is called. This is lexical scope (this is different: it depends on the call).
  • Shadowing: an inner variable with the same name hides the outer one inside that scope.
  • In sloppy mode, assigning to an undeclared name creates a global variable. In strict mode it throws ReferenceError.
  • Strict mode: this is undefined in plain function calls, writing to read-only properties throws, duplicate parameter names are errors, with is banned. ES modules and class bodies are always strict.
  • An IIFE, (function () { ... })(), creates a private scope. function foo() {}() fails because a line starting with 'function' is a declaration, not an expression. ES modules replaced most IIFE use.
  • globalThis works in browsers, workers and Node. In a classic script, top-level var and function declarations become properties of window; top-level let and const do not.

The red pen

Common traps: mistake → fix

  • Mistake: Scope depends on where a function is called

    Fix: that is this; scope is fixed by where the code is written.

  • Mistake: A block creates scope for var

    Fix: var is function-scoped and leaks out of if and for blocks.

  • Mistake: You must write 'use strict' in modules

    Fix: modules and classes are strict automatically.

Easy to hard

Questions interviewers ask, easy to hard

  1. What kinds of scope does JavaScript have?
  2. What is the scope chain? Show shadowing with an example.
  3. Why does function foo(){}() throw? Make it a working IIFE.
  4. Name three things strict mode changes.
  5. Why should a third-party widget or a micro-frontend never add global variables? How do you isolate it?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview