Here's a mystery for you. Run this code:
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.)
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.
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.