Does JavaScript use lexical or dynamic scope?
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.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Lexical Scope vs Dynamic Scope in JavaScript
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.
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
