BLOCK SCOPE and SHADOWING in JavaScript

Shahid Bugti
3 min readJan 11, 2024

--

To understand Block Scope first we must know that what a block Is.

What exactly a Block is?

A block is pair of curly braces “{ }”, it is also called compound statement.

Use of Block:

“Block is used to write multiple statements in a place where JavaScript expects a single statement.”

To understand this statement let look a an example

//The following code is perfectly correct.
if(true) console.log("true");

//But if We want to use multiple statements of code
if(true){
console.log("This code will be executed because the condition is true.");
// You can add more statements here
let x = 5;
let y = 10;
console.log("The sum of x and y is:", x + y);
}

The curly braces or not in the syntax of if statement but we wanted to use multiple statements so we used a block.

Now lets see what Block Scope is?

Block Scope:

The block scope of a variable means that it is accessible in particular Block.

In this block of code we have three variables declared with var, let and const respectively, you can see the variables declared with let and const are in a seperate memory space named as Block, while the variable declared with var is in global scope , it cleares that variable declared with let and const are block scoped.

{
var a = 10;
let b = 15;
const c = 20;
}
console.log(b); //uncaught refrence error: b is not defined.

in given code we are trying to access a block scoped variable in global scope that is why JavaScript throws an error.

{ 
var a = 10;
let b = 15;
const c = 20;
}
console.log(a);//10

This code is perfectly fine because we are accessing a global scoped variable in global scope, even the “a” is declared in a block but it is still not block scoped.

Shadowing :

Variable shadowing happens when a variable is declared in an inner scope using the same name as a variable in an outer scope. This leads to the inner scope’s variable taking precedence, effectively replacing and overshadowing the outer scope’s variable.

var a = 20;//this is the puter scoped 
{
var a = 10;//this variable shadows the outer scoped one;
let b = 15;
const c = 20;
}

Technically both variables have same scope “Global Scope” but redeclaration is allowed in case of var, so the code is correct.

let  a = 20;
function(){
let a = 20;
}

In case of let redeclaration is not allowed but here the scopes of both variables are different.

Illegal Shadowing:

Shadowing the variables declared with let and const in same scope is illegal.

let a = 10;
let a = 5;
let a = 10;
if(true){
var a = 10;
}

Technically both the variables have same scope so it is not correct as I mentioned that in let declaration shadowing them in same scope is illegal.

Thanks for taking the time to explore this Article.

lets connect on LinkedIn

www.linkedin.com/in/muhammad-shahid-bugti-2a7b43276

for More content follow me.

--

--