JavaScript Course
JavaScript
/
Intermediate

Lexical Scope

Definition

Lexical scope means that a variable's scope is determined purely by its physical placement in the source code. Inner functions have access to variables declared in their outer scope.

Explain Like I'm New

Lexical scope is like a set of Russian nesting dolls. The smallest doll inside can see all the wood from the larger dolls surrounding it. But the large outside doll cannot look inside the tiny doll.

Real World Example

If a function `child()` is written inside `parent()`, `child()` can use any variables defined in `parent()`. If `parent()` is called somewhere else, `child()` STILL remembers where it was physically written.

Common Use Cases

  • •Closures
  • •Private variables

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What does Lexical mean?

intermediate

  • What is the Scope Chain?

advanced

  • What is the difference between Lexical Scope and Dynamic Scope?

Flash Cards

Question

What is the Scope Chain?

Click to reveal answer
Answer

When you try to use a variable, the JS engine looks in the current function. If it doesn't find it, it steps 'outward' to the parent function's scope, and so on, until it reaches the Global Scope. If it's not there, it throws a ReferenceError.

Question

Lexical vs Dynamic Scope?

Click to reveal answer
Answer

Lexical scope is determined by WHERE the function is WRITTEN. Dynamic scope is determined by WHERE the function is CALLED. JavaScript uses Lexical scope (with the exception of the `this` keyword, which behaves dynamically).