Block Scope and Shadowing in JavaScript

In this article we are going to discuss:

  • What is block scope?
  • What is shadowing and illegal shadowing?

What is block scope

Blocks are used to combine multiple statements into a single group or a compound statement with two curly braces { }. Here is an example of a block.

{
	statement 1
	statement 2
	...	
}

Scope refers to the availability of variables or functions in certain parts of the javascript code.

The let and const are block-scoped variables. 

If let and const variables are declared inside a block, then the scope of such variables will be inside that block. Let's take the below example:

if(true){
   let a = 10;
   console.log(a); // 10
}
console.log(a); // ReferenceError: a is not defined

Here first console.log prints 10 in the console and the second console.log shows ReferenceError because the variable a cannot access from outside of the block.

What is shadowing and illegal shadowing

When a variable is declared in the inner scope having the same variable name defined on its outer scope and then we call the variable from the inner scope, the value in the variable is the value assigned in the inner scope. This is known as Shadowing or Variable Shadowing. We can explain with below example:

let a = 10
if (true) {
	let a = 20; 
	console.log(a); 
}     
console.log(a); 

Output:

20
10

We can shadow let variable by let variable and var variable by let variable. But we can't shadow let variable by var variable. This is illegal shadowing. 

var is not scoped to the block, it is scoped to the containing function. If there is no containing function, it ends up in the global scope. Hence it conflicts with the let a declaration that is also in the global scope.