JavaScript lesson · 16 min
JavaScript Scope
Understand where variables are visible and why block scope prevents confusing bugs.
What you will practice
- Understand global and block scope.
- Avoid using a variable outside the place where it exists.
- Use local variables to keep code predictable.
What this means
Scope means the area of code where a name can be used. A variable does not automatically exist everywhere.
Variables created with `let` and `const` inside curly braces usually belong only to that block. A block can be an `if` statement, a loop, or any pair of `{ }` braces.
Scope protects code from accidental name collisions. Two small parts of a program can use the same variable name without stepping on each other if the names live in different scopes.
If this is your first time seeing this
Scope answers the question: where can this variable be seen?
If a variable is created inside a block, code outside that block usually cannot use it.
Mini glossary
- Scope
- The part of code where a name is available.
- Block
- Code wrapped in curly braces.
- ReferenceError
- An error that often happens when a name does not exist in the current scope.
Example from everyday life
Scope is like rooms in a house. A note on the kitchen counter is easy to see while you are in the kitchen, but someone in the office does not automatically see it. If everyone used one giant wall for every note, the house would become chaos quickly.
How it works step by step
- The code creates `status` in the outer scope, so the whole example can use it.
- Inside the `if` block, the code creates `detail`. That name exists only inside that block.
- The code builds the final message while it is still inside the block.
- Outside the block, the program prints the message but does not try to use `detail` directly.
Where you will use this
- A form submit handler creates temporary validation details that should not leak into the rest of the page.
- A loop uses a temporary item name for each row it processes.
- A component keeps local values private so other components do not accidentally change them.
Before you run the code
Good scope habits make bugs easier to find. When a variable exists only where it is needed, fewer lines of code can accidentally change it.
If you see a `ReferenceError`, one common cause is trying to use a variable outside its scope.
Common beginner mistakes
- Creating a variable inside an if block and trying to use it outside.
- Reusing the same name in too many scopes.
- Putting everything in global scope, where it can be changed by too much code.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Try logging `detail` outside the block and read the error.
- Move `const detail` above the if block and compare behavior.
- Create another block with its own `detail` variable.