Scope, Hoisting & Closures

Who can see what, and the function that never forgets. Eleven short pages from Grade 9 of High School, about 14 minutes of reading in all.

What you’ll learn

  • What scope is and why it exists
  • Global, function and block scope
  • Why var leaks out of blocks
  • Shadowing: when names collide
  • The scope chain
  • Hoisting and the \

The pages

Eleven pages, about 14 minutes.

  1. What Is Scope? Here's a mystery for you. Run this code. Inside the function, filling works perfectly. But outside, JavaScript says it…
  2. Global Scope: The Hallway A variable created outside of any function or block lives in the global scope. It can be seen from everywhere in your…
  3. Function Scope: Your Bedroom Variables created inside a function (including the function's parameters) can only be seen inside that function…
  4. Block Scope: Your Closet Variables created with let or const inside any pair of curly braces (an if block, a loop, or even just a plain { }…
  5. Why var Leaks Out of Blocks Remember Grandpa's old box, var, from Grade 1? We said it had some quirks related to scope. Here's the biggest one…
  6. Shadowing: When Names Collide What happens if an inner scope creates a variable with the same name as one in an outer scope? Inside the function…
  7. The Scope Chain When JavaScript sees a variable name, how does it find the right box? It follows a simple rule: start in the current…
  8. Hoisting Here's a strange one. Look at this code, which calls a function before it's defined. How does that work? JavaScript…
  9. Closures: Functions With Backpacks Now we get to one of the most powerful (and famous) ideas in JavaScript. It has a slightly scary name, closures, but…
  10. Mini Project: The Secret Vault Let's use closures to build a password-protected vault that locks itself after three wrong guesses. The password and…
  11. Recap The key ideas of Grade 9, JavaScript scope and closures, on one page. Scope is where a variable can be seen and used…

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning