The Difference Between Lexical and Dynamic Scoping

The Difference Between Lexical and Dynamic Scoping

Ferenc Almasi β€’ Last updated 2021 September 18 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

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:

Copied to clipboard! Playground
function a() { 
    console.log(i);
}

function b() {
    var i = 1;
    a();
}

var i = 0;

b();
scope.js

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.

Lexical vs dynamic scoping in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.