DEV Community

Cover image for Block Scope and Shadowing in JavaScript
Naveen Kamath
Naveen Kamath

Posted on

Block Scope and Shadowing in JavaScript

Hello Readers,

  • Read this Blog to know about Block Scope and Shadowing .

Block:

  • also known as Compound Statement. For Example
{
This is a Block.
}
Enter fullscreen mode Exit fullscreen mode
  • Block is used to Combine Multiple JS Statements into One Group.
  • We group multiple statements in a Block, so that we can use it where JS expects one Statement.
if(true)   //This statement will give error.
Enter fullscreen mode Exit fullscreen mode
  • The if syntax expects any statement after if(true) ...here.
if(true) true //This is correct.
Enter fullscreen mode Exit fullscreen mode
  • But what if we want to include multiple statements in if block, Here we use Block {}.
if(true){
  line1
  line2
  more lines ...
}
Enter fullscreen mode Exit fullscreen mode

BlockScope:

  • All the variables and Functions accessible inside a scope, so that's why we say let and const are Block Scoped because they are stored in a different memory space reserved for the Block.

Shadowing:

  • If we have same Variables outside as well as inside the block. The variable inside the block shadows the outer variables. For Example:

Image description

  • But Not in case of let or const due to lexical scopping

Image description

  • vice versa not true!.
  • All these programs work same for Arrow Functions too.
  • Thanks for Reading the blog, Have a Great Day :)

Top comments (1)

Collapse
 
1122abhi profile image
Abhijeet Konnur

Nice Explaination