Understanding Scope and Context in JavaScript
Want a deeper understanding of “Scope” & “Context” in JS? Want it demystified? Look no further. I have simplified it for you!
You might have heard many times that JavaScript is weird😨, JavaScript is hard to understand😨, JavaScript is unpredictable🙄 and what not…
Well, It’s not that weird if you understand JS inside-out,
It’s not that hard if you pay attention to details,
It’s not unpredictable if you understand implementation details.
I’ll be writing more often about JS and will try to simplify hard topics.😎
Stay tuned, follow me on Twitter for updates.
Let’s get started
We’ll first understand what is Scope with one analogy and some code snippets then we’ll understand what is Context with some code snippets.
Let’s keep going.
Scope
To understand what is scope in JS we’ll use one analogy.
Let’s imagine you are an aspiring merchant and you are doing trades in your local market(your city), you buy goods from one part of your city and sell in another part of the city with some margin, you are able to book some good margins at the end of the day,
One day, one of your elite customer requests goods which are not available in your territory😇. You don’t want to lose that elite customer by saying no to him, you want to make it available for him anyhow.
To make those goods available to your elite customer you have to travel beyond your territory and see if it is available in the neighboring territory if it is not available in the neighboring territory you are willing to travel further(other territories) to make your elite customer happy.
That's it, read this analogy again,
Territory in which(local territory) you are doing business is nothing but the Scope of your business. you sell your good in your local territory which you bought from the same territory.
But in special cases, you are willing to go in someone else's scope/territory and look for good which your customer requested for.
Let’s now understand in terms of JavaScript
In JavaScript, we call these territory as Scopes.
So Scope is a synonym for territory in JavaScript.
Like your business, JavaScript also has territory in which it does business.
Unlike you, JavaScript is also willing to change its territory to make his customer happy.
The only difference between you and JavaScript is that by default you do your business in the local territory, JavaScript by default does business in the global territory.
In JavaScript, its customer can define territory/scope in which they request JavaScript to do business. but since JavaScript by default does business in the global territory it will always look for the goods in its global territory if customer-defined territory doesn’t have it.
In JavaScript, there are mainly three scopes
1.Global Scope
As stated earlier, it is a default scope in JavaScript. which means if the variable is not defined inside any other scope, it belongs to the global scope.
Although, there is a catch we are avoiding it for now.
As you can see in the above code snippet,
I have defined variable name inside and outside of the function called someFunction and variable anotherName outside of the function.
Whatever defined inside a function called someFunction, is local to the function, we can not access it outside of someFunction. and whatever outside the someFunction belongs to the global scope.
As stated in the above analogy, if good is not available in the local scope, JS will always try to find it in the global scope.
Inside someFunction, we are printing anotherName, JS will first look if it is available in someFunction scope which is immediate local scope while inside the function, if it not available it will Jump outside of that scope and lookup for anotherName, if not available there it will again jump outside of that scope and it goes on until it reaches to the default scope which is the global scope.
In our example, we only have two scopes, one is someFunction scope and another is global scope,
2. Function Scope/ Local Scope
As explained in the above example, a variable defined inside someFunction is only accessible inside that function, which means the scope of the variable becomes the function in which it is defined.
As you can see in the above example,
variables defined inside functions are also available to nested functions.
Remember our analogy,
When doing business inside nestedFunction scope, elite customer requests you some good which is not available in your territory, first, you will look into the neighborhood if it is available if not then only you’ll travel further.
In the above example, inside nestedFunction, we are trying to print name, which is not defined inside nestedFunction, JS jump outside the scope and lands in someFunction’s scope, there it finds name and returns back to its own territory which is nestedFunction scopes.
3. Block Scope
Block scope is quite similar to function scope the only difference is syntax.
In JavaScript, we can create block scope using curly braces “{“.
Scope in JavaScript is nothing but the territory in which variables are visible.
Note: The scope of the variable might change depending on how it is defined.
for example, variables defined using let keyword is block-scoped and variables defined with var keyword are functions scoped. There are more rules to it but we’ll ignore those forsake, of simplicity.
Context
As we learned what is Scope above, we can now state that whenever and wherever a variable is defined it belongs to some scope, it might be a global scope, function scope, or block scope.
Similarly, functions also belong somewhere, We can call a function from anywhere, off-course it needs to visible in that scope.
A context is a place in which a function is being executed. this keyword inside function always points to the context in which it is being executed or where it belongs.
In JavaScript(web browser) Window is a global object in which all functions gets executed unless they are defined or provided with some other context.
As you can see in the above examples, someFunction is executed in the global Window object, so its context becomes a window, and function fn is defined inside user Object hence its context is the user.
Context is also referred as execution context, we can change the context of the function using the call, apply, and bind method.
Also, there are some rules which identify the context of a function but we are not covering them here.
As you can see in the above example, the constructor function creates a separate execution context but if invoked as a normal function its gets executed in the global Window context.
Note: Default execution context in Worker is WorkerGlobalScope
whereas in Node.JS there is a global
object in which functions gets executed.
So in simple words context is an object to which function belongs and this keyword always refers to a context to which function belongs.
That's all about Scope and Context, I hope you have learned something new today.
For more details, you can refer below articles
Previously, I also wrote
If you enjoyed this article please like and share
It encourages me to write more
If you have some feedback or suggestions please reach out to me on Twitter