DEV Community

Cover image for Block in JS part-2
Pratiyush Kumar
Pratiyush Kumar

Posted on

Block in JS part-2

Hello Folks, I am back with the part2 of block where I will share next part of block. In previous blog we saw what do we mean by block now we will see what is block scope.

Block Scope means whatever variables and functions are defined inside a block, they have access inside block itself. They can not be accessed outside of the block.

Below is example to show that variables inside block is getting accessed.
Alt Text

output is below.

Alt Text

If we try to access variables outside the block then you will only variable which was defined with var can be accessed outside the block because var is global scoped while let and const variables are blocked scoped.

Thus this proves that let and const variables are blocked scope.

Alt Text

Alt Text

Hence you can see if we try to access the let and const variable outside the variable it will give error as "uncaught ReferenceError: b is not defined".

Above we talk about block scope where we saw the scope of variable inside the block but what about the functional scope.

Inside function every variable is function scoped i.e. variables can be accessed only inside the function and not outside the fucntion.

Alt Text

Alt Text

but when we try to access a variable inside a function that is defined outside the function we can access the variable.

Alt Text

Alt Text

Top comments (0)