DEV Community

Cover image for #13) Explain Scope and Scope Chain in JS💥
Mayank Yadav
Mayank Yadav

Posted on

#13) Explain Scope and Scope Chain in JS💥

🔰Scope

Scope determines the accessibility or visibility of a variables in your piece of code.

There are 3️⃣ types of Scopes in JavaScript👇

1️⃣ Global Scope
2️⃣ Local or Function Scope
3️⃣ Block Scope

🔰Global Scope

✅Variables that are declared outside any function have Global Scope.
✅So, they are accessible from anywhere inside the code.
image

🔰Local or Function Scope

✅Variables declared inside the function are considered as local scope.
✅Every function has it's own scope.
✅The variable is visible inside the function and cannot be accessed outside the function.
image

🔰Block Scope

✅Whenever you see {curly brackets}, it is a block.
✅Block Scope is related to the variables declared using let and const, which means those variables exist only within the corresponding block.
✅Accessible inside that block and cannot be accessed outside of it.
✅A block scope is present in codes within if, switch conditions or for and while loops.
image

🔰Scope Chain

✅The scope chain is simply the memory space of the function that was called, and the memory space of its outer environment.
image
✔In the above example, the 1st console is for fruit2 i.e., 🥭.
It Does not find 🥭 inside newFavFruit, so it looks for variable inside favFruit, returns 🥭.

✔In the 2nd console, it is for fruit i.e., 🍌.
It does not find 🍌 inside nestedFavFruit, so it looks for variable inside favFruit and does not find it, so looks for variable in global scope, finds it and result is 🍌.

⚠As you can see, if the JavaScript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope


Discussion (0)