Sub topic 1
What Scope Means in JavaScript
Scope is the region of code where a name is visible. JavaScript uses lexical scope, which means visibility depends on where you write a declaration in the source code. Where a function is called has no effect. Once you know which scope a name belongs to, you can predict which value any line of code will read.
Prerequisites
This chapter assumes you already know how to:
- Read basic JavaScript syntax.
- Declare variables with
var,let, andconst. - Write and call functions.
- Use
ifstatements andforloops. - Run code in a browser console or Node.js.
The Four Levels of Scope
| Scope | Created by | Holds |
|---|---|---|
| Global | The script itself | Top-level declarations |
| Function | Each function body | `var`, `let`, `const`, parameters |
| Block | Any `{ }` block | `let`, `const`, `class` only |
| Module | Each ES module file | Top-level module declarations |
Global Scope
The global scope holds names declared outside any function or block. Every part of a program can read them. That makes it easy to overwrite a global by accident, so keep as few names there as you can.
Function Scope
Each call to a function creates a new scope. Names declared inside the function, including var declarations, cannot be seen from outside it.
Block Scope with let and const
let and const are limited to the nearest enclosing block. var ignores blocks and attaches to the enclosing function or script.
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(typeof b); // "undefined" (b is not visible here)How the Scope Chain Resolves Names
When code reads a name, the engine looks in the current scope first. If the name is not there, it checks the enclosing scope, then the one around that, and so on until it reaches the global scope. This sequence of scopes is called the scope chain. The search stops at the first match it finds. If no scope has the name, a ReferenceError is thrown.
const level = "global";
function outer() {
const level = "outer";
function inner() {
return level;
}
return inner();
}
console.log(outer()); // "outer"
console.log(level); // "global"inner has no level of its own. The lookup finds level in outer and stops there, so it never reaches the global level.
Exercise
If you delete the line const level = "outer"; from the example, what does outer() return, and why?
Show answer
It returns "global". The lookup for level fails in inner and then in outer, so it continues to the global scope and finds level there.