Lexical Scope in JavaScript – Explained with Examples
The term “lexical scope” may seem tricky to grasp at first glance. But it’s helpful to understand the word “lexical”. So, let’s get it started there.
What Is Lexical?
Lexical refers to the definition of things.
Anything related to creating words, expressions, or variables is termed lexical.
For instance, a scrabble game is a lexical activity because it relates to the creation of words.
Also, someone whose job relates to linguistics (the study of languages) has a lexical career.
So, now that we know what lexical means, we can talk about lexical scope.
What Is a Lexical Scope in JavaScript?
Lexical scope is the definition area of an expression.
In other words, an item’s lexical scope is the place in which the item got created.
Example of lexical scope
Consider the code below:
In the snippet above, notice that we defined myName
variable in the global scope and called it in the getName()
function.
Question: Which of the two spaces is myName
’s lexical scope? Is it the global scope or the getName()
function’s local scope?
Answer: Remember that lexical scope means definition space—not invocation space. Therefore, myName
’s lexical scope is the global scope because we defined myName
in the global environment.
Another example of lexical scope
Question: Where is myName
’s lexical scope?
Answer: Notice that we created and called myName
within getName()
. Therefore, myName
’s lexical scope is getName()
’s local environment because getName()
is myName
’s definition space.
How Does Lexical Scope Work?
A JavaScript expression’s definition environment determines the code permitted to access it.
In other words, only code within an item’s lexical scope can access it.
For instance, consider the code below:
Notice that the invocation of displayFullName()
in the snippet above returned an Uncaught ReferenceError
. The error returned because only code within an item’s lexical scope can access the item.
Therefore, neither displayFullName()
function nor its internal code can access the lastName
variable because lastName
got defined in a different scope.
In other words, lastName
’s lexical scope is different from that of displayFullName()
.
lastName
’s definition space is showLastName()
while displayFullName()
’s lexical scope is the global environment.
Now, consider this other code below:
In the snippet above, displayFullName()
successfully returned "Oluwatobi Sofela"
because displayFullName()
and showLastName()
are in the same lexical scope.
In other words, displayFullName()
could invoke showLastName()
because the two functions are both defined in the global scope.
Wrapping It Up
Any time you hear lexical, think definition.
So, the lexical scope of a car, variable, phone, function, or swimsuit refers to its definition region.