liveBook · Manning

[[Environment]]

As explained in Secrets of the JavaScript Ninja, Second Edition

The internal function property that stores a reference to the lexical environment in which the function was created.

A lexical environment maps identifiers to variables. When a function is created, JavaScript stores a reference to its creation-time lexical environment in the internal [[Environment]] property. This lets the function find outer variables even when it is called elsewhere. section 5.4 section 5.4.2

When the function is called:

  • JavaScript creates a new execution context and lexical environment for that call. section 5.4.2
  • The new environment links outward to the environment referenced by the function’s [[Environment]] property. Identifier lookup can then reach variables in outer environments. section 5.4.2
Figure 5.9. How JavaScript engines resolve the values of variables

Trace how JavaScript resolves variable values through nested environments. section 5.4.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines lexical environments and traces function creation and calls, while noting that [[Environment]] cannot be accessed directly.
Examples
Uses a simple ninja lookup and nested skulk/report functions to illustrate local, outer, and global variables.
What you can do after
Understand how a function resolves outer variables through the environment captured when it was created.
How it connects
Connects lexical environments with scopes, closures, execution contexts, and identifier lookup.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.