What is the first thing that pops in your mind when you ask someone what is scope?
Something related to accessibility maybe.
There are various concepts around this scope which are interesting and make you pull your hair at the same time.
Most of the javascript developers will tell you 'let' and 'const' are block scoped.
What is scope exactly?
Scope defines the accessibility of any variable or function.
There are 2 types of scope:
- Global scope
- Local scope
What is global scope?
Variables or functions which can be accessed by anyone outside the block or inside the block.
What is local scope?
Local scope is of many types. Some are
- Block scope
- Function scope
- Lexical Scope
Block scope
what is a block?
Block is a group of statements where Javascript expects a single statement.
you can have if block, switch block, for-loop block etc These are all blocks.
What is block scope then?
Variables or functions which are accessible within this block.
Simple isn't it?
Here Javascript has gotcha
We can declare variables as var, let, and const.
Earlier I mentioned let and const are block scoped
let see how these 3 work inside a block
What will be the output? Let's see that
What if I want to access the 3 variables outside the block?
Can i?
Let's see that in the working
Can you see that it says 'Reference Error - b is not defined' but it shows the value of a which is of var type where as let is not accessible.
Now can you relate why let and const are block-scoped.
Let's see how JS engine works for let and const
Initially, the variables let and const are placed in block scope and the var is placed in the global scope and initialized with 'undefined'
As we execute the code line by line then variables get initialized with the values
Here can you see that block scope vanishes?
As we are out of the block the block scope also gets deleted due to which let and const are not accessible outside the block and hence called 'block scope'.
Function scope
Variables having scope within a function
Code snippet for above statement
we cannot access any variable outside the function scope.
Lexical scope
Child scope variables can access parent scope variables.
It is said that the Child function is lexically bound by the parent function.
The image illustrates the lexical scope
the innerMost function has access to inner function variables as well as outer function variables too.
Please note that var is an issue creator it overrides the parent assignment for the variable in block scope and not in function scope hence let and const were introduced
The below image is an illustration in block scope
This image is for function scope
Hoping the article was quite knowledgeable for the ones reading this. Please add your comments if I have missed anything or mentioned something wrong.
Top comments (0)