AceDevHub
Advanced JavaScript Interview QuestionsAdvancedConcept

JavaScript · Question 71

What are execution contexts and lexical environments in JavaScript, and how do they relate to scope?

Direct answer

An execution context represents the state needed to execute code, while lexical environments and environment records hold the bindings that lexical name resolution consults; scope lookup follows the chain of outer environments.

A useful senior-level model is to separate execution from name resolution. An execution context tracks the currently executing code and associated state. Lexical environments provide the structure used to resolve identifiers such as local variables, parameters, and imported bindings.

When code evaluates user.name, resolving user begins in the current environment record. If the binding is not there, resolution follows the outer environment references until it finds a binding or reaches the end of the chain. This is the mechanism behind lexical scope; it is more precise than saying JavaScript “searches parent functions.”

  • Function calls create new execution contexts and function-related environments.
  • Blocks can introduce lexical bindings for let, const, and class without creating a new function call.
  • Closures work because functions retain access to the lexical environment chain associated with where they were created.