Dhrumi Shah
Dhrumi Shah

@deetwts

13 Tweets 4 reads May 26, 2022
SERIES : How JavaScript works behind the scenes?
Part 5 (last part) ⬇
📌 What is scope?
The space in which variables and statements are available is known as scope.
It allows variables with the same name to exist without colliding, and it prohibits outer scopes from having access to inner scopes.
📌 Types of scope :
In JavaScript we have three types of scope:
1. Global scope
2. Function/local scope
3. Block scope
📌 Global scope
It is default scope and there is only one Global scope in whole program which is the top scope. The declarations inside this space can be accessed anywhere in the code
Example :
The function `myAge()` is able to reference age which is present in global scope.
📌Local scope or Function scope :
It is created inside the function and declarations inside the function are only accessible there.
Example :
The `age` constant is located inside the function scope so we are able to return it, but when we try to print it from the global scope we get a reference error. This happens because outer scopes cannot access the inner scope created by `myAge`.
📌Block scope :
It is space between a pair of curly braces. Applicable to only le and const. Declarations are only accessible inside the block
Note: Var is function scope
Example : we are able to print the variable `msgOne` but not constant `msgTwo`
📌Scope chain :
Take a look at the code below. What is printed to the console? The answer is `Jonas is a 30-old teacher`. But what makes it possible for the `second()` function to access the constants from outside the scope?
When the `second()` function is executed it finds that `myName` and `age` are not in local scope
So, how is JavaScript able to reference it?
When the constant is not found in the local scope JavaScript reaches the parent scope getting Jonas and 30 by variable lookup
variable lookup:
When a variable is not in the local scope, the engine looks up in the parent scope chain until it finds the variable it’s looking for.
As the value of job (teacher) is present in local scope there is no need of variable lookup.
It is important to know that the scope chain works only one way, from the inner scope to the outer scopes.
The scope chain doesn't affect by order of function.
I have written blog on Conditional Statements in JavaScript on hashnode.
Check it out here :
dhrumishah.hashnode.dev
Thanks for reading this thread ❤
If you like it , make sure you:
🔷Like the tweet
🔷Retweet the first tweet⚡
For more content , Follow:
@deetwts

Loading suggestions...