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.
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
What is block scope then?
Variables or functions which are accessible within this block.
Simple isn't it?
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 if I want to access the 3 variables outside the block?
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.
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'.
Variables having scope within a function
Code snippet for above statement
we cannot access any variable outside the function 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
Hoping the article was quite knowledgeable for the ones reading this. Please add your comments if I have missed anything or mentioned something wrong.