What is Scope in JavaScript?

In JavaScript, Scope refers to where something is available to us. It is defined by where variables are declared and where they are available for us to use. JavaScript is a bit wild sometimes but with a strong understanding of scope we can tame it and control the flow of our code so it is readable and strong.

Javascript has two scopes we can utilize: Global and Local. We will get into the nitty gritty of each later in this blog. To put it simply, Global scope refers to anything declared outside of a block of code and Local Scope refers to anything declared inside a block of code.

Let’s use an example from the real world to help us understand how this works. In any office or work place, there is a hierarchy starting at the top with a CEO that works it’s way down to the entry level employees. The CEO hypothetically has all of the information regarding the company, followed by the management team, team leads, and entry level employees. However, each of those sub-teams has their own lingo, conversations, and communications that are unique to their department and the job they are doing. That’s local scope. Those water-cooler talks aren’t supposed to get back to the CEO (probably for good reason). But also every tiny detail of each piece of each team being up to the CEO would be too much. That information belongs to that sub-team. The CEO lives in the global scope and each sub-team lives in their own local scope. They still answer to the CEO but also converse and communicate within their team to get the job done effectively and keep the company moving. That’s scope!


How does Scope work in JavaScript?

Every piece of JavaScript code is run in an execution context. The execution context refers to the environment in which the code is being fired off. In a JavaScript execution context, we can see to all of the variables and functions that were declared within that context. We can have both a global execution context and a local execution context for our code, still following the principles of where the code was defined discussed above (inside or outside a block of code).

#web-development #front-end-development #beginner-javascript #javascript #javascript-tips

JavaScript’s Scope
1.65 GEEK