Scope in JavaScript – Explained with Examples
Scope refers to the area where an item (such as a function or variable) is visible and accessible to other code.
- Scope means area, space, or region.
- Global scope means global space or public space.
- Local scope means local region or restricted region.
Here's an example:
// Define a variable in the global scope:
const fullName = "Oluwatobi Sofela";
// Define nested functions:
function profile() {
function sayName() {
function writeName() {
return fullName;
}
return writeName();
}
return sayName();
}
In the snippet above, we defined the fullName
variable in the global scope. This means that it is visible and accessible globally to all code within the script.
But we defined writeName()
within the sayName()
function, so it is locally scoped to sayName()
.
In other words, writeName()
is locally visible and accessible only to code in the sayName()
function.
Keep in mind that whenever the writeName()
function gets invoked, the computer will not go straight to the global scope to call the fullName
variable. Instead, it must sequentially go through the scope chain to look for fullName
.
What Is a Scope Chain?
A scope chain refers to the unique spaces that exist from the scope where a variable got called to the global scope.
Here's an example:
// Define a variable in the global scope:
const fullName = "Oluwatobi Sofela";
// Define nested functions:
function profile() {
function sayName() {
function writeName() {
return fullName;
}
return writeName();
}
return sayName();
}
In the snippet above, observe that the fullName
variable got called from the writeName()
function's scope.
Therefore, the scope chain that exists from the variable's call to the global scope is:
writeName() scope ---> sayName() scope ---> profile() scope ---> global scope
In other words, there are four (4) spaces from fullName
's invocation scope to its lexical scope (the global scope in this instance).
The global scope is the last link in JavaScript's scope chain.
How Does the Scope Chain Work?
JavaScript's scope chain determines the hierarchy of places the computer must go through—one after the other—to find the lexical scope (origin) of the specific variable that got called.
For instance, consider the code below:
// Define a variable in the global scope:
const fullName = "Oluwatobi Sofela";
// Define nested functions:
function profile() {
function sayName() {
function writeName() {
return fullName;
}
return writeName();
}
return sayName();
}
In the snippet above, whenever the profile()
function gets invoked, the computer will first invoke the sayName()
function (which is the only code in the profile()
function).
Secondly, the computer will invoke the writeName()
function (which is the only code in the sayName()
function).
At this point, since the code in writeName()
instructs the computer to call and return the fullName
variable's content, the computer will call fullName
. But it will not go directly to the global scope to call fullName
.
Instead, the computer must go step-by-step through the scope chain to look for the lexical scope of fullName
.
So, here are the sequential steps the computer must take to locate fullName
's lexical scope:
- Firstly, the computer will check if
fullName
got defined locally within thewriteName()
function. But it will find nofullName
definition there, so it moves up to the next scope to continue its quest. - Secondly, the computer will search for
fullName
's definition insayName()
(the next space in the scope chain). Still, it doesn't find it there, so it climbs up the ladder to the next scope. - Thirdly, the computer will search for
fullName
's definition in theprofile()
function. Yet still,fullName
is not found there. So the computer goes forward to seekfullName
's lexical scope in the next region of the scope chain. - Fourthly, the computer goes to the global scope (the following scope after
profile()
). Fortunately, it findsfullName
's definition there! Therefore, it gets its content ("Oluwatobi Sofela"
) and returns it.
Time to Practice with Scope 🤸♂️🏋️♀️🏊♀️
Consider the script below. Which of the three fullName
variables will the computer call?
// First fullName variable defined in the global scope:
const fullName = "Oluwatobi Sofela";
// Nested functions containing two more fullName variables:
function profile() {
const fullName = "Tobi Sho";
function sayName() {
const fullName = "Oluwa Sofe";
function writeName() {
return fullName;
}
return writeName();
}
return sayName();
}
Will the computer call the first, second, or third fullName
variable?
You will benefit much from this tutorial if you attempt the exercise yourself.
If you get stuck, don't be discouraged. Instead, review the lesson and give it another try.
Once you've given it your best shot (you'd only cheat yourself if you don't!), go ahead to see the correct answer below.
Did You Get It Right?
Out of the three fullName
definitions present in the script above, the computer will call and return the one defined in the sayName()
function.
sayName()
's fullName
variable will get called because sayName()
is the scope inside which the computer will first find a fullName
definition.
Therefore, when profile()
gets invoked, the returned value will be "Oluwa Sofe"
.
- Suppose the computer did not find
fullName
's definition in any of the scopes. In such a case, the computer will returnUncaught ReferenceError: fullName is not defined
. - The global scope is always the last scope of any JavaScript scope chain. In other words, the global scope is where all searches will end.
- An inner (child) scope has access to its parent (outer) scope, but an outer scope does not have access to its child scope.
For instance, in the snippet above,
writeName()
can access code inside any of its parent scope (sayName()
,profile()
, or the global scope). However, neithersayName()
,profile()
, nor the global scope can access any ofwriteName()
's code.
Wrapping It Up
JavaScript scope is all about space.
So next time your partner calls you to their private scope, remember they are inviting you to their private space 😜!
When you get there, be sure to ask them about their best lexical game…
But what does lexical mean, I hear you ask? Let's find out in this article.
Overview
This article discussed what scope means in JavaScript. We also looked at why it is an important programming concept.