All 28 lessons ▾
Inside JavaScript · Lesson 7 of 28
Scope, the Scope Chain and Lexical Environment
So, a function prints a variable it never created. How does it find it? Where does it look, and in what order? So today we learn scope, and the scope chain.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- Scope: where a variable can be accessed
- Lexical environment: local memory + the parent's reference
- The parent is where a function is written
- Scope chain: search up, parent by parent, to global
- The closest variable wins; the outside can't see in
- Reached null and still not found: not defined
Part 1Where can I use this variable?
So today's topic is one of the most important topics in JavaScript. Scope. And if you get scope right, closures, which come a little later, will feel super easy. So let's start with a simple program, and a simple question.
1function kitchen() {2 console.log(owner);3}4 5var owner = "Asha";6kitchen();Asha
So here's our program. A function kitchen, that logs owner. And a global variable owner. Global is pushed, and phase one stores kitchen, and owner as undefined. Line five, owner becomes Asha. Line six calls kitchen, and a brand new execution context is created for it. Now line two logs owner. But wait. kitchen has no owner in its own memory. Its memory is empty! So what happens? Does it print undefined? Is it an error? No. It prints Asha. Then kitchen is done, and it's popped. So how did kitchen find owner? That's what this whole episode is about.
So first, what is scope? Scope simply means, where in your code can you access a variable? Now you'll hear it asked two ways. What is the scope of this variable? Or, is this variable in the scope of that function? Both mean the same thing. So can kitchen access owner? Yes, we just saw it. Can the global code access something inside a function? We'll see. And in JavaScript, scope is directly tied to a fancy-sounding thing called the lexical environment. Don't worry, it's simpler than it sounds. So let's break it down.
Part 2The lexical environment
Now remember, every function call gets its own execution context, with its own memory. Now here's the new part. Along with its memory, every execution context also gets something extra.
Every execution context gets a lexical environment. And a lexical environment is just two things. Its own local memory, plus a reference to the lexical environment of its parent. That's it. Now, what does lexical mean? It means, in order, in hierarchy. Where the code is physically written. So the parent of a function is the place where that function is written. Not where it's called. Remember this, it's going to matter a lot.
1var wifi = "home123";2 3function house() {4 var key = "blue-key";5 room();6 7 function room() {8 console.log(wifi);9 console.log(key);10 }11}12 13house();So let's take a bigger program. A global variable wifi. A function house, with its own key. And inside house, another function, room. Now look at where things are written. room is written inside house. So room's lexical parent is house. And house is written in the global space. So house's lexical parent is global. And global? It's the top. It has no parent. Its parent is null. So room, inside house, inside global. That's the hierarchy.
So here's the call stack while room is running, like in episode two. Global at the bottom, house above it, and room on top. And each one keeps a link to its parent's environment. So now, room runs line eight, and logs wifi. Where does JavaScript look? First, in room's own local memory. Is wifi here? No. So it follows the link to room's parent, house. Is wifi in house? No. So it follows the link again, to house's parent, global. Is wifi in global? Yes! It's found, and it prints home123. And key? Same story. Not in room, so it goes up to house, and finds blue key right there. Now if something isn't even in global, JavaScript reaches null, the end of the chain, and that's when you get not defined.
So this chain of lexical environments has a name. The scope chain. Remember this. When JavaScript looks for a variable, it checks the local memory first. Not there? Then the parent's. Then the parent's parent. All the way up to global. If it finds the variable, it uses it. If it reaches null, it's not defined. So the scope chain is just this chain of links, one parent at a time.
Now here's a picture to make it stick. You need some sugar. First, you check your own kitchen. That's the local memory. Not there? You check your family's house, the parent. Still no sugar? You go to the society shop, the global scope. And if it's nowhere, you give up, that's not defined. But now notice one thing. You never go into the neighbour's house, even if they live right next door. They're not your parent. So the scope chain works exactly like this.
And you can see the scope chain with your own eyes. So put the word debugger inside room, open the developer tools, and run the page. It pauses right there. Now look at the panel called Scope. You'll see Local, that's room's own memory. Then Closure, house, that's room's parent. And then Global. So that list is the scope chain, exactly the way we drew it! And did you notice that word, closure? Keep it in mind. It's coming very soon, and you already know half of it.
Part 3Three more cases
Now let's test this rule with three more cases. Each one teaches you something new, so watch closely.
1var wifi = "home123";2 3function room() {4 var wifi = "guest-wifi";5 console.log(wifi);6}7 8room();guest-wifi
So case one. What if room has its own wifi? Line eight calls room, and room's memory now has its own wifi, guest wifi. Line five logs wifi. Now JavaScript checks the local memory first, finds guest wifi right there, and stops looking. It never goes up to the global one. So it prints guest wifi. The closest one always wins.
1function house() {2 var key = "blue-key";3}4house();5 6console.log(key);ReferenceError: key is not defined
Now case two. Can the global code read a variable from inside a function? Line four calls house, and key lives in house's memory. Then line six, in the global code, logs key. So JavaScript looks in global memory. No key. And global's parent is null, so there's nowhere else to look. We get an error. key is not defined. So the chain only goes up. An inner function can see outer variables, but the outer code can never see inside a function.
1var place = "global";2 3function show() {4 console.log(place);5}6 7function run() {8 var place = "run";9 show();10}11 12run();global
And now case three. This one is a favourite in interviews. So line twelve calls run, and run has its own place, run. Then line nine calls show. show runs line four and logs place. Now think. show was called from inside run. So will it print run? No! It prints global. Now remember what lexical means. show is written in the global space, so its parent is global, not run. So the chain follows where a function is written, never where it's called from.
So remember this rule. Scope depends on where a function is written in your code, not where it's called. That's why it's called lexical scope, or static scope. So you can tell the scope of any variable just by reading the code, without running it. That's a superpower when you're debugging.
Part 4Quiz and recap
So quick quiz first. Pause the video, and think.
1var team = "blue";2 3function outer() {4 var team = "red";5 function inner() {6 console.log(team);7 }8 inner();9}10 11outer();So what does inner print?
Show the answer
Inner has no team of its own. So it looks up to its parent, which is outer, because inner is written inside outer. And outer has team equals red. Found! So it prints red. It never even reaches the global blue. Did you get red? Then you've really understood the scope chain. Well done!
Did case three surprise you?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.