Facebook Pixel

What is the difference between lexical scope and dynamic scope?

In lexical scope, a function sees variables from where it was written. In dynamic scope, a function sees variables from whoever called it. JavaScript uses lexical scope; dynamic scope would make foo log the caller's x, not the writer's x.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Lexical Scope vs Dynamic Scope in JavaScript

Lexical (static) scope. The scope chain is determined by where functions are written in the source code, not where they are called. Calling a function from a different scope does not give it access to that scope's variables.

Dynamically (by how the function is called), with one exception: arrow functions inherit this lexically from their enclosing scope. This is the main place where JS feels dynamic, but variable resolution (the scope chain) is always lexical.

It makes code predictable (you can read a function and know what it accesses), enables closures (the written-time chain persists), allows static tooling (linters, type checkers), and lets the engine optimize scope resolution at parse time.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.