Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let
and const
.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
Block Scope and shadowing in JS
https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=10&ab_channel=AkshaySaini
- Block is defined by a ' { } '. It is also known as a compound statement. It combines multiple java script statements into one. We use a block to give multiple statements to places where we expect a single statement.
Example:
// single statement
if(true) true
// multiple statement with block
if(true) {
// statement 1
// statement 2
// statement 3
}
{
var a = 10;
let b = 100;
const c = 1000;
}
- Now if we observer this program as soon as the program runs the b and c gets a undefined value in block scope and a gets undefined in a global scope unlike let and const.
- Once javascript encounters the last statement and ending of the scope the let and const are no longer accessible and hence they are known as block-scoped variables.
Shadowing in JavaScript
var a = 100;
{
var a = 10;
let b = 100;
const c = 1000;
console.log(a);
}
console.log(a);
// output
10
100
- This is shadowing the a is 100 as the code hits the last line of the scope it destroys the a value as 10 in the global scope and it went back to the 100 and this is how shadowing happens.
- The a inside the block shadows the global a value that is 100 and instead will print 10 if we do console.log(a) inside a block
- Here it will give a syntax error as it is a illegal shadowing we cannot shadow a let with a var but we can do with a let itsef