Scope & lexical environments
Try code in the playgroundUnderstand the concept
Scope is the part of a program where a variable can be accessed. JavaScript uses lexical scope, which means the available outer variables depend on where a function was defined, not where it is later called. The engine searches outward through surrounding scopes when a name is not found locally.
Important ideas
-
Scope decides where a variable is available.
-
Lexical scope depends on where code is written.
-
An inner function can use variables from its outer scope.
-
Block scope applies to
letandconstinside braces;varnormally belongs to the enclosing function. -
A local variable can shadow an outer variable with the same name, which can make debugging confusing.
Can you explain it without the notes?
What is scope? What does lexical mean?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
Scope is the part of a program where a variable can be accessed. JavaScript uses lexical scope, which means the available outer variables depend on where a function was defined, not where it is later called. The engine searches outward through surrounding scopes when a name is not found locally.
Turn this concept into a clear answer.
- A function carries its access to outer scopes even when passed to another function.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What is scope? What does lexical mean?”. Examples are study fragments; framework behavior can depend on your version.