Scope
Where variables live.
A variable made inside a function can't be seen outside it. A variable made inside an if block can't be seen outside the block. Where a variable can be used is called its scope.

- Inside a function
- Inside a block
- Where it can be used: scope
Inside and outside
App name is declared at the top, so it's visible everywhere. Message is declared inside the function, so it only exists in there. And bonus is declared with let inside the if block, so it disappears when the block ends. Run it. Trying to use message outside the function gives a reference error.
const appName = "Notes";
function show() {
const message = `Welcome to ${appName}`;
console.log(message);
}
show();
if (true) {
let bonus = 10;
}
try { console.log(message); }
catch (e) { console.log("Outside:", e.message); }Welcome to Notes Outside: message is not defined
Why scope is good
Scope keeps variables private, so different parts of a program don't clash. Two functions can both use a variable called total, without interfering. A good rule is to declare variables in the smallest scope you can, close to where you use them.
| key | value |
|---|---|
| Global | visible everywhere |
| Function scope | inside the function |
| Block scope | let and const in { } |
| Rule | smallest scope possible |
Summary
Scope decides where a variable can be used. Let and const are block scoped, and function variables stay inside. Next, closures.
Key takeaways- Global vs local
- let/const are block scoped
- Keep scopes small