All 28 lessons ▾
Inside JavaScript · Lesson 9 of 28
Block Scope and Shadowing
Curly braces. You write them all the time. But did you know they create their own little world for let and const? So today, block scope, and shadowing.
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
- A block groups statements in curly braces
- let and const are block-scoped; var is not
- Shadowing: an inner name hides the outer one
- With var, the block overwrites the outer value
- With let and const, the outer value is safe
- var shadowing let across a block: SyntaxError
Part 1What is a block?
So before we talk about block scope, we need to answer a simple question. What exactly is a block? Now you've been writing blocks since your first day of coding, maybe without knowing their name. So let's see.
1if (isRaining) takeUmbrella();2 3if (isRaining) {4 takeUmbrella();5 wearBoots();6}So look at the first line. An if statement expects one single statement after it. Here, takeUmbrella. One thing, so no braces needed. Now what if you want to do two things when it's raining? Take an umbrella, and wear boots. JavaScript still expects one statement. So we wrap both inside curly braces. Now these two statements are grouped together, and JavaScript treats the whole group as one statement. And that group, inside curly braces, is a block.
So remember this. A block is a group of statements inside curly braces, used wherever JavaScript expects just one statement. Its official name is a compound statement. If blocks, for loops, while loops, they all use blocks. And even a pair of curly braces on its own, with nothing before it, is a perfectly valid block. Now, what happens to variables inside a block? That's the interesting part.
Part 2Block scope
So let's put a var, a let, and a const inside a block, and watch where each one lives. Watch the memory very carefully.
1{2 var coins = 10;3 let lives = 3;4 const level = 1;5}6console.log(coins);7console.log(lives);10 ReferenceError: lives is not defined
In phase one, coins is a var, so it goes into the global memory, with undefined. Now the code enters the block. And observe, the block gets its own separate memory. lives and level are hoisted right there, in the block's memory, locked in their dead zone. Line two, coins becomes ten, up in global. Line three, and lives gets its value. Line four, and level gets its value too. Now the block closes, and its memory is gone, with lives and level inside it. Line six logs coins, and it prints ten. Fine, it's global. But line seven logs lives. And we get an error. lives is not defined. It only existed inside the block.
So, what is block scope? It's simply what you can access inside a block. And remember this. let and const are block scoped. They live in the block's own memory, and they can't be accessed outside the block. But var doesn't care about blocks at all. A var inside a block escapes, and lives in the outer scope, like global here. So that's why coins worked outside, and lives didn't. Now I'll say it once more, in one line. let and const stay in their block, var walks right out of it.
Part 3Shadowing
Now, what happens when a variable inside a block has the same name as one outside? This is called shadowing. And with var, it can surprise you. So let's find out.
1var coins = 100;2{3 var coins = 10;4 console.log(coins);5}6console.log(coins);10 10
So here, coins is declared twice with var. Once outside, and once inside the block. But a var ignores blocks, remember? So both of these are the very same variable, in global memory. That's why phase one creates only one coins. Line one sets coins to one hundred. Line three, inside the block, overwrites that same global coins with ten. Line four prints ten. And now line six, outside the block, prints ten again! Not one hundred. The block changed the outside variable. Dangerous.
So here's the definition. Shadowing means an inner variable, with the same name as an outer one, hides the outer one inside its block. And with var, it's worse. Because a var isn't really inside the block, it doesn't just hide the outer variable, it overwrites it. That's a classic bug, and a very important one. Now watch what let does instead.
1let lives = 9;2{3 let lives = 3;4 console.log(lives);5}6console.log(lives);3 9
So same idea, but with let. The outer lives is hoisted, and line one sets it to nine. Now the code opens the block, and the block gets its own memory, with its own brand new lives. A separate variable! Line three sets the inner lives to three. Line four looks for lives, finds the inner one first, and prints three. The block ends, and the inner lives is gone with it. Line six prints the outer lives, and it's nine. Completely untouched. So that's safe shadowing.
So with let and const, shadowing is safe. The inner variable lives in the block's own memory, hides the outer one only inside the block, and the outer value is never touched. Now if you pause inside the block in DevTools, you can see both of them, side by side. The inner lives, three, under Block. And the outer lives, nine, under Script. And the same is true for functions. A const inside a function shadows a const outside, and the outside one stays exactly the same. Separate boxes, remember?
1const floor = "ground";2{3 const floor = "first";4 {5 const floor = "second";6 console.log(floor);7 }8 console.log(floor);9}10console.log(floor);second first ground
And now blocks can sit inside blocks, like floors in a building. So here we have three floors, and each one has its own const floor. Line six is on the top floor, and it logs floor. Now JavaScript takes the nearest one, the one in its own block. So it prints second. Line eight is one level down, so it finds the middle floor's value. It prints first. And line ten is outside all the blocks, so it prints ground. And if the top block didn't have its own floor? Line six would simply look one level up, and print first. So blocks follow the same lexical scope chain we learned in episode seven. Nearest wins, then up, one level at a time.
Part 4Illegal shadowing
Now, there's one kind of shadowing that JavaScript doesn't allow at all. It's called illegal shadowing. So let's see why it's illegal.
1let level = 1;2{3 var level = 2;4}SyntaxError: Identifier 'level' has already been declared
So look at this. Outside, we have let level. Inside the block, we try var level. Now remember, a var escapes the block and tries to live in the outer scope. But the outer scope already has a let called level. Two declarations, same name, same scope. So JavaScript rejects the whole file, before running a single line. A syntax error. Identifier level has already been declared. So you can't shadow a let with a var like this.
1let level = 1;2 3function play() {4 var level = 2;5}But this one is completely fine. Here, the var level is inside a function, not just a block. And a var is function scoped. It can escape a block, but it can never escape a function. So this var stays inside play, in play's own memory, and it never clashes with the outer let. No error at all. Everything works. So the rule is simple. A var can't cross into a scope where a let or const already has that name.
So remember the rules of shadowing. let can shadow let. let can shadow var. var inside a function can shadow anything, because it stays in the function. But var inside a plain block can't shadow a let or const outside, because it would leak into their scope. That one is illegal shadowing, a syntax error. And all of this works the same way for arrow functions too.
1let x = 1;2{3 let x = 2;4}5var y = 1;6{7 var y = 2;8}9console.log(x, y);What does the last line print?
Show the answer
So x is a let. The inner x lived only inside its block, so the outer x is still one. But y is a var. The inner var y is the same global y, so it overwrote it with two. So the answer is one, and two. Did you get it right? Then you've really mastered block scope, and shadowing too. Well done!
Have you ever been bitten by a var inside a block?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.