All 28 lessons ▾
Inside JavaScript · Lesson 4 of 28
Every Function Call Gets Its Own Box: Variable Environment
Here's a puzzle. The same variable name, in three different places. Which value does JavaScript print? Let's run it line by line, and find out together.
Got a doubt? Ask in the comments under the video.Subscribe
- Every function call gets a new execution context
- Each context has its own memory: its variable environment
- The same name in different functions: different variables
- JavaScript looks in the local memory first
- When a function returns, its box and its variables are deleted
- The global context lives until the program ends
Part 1Same name, three places
Today's question is a tricky one. What happens when the same variable name lives in many places? In the global code, and inside two different functions. Which one does JavaScript use? Let's find out. And whatever we learn today will help you a lot with scope and closures later.
1var city = "Delhi";2showHome();3showOffice();4console.log(city);5 6function showHome() {7 var city = "Pune";8 console.log(city);9}10 11function showOffice() {12 var city = "Bengaluru";13 console.log(city);14}Pune Bengaluru Delhi
Here's our program. A variable city, which is Delhi. Then we call two functions, showHome and showOffice, and then we log city. Now look inside the functions. Each one has its own var city! Pune in one, and Bengaluru in the other. The same name, three times. So what will this print? Let's run it. First, the global execution context is created, and pushed onto the call stack. Phase one. city gets undefined. And both functions are stored whole.
Now phase two. Line one. city becomes Delhi. Line two calls showHome. And you know what happens now. A brand new execution context is created for showHome, and pushed on top of the stack. Now listen carefully, because this is the key point of this whole episode. This new box has its own memory. Its own variable environment. So when phase one runs inside showHome, it creates a brand new city. A completely separate variable. It's not the global city. It just has the same name. And it starts as undefined.
The arrow jumps to line seven, and city becomes Pune. Line eight, console.log city. Now which city does JavaScript look at? It looks in the local memory first, the memory of this execution context. It finds Pune right there. So the console prints Pune. And now showHome is done, so its whole execution context is deleted, and popped off the stack. Its city is gone with it.
Back in global, line three calls showOffice. The same story again. A brand new context is pushed, with its own city, starting as undefined. Line twelve, and city becomes Bengaluru. Line thirteen logs city, finds it in its own local memory, and prints Bengaluru. Done, and popped.
Finally, line four. console.log city, in the global code. Now which city is it this time? JavaScript looks in the global memory, and city there is still Delhi. Nobody touched it! So it prints Delhi. And the program ends, so global is popped too, and the call stack is empty.
So remember this. Every execution context has its own memory, its own variable environment. Three boxes, three different variables called city. They just share a name. Each function looks at its own city first, and the global city stays safe.
Here's the whole picture in one place. The global box has city equals Delhi, and it lives till the very end. showHome got its own box, with city equals Pune, and that box was deleted the moment the function returned. The same with showOffice and Bengaluru. Separate boxes, separate memories. That's the variable environment of each execution context.
Let me give you a picture to remember this. Think of a hotel. The lobby is the global context. It's there all day. Every guest who checks in gets a room, with their own cupboard. Two guests can both keep a blue shirt in their cupboards, and nobody gets confused, because each shirt is in its own room. Another guest, another room. And when a guest checks out, the room is cleared. That's exactly a function call. Its own room, its own cupboard, cleared when it returns.
Part 2Parameters live there too
Now, one more thing people often miss. What about parameters?
1var city = "Delhi";2greet("Mumbai");3 4function greet(city) {5 console.log("Hi from " + city);6}Hi from Mumbai
Look at this. The function greet takes a parameter, and its name is city too. Global is pushed, and phase one runs first, as always. Line one, city becomes Delhi. Line two calls greet with Mumbai. A new execution context is pushed. And here's the thing. A parameter is just a variable in the function's own memory. So this city, the parameter, gets Mumbai, right inside greet's own box. Line five looks in the local memory, finds Mumbai, and prints hi from Mumbai. Then greet is popped, and its city is gone. The global city? Still Delhi. Same rule, every time.
Part 3See it in your browser
Now, you don't have to trust my drawings. You can see all of this happening in your own browser.
Open your browser's developer tools, and go to the sources tab. Put a breakpoint inside showHome, and run the page. Now look at the call stack panel. You'll see showHome sitting on top of the global context, which shows up as anonymous. And in the scope panel, you'll see two memories. The local one, with its city, and the global one, with its own city. Step forward, and watch showHome disappear from the call stack. It's the same story we just drew, happening for real. Try it, it's a lot of fun.
Part 4Why this matters
And why should you care about this? Because this one idea is the base of two big topics coming up.
And here's a quick peek at what's coming. What if a function logs city, but it never created its own city? Then JavaScript doesn't find city in the local memory, so it looks outside, in the memory around it, and finds the global one. That looking outside has a name, the scope chain. It's a whole story of its own, so we'll do it properly in episode seven. For now, just remember. Local memory first, always.
Because each function has its own memory, a variable inside a function can't leak out and break the rest of your code. That's the start of scope, which we'll see in episode seven. And later, when a function remembers its memory even after it returns, that's closures, in episode ten. Everything builds on today's idea.
1var food = "dosa";2 3function lunch() {4 var food = "biryani";5}6 7lunch();8console.log(food);What does the last line print?
Show the answer
Lunch has its own food, biryani, sitting in its own box. And that box is deleted the moment lunch returns. The global food was never touched. So the last line prints dosa. Did you get it right? Then you've really understood today's idea. If you said biryani, no problem. Just watch the cities part one more time, and it will click.
If showHome wanted to change the global city, how would you write it?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.