DEV Community

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

Posted on

1

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay