14.11 The with Statement

Note 1

Use of the Legacy with statement is discouraged in new ECMAScript code. Consider alternatives that are permitted in both strict mode code and non-strict code, such as destructuring assignment.

Syntax

WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] Note 2

The with statement adds an object Environment Record for a computed object to the lexical environment of the running execution context. It then executes a statement using this augmented lexical environment. Finally, it restores the original lexical environment.

14.11.1 Static Semantics: Early Errors

WithStatement : with ( Expression ) Statement Note

It is only necessary to apply the second rule if the extension specified in B.3.1 is implemented.

14.11.2 Runtime Semantics: Evaluation

WithStatement : with ( Expression ) Statement
  1. Let val be the result of evaluating Expression.
  2. Let obj be ? ToObject(? GetValue(val)).
  3. Let oldEnv be the running execution context's LexicalEnvironment.
  4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
  5. Set the running execution context's LexicalEnvironment to newEnv.
  6. Let C be the result of evaluating Statement.
  7. Set the running execution context's LexicalEnvironment to oldEnv.
  8. Return Completion(UpdateEmpty(C, undefined)).
Note

No matter how control leaves the embedded Statement, whether normally or by some form of abrupt completion or exception, the LexicalEnvironment is always restored to its former state.