Welcome back
In JavaScript for Beginners you wrote functions, loops, arrays, and objects. This course is about how JavaScript actually works underneath, the material interviews are made of. Scope is the right place to start because half the bugs you will debug at work come down to which variable a line of code is actually touching, and closures (next lesson) — the mechanism behind every event handler, debounce, and React hook — are nothing but these scope rules applied carefully.
First term: scope, the set of variables a piece of code can see. JavaScript uses lexical scope: what a function can see is decided by where it is written in the source code, not where it is called from.
A function written inside another function can read the outer function's variables:
function outer() { const secret = "level 1"; function inner() { console.log(secret); // inner can see outer's variables } inner(); }
Code exercise · javascript
Run it. `inner` never declares `secret`, yet it prints it. It reads it from the scope it was written inside.
The scope chain
When JavaScript needs a variable, it looks in the current function first. Not there? It steps outward to the enclosing function, then outward again, all the way to global scope. This path is the scope chain.
Two rules to memorize:
- Lookup only goes outward, never inward.
outercannot read variables declared insideinner. - If two scopes declare the same name, the closest one wins (this is called shadowing).
Code exercise · javascript
Run it. Two different variables share the name `name`. Inside `greet`, the closest declaration wins (shadowing), so the same word refers to different variables on different lines. The outer variable is untouched.
Quiz
Inside `inner()` you declare `const temp = 1`. Can code in `outer()` (outside `inner`) read `temp`?
Code exercise · javascript
Your turn. Three nested functions: make `innermost` print the string `"a b c"` by reading one variable from each level. No new variables, just combine `a`, `b`, and `c` with spaces.