Understanding Scope in JavaScript

Samyak Jain - May 29 '23 - - Dev Community

The most basic definition of Scope would be that it defines or makes a boundary within which a variable or a function is recognized and can be referenced meaning it can be used somewhere else too like in some operations maybe as simple as adding two variables to get the result. Or you can say that it defines the availability of variables and functions in certain parts of the code.

Didn't Understand it? No problem its just the start we'll see some examples and deep dive in this topic.
So before we categorize Scope lets see an example.

Example 1

See that? We made two variables x and y , now x was accessible in function and outside the function but when we tried to do the same with y then we got an error.
You can try it out in this Repl

This Repl will contain all the Examples that I will talk about throughout in this blog.

To Understand this, Scope is categorized in two sub categories which are

  1. Global Scope
  2. Local Scope

Now before we understand Scope any further or talk about its sub categories, you know about those glass doors which are transparent only from one side? Meaning anyone inside that room can see outside but no one from outside can see anything inside.
So we can think of scope as a series of rooms which are connected through these one way visible glass doors so that the person which is one level inside the room can see the outside room but not vice versa like this

Room Illustration

Global Scope

Now talking about Global Scope, as the name suggests its a scope whose variables and functions are available globally meaning they can be used anywhere inside any function.

It's the highest level of scope that covers the entire program. Anything you declare in the global scope can be accessed and used from anywhere within the program.

So according to our analogy of doors, this can be taken as the outermost room and people inside this room can see all the facilities here and people in the rooms next doors can also see them, why? Because the door is transparent from that side.

Example

Global Scope Example 1

See that? We were able to log x in the global scope but also in the function, why? Because according to the analogy the door is transparent so function can access the variables outside of it and in the global scope.

Lets see one more Example

Global Scope Example 2

Here not only we accessed the variable inside the function but also modified it, this is just another aspect of scoping.

How can you prevent it?

You can pass the variable as an argument in the function so that a copy of that variable is sent to the function instead of the original value, which will always reference the original one.

If you are interested in learning more about this , check out my blog on Pass by Values and Pass by Reference to understand it more

Click here

Local Scope

So Local Scope can be explained as the scope that is created within a specific function or block of code. It's like a little bubble or container that holds variables and functions and keeps them separate from the rest of the program.

It can be said in a sense that local scope is a small global scope meaning whatever you do inside the scope at the top level of that function is accessible through out that function, but not outside that function. That's why its a local scope.

Remember that example I used at the beginning? Where variable y threw an error? That was because y was declared inside a local scope but was tried to access in a global scope, or according to the Glass Door Analogy People Outside of that room (Function) can't see what's inside.

Now if you made two functions in the global scope say RandomFunction and RandomFunction2 then variables in RandomFunction are not accessible in RandomFunction2 as both have them there own seperate bubble or scope.

According to our Glass Door Analogy, imagine that our room has two doors. Now, the people inside their respective rooms can see the content of the common room, but they cannot see the content of each other's rooms.

Now then that's cleared lets see one more interesting example

Local Scope Example

Now here I created variable x two time , once in the global scope and then inside the function, and when I tried to access x inside the function then it logged the value which was most near to it, which was 7 in this case.

This happened because that's how scope works, it starts looking for the variable in the current scope and then goes one level up one by one, and uses the reference which it finds first.
So in this case x inside the Random Function was found first and hence used.

But then after coming out of the function when we tried to log it again it logged 5 this is because once the function is done running then all the variables inside the function are destroyed or simply doesn't exists anymore (You will see something different when you will study closures) and also because of the same concept of accessibility, now that function variable is not accessible it will use the original value.

This also brings us to a standard to try to give unique names to your global variables so that they don't contradicts with the ones in your local scope. As long as you are not giving them same name on purpose

Now there is one more aspect of local scope which Blocked Scope

Block scope refers to the scope that is created within a set of curly braces {} in JavaScript. It's like a mini neighborhood within your code where variables and functions are contained and only accessible within that specific block.

Lets take example of an if statement to explain block scope

Block Scope Example

See that? We were able to log y as long we were inside the block scope or inside the if condition, but as soon as we came out it showed as that its undefined, because this variable is not visible outside its scope.

To fix this error just declare y outside the block scope and then reference it inside the block scope.
This way now it can access the data of outer scope and modify it.

Now normally this will work but try using var instead of let to declare y

Block Scope Example 2

Here you can see that although we declared the variable in block scope still we were able to use it outside its scope why?

The reason for this behavior is that var declarations are function-scoped, meaning they are accessible throughout the entire function, regardless of blocks or conditional statements. Therefore, the var y = 6 declaration inside the if block modifies the value of y in the outer scope as well.

Meaning you can create a function inside the RandomFunction after this if-else statement block and try to log y there , and it will work even there, because y is function scoped, it will work in the entire function.

Although it sounds cool to use var to do something like this its not generally recommended to use these types of approaches in your code, as it can lead to problems in maintainability, readability and overall performance of the code.

Now that we have started to talk about Nested Functions lets also talk about a really important topic related to it which is

Lexical Scope

Lexical scope, also known as static scope, refers to how variable and function names are resolved at the time of writing the code, based on the physical placement or structure of the code. In simpler terms, it determines the accessibility and visibility of variables and functions based on where they are defined in the source code.

Didn't get it? No problem, lets see an example

Lexical Scope Example

Hmm we have seen this behavior before too right? Exactly!! This is what we saw when we saw that example of Globally Scoped variable been used in the local scope.

Lexical Basically means that we access things from the Parent , in our case the Parent Scope, now either the parent is Global Scope or the upper Function its the same thing.

This Wraps up the concept of Scope in JavaScript, if you think I missed something please let me know,

Thanks for reading so far 😁

. . . . . . . . . . . . . . .