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 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.

🔰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.

🔰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.

🔰Scope Chain

✅The scope chain is simply the memory space of the function that was called, and the memory space of its outer environment.
✔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

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.