Variable shadowing in JS

To understand shadowing, you need to have a good idea on Block Scope in JS.

What is Variable Shadowing

Variable shadowing occurs when a variable of inner scope defined with the same name as of outer scope. When we call that variable in the inner scope, we will get the value of the inner scoped variable. This is known as Shadowing or Variable shadowing. The introduction of let and const in ECMAScript 6 along with block scoping allows variable shadowing.

function fn1() {
    var a = "Car";
    let  b = 'Black';
    const c = 'Video';
    
	if (true) {
        var a = "Bike";
        let b = 'Red '; // New value assigned
        const c = 'Book';

        console.log(a); // Result is Bike
        console.log(b); // Result is Red
        console.log(c); // Result is Book
	}
	
    console.log(a); // Result is Bike
    console.log(b); // Result is Black
    console.log(c); // Result is Video
}
fn1();

Illegal Shadowing

Now, while shadowing a variable, it should not cross the boundary of the scope, i.e. we can shadow var variable by let variable but cannot do the opposite. So, if we try to shadow let variable by var variable, it is known as Illegal Shadowing and it will give the error as “variable is already defined.”

function fn1() {
    var b = 'Black';
    let c = 'Video';
    
	if (true) {
        let b = 'Red '; // Legal shadowing
        var c = 'Book'; // Illegal Shadowing. 
                        // Throws error as Identifier 'c' has already been declared

        console.log(b); // Result is Red
        console.log(c); // This will throw error
	}
	
    console.log(b); // Result is Black
}
fn1();
References

geeksforgeeks

Read More