The Difference Between Lexical and Dynamic Scoping
Lexical scoping refers to the variables in the location of a function's definition, whereas dynamic scoping refers to the variables in the location of a function's invocation. What does this mean? Take a look at the following code example:
function a() {
console.log(i);
}
function b() {
var i = 1;
a();
}
var i = 0;
b();
We have two function, a
and b
. a
logs out the value of i
which is set globally to 0. b
sets its value to 1, and calls a
. If we call b
, it will log out 0. This is because β while a
doesn't have a variable called i
β a
has access to the enclosing scope where the function is defined. And in the global scope, we have an i
which is set to 0. This is called lexical scoping.
In dynamic scoping, the value of i
will be 1. This is because instead of looking at where the function is defined, it looks at where it is called from. It sees from the call stack that it has been called from b
, which sets the value of i
to be 1.
As you can see, lexical scope looks at where a function is declared, where dynamic scope refers to where a function is called from.
Note that JavaScript works with lexical scoping and doesn't have a dynamic scope.
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: