What Is Scope?

Grade 9, page 1 of 11. A one-minute read.

Here's a mystery for you. Run this code:

JavaScript
function makeSandwich() {
  const filling = "egg";
  console.log(`Making a ${filling} sandwich`);
}

makeSandwich();
console.log(filling);

It prints

Making a egg sandwich
Uncaught ReferenceError: filling is not defined

Inside the function, filling works perfectly. But outside, JavaScript says it doesn't exist. Where did it go?

The answer is scope. A variable's scope is the region of your code where that variable can be seen and used. The variable filling was created inside the function, so it only exists inside the function. Outside, it's invisible.

(Also, it should say "an egg sandwich," not "a egg sandwich." Grammar bugs are bugs too. We'll let it slide.)

Think of it like thisThe house with one-way windows

Imagine your code is a house. The whole house is the global scope. Inside the house, each function is a room with its own door. Inside a room, there might be a closet (a block, like an if or a loop).

The windows in this house are special one-way mirrors. From inside a room, you can see out into the rest of the house. But from outside, you can't see into the room.

So code inside a room can use variables from the hallway, but code in the hallway can't use variables that live inside a room.

Scopes are like rooms inside rooms: you can look out, but not in

Why does JavaScript work this way? Because it keeps things tidy and safe. If every variable were visible everywhere, then a variable called total in your shopping cart code could accidentally clash with a variable called total in your game-score code. Scope lets each part of your program have its own private variables, without worrying about what the other parts are doing.

There are three levels of scope: global, function, and block. Let's tour the house.

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