Environment Record is a specification type used to define the association ofIdentifiers to specific variables and functions, based upon the lexical nesting structure of ECMAScript code. Usually an Environment Record is associated with some specific syntactic structure of ECMAScript code such as aFunctionDeclaration, aBlockStatement, or aCatch clause of aTryStatement. Each time such code is evaluated, a new Environment Record is created to record the identifier bindings that are created by that code.
Every Environment Record has an[[OuterEnv]] field, which is eithernull or a reference to an outer Environment Record. This is used to model the logical nesting of Environment Record values. The outer reference of an (inner) Environment Record is a reference to the Environment Record that logically surrounds the inner Environment Record. An outer Environment Record may, of course, have its own outer Environment Record. An Environment Record may serve as the outer environment for multiple inner Environment Records. For example, if aFunctionDeclaration contains two nestedFunctionDeclarations then the Environment Records of each of the nested functions will have as their outer Environment Record the Environment Record of the current evaluation of the surrounding function.
Environment Records are purely specification mechanisms and need not correspond to any specific artefact of an ECMAScript implementation. It is impossible for an ECMAScript program to directly access or manipulate such values.
AFunction Environment Record corresponds to the invocation of an ECMAScriptfunction object, and contains bindings for the top-level declarations within that function. It may establish a newthis binding. It also captures the state necessary to supportsuper method invocations.
AnObject Environment Record is used to define the effect of ECMAScript elements such asWithStatement that associate identifier bindings with the properties of some object.
AGlobal Environment Record is used forScript global declarations. It does not have an outer environment; its[[OuterEnv]] isnull. It may be prepopulated with identifier bindings and it includes an associatedglobal object whose properties provide some of the global environment's identifier bindings. As ECMAScript code is executed, additional properties may be added to theglobal object and the initial properties may be modified.
TheEnvironment Record abstract class includes the abstract specification methods defined inTable 14. These abstract methods have distinct concrete algorithms for each of the concrete subclasses.
Determine if anEnvironment Record has a binding for the String valueN. Returntrue if it does andfalse if it does not.
CreateMutableBinding(N, D)
Create a new but uninitialized mutable binding in anEnvironment Record. The String valueN is the text of the bound name. If the Boolean argumentD istrue the binding may be subsequently deleted.
CreateImmutableBinding(N, S)
Create a new but uninitialized immutable binding in anEnvironment Record. The String valueN is the text of the bound name. IfS istrue then attempts to set it after it has been initialized will always throw an exception, regardless of the strict mode setting of operations that reference that binding.
InitializeBinding(N, V)
Set the value of an already existing but uninitialized binding in anEnvironment Record. The String valueN is the text of the bound name.V is the value for the binding and is a value of anyECMAScript language type.
SetMutableBinding(N, V, S)
Set the value of an already existing mutable binding in anEnvironment Record. The String valueN is the text of the bound name.V is the value for the binding and may be a value of anyECMAScript language type.Sis a Boolean flag. IfS istrue and the binding cannot be set throw aTypeError exception.
GetBindingValue(N, S)
Returns the value of an already existing binding from anEnvironment Record. The String valueN is the text of the bound name.S is used to identify references originating instrict mode code or that otherwise require strict mode reference semantics. IfS istrue and the binding does not exist throw aReferenceError exception. If the binding exists but is uninitialized aReferenceError is thrown, regardless of the value ofS.
DeleteBinding(N)
Delete a binding from anEnvironment Record. The String valueN is the text of the bound name. If a binding forN exists, remove the binding and returntrue. If the binding exists but cannot be removed returnfalse. If the binding does not exist returntrue.
HasThisBinding()
Determine if anEnvironment Record establishes athis binding. Returntrue if it does andfalse if it does not.
HasSuperBinding()
Determine if anEnvironment Record establishes asuper method binding. Returntrue if it does andfalse if it does not. If it returnstrue it implies that theEnvironment Record is aFunction Environment Record, although the reverse implication does not hold.
WithBaseObject()
If thisEnvironment Record is associated with awith statement, return the with object. Otherwise, returnundefined.
9.1.1.1 Declarative Environment Records
EachDeclarative Environment Record is associated with an ECMAScript program scope containing variable, constant, let, class, module, import, and/or function declarations. A Declarative Environment Record binds the set of identifiers defined by the declarations contained within its scope.
9.1.1.1.1 HasBinding (N )
The HasBinding concrete method of aDeclarative Environment RecordenvRec takes argumentN (a String) and returns anormal completion containing a Boolean. It determines if the argument identifier is one of the identifiers bound by the record. It performs the following steps when called:
IfenvRec has a binding forN, returntrue.
Returnfalse.
9.1.1.1.2 CreateMutableBinding (N,D )
The CreateMutableBinding concrete method of aDeclarative Environment RecordenvRec takes argumentsN (a String) andD (a Boolean) and returns anormal completion containingunused. It creates a new mutable binding for the nameN that is uninitialized. A binding must not already exist in thisEnvironment Record forN. IfD istrue, the new binding is marked as being subject to deletion. It performs the following steps when called:
Assert:envRec does not already have a binding forN.
Create a mutable binding inenvRec forN and record that it is uninitialized. IfD istrue, record that the newly created binding may be deleted by a subsequent DeleteBinding call.
Returnunused.
9.1.1.1.3 CreateImmutableBinding (N,S )
The CreateImmutableBinding concrete method of aDeclarative Environment RecordenvRec takes argumentsN (a String) andS (a Boolean) and returns anormal completion containingunused. It creates a new immutable binding for the nameN that is uninitialized. A binding must not already exist in thisEnvironment Record forN. IfS istrue, the new binding is marked as a strict binding. It performs the following steps when called:
Assert:envRec does not already have a binding forN.
Create an immutable binding inenvRec forN and record that it is uninitialized. IfS istrue, record that the newly created binding is a strict binding.
Returnunused.
9.1.1.1.4 InitializeBinding (N,V )
The InitializeBinding concrete method of aDeclarative Environment RecordenvRec takes argumentsN (a String) andV (anECMAScript language value) and returns anormal completion containingunused. It is used to set the bound value of the current binding of the identifier whose name isN to the valueV. An uninitialized binding forN must already exist. It performs the following steps when called:
Assert:envRec must have an uninitialized binding forN.
Set the bound value forN inenvRec toV.
Record that the binding forN inenvRec has been initialized.
Returnunused.
9.1.1.1.5 SetMutableBinding (N,V,S )
The SetMutableBinding concrete method of aDeclarative Environment RecordenvRec takes argumentsN (a String),V (anECMAScript language value), andS (a Boolean) and returns either anormal completion containingunused or athrow completion. It attempts to change the bound value of the current binding of the identifier whose name isN to the valueV. A binding forN normally already exists, but in rare cases it may not. If the binding is an immutable binding, aTypeError is thrown ifS istrue. It performs the following steps when called:
IfenvRec does not have a binding forN, then
IfS istrue, throw aReferenceError exception.
Perform ! envRec.CreateMutableBinding(N,true).
Perform ! envRec.InitializeBinding(N,V).
Returnunused.
If the binding forN inenvRec is a strict binding, setS totrue.
If the binding forN inenvRec has not yet been initialized, then
Throw aReferenceError exception.
Else if the binding forN inenvRec is a mutable binding, then
Change its bound value toV.
Else,
Assert: This is an attempt to change the value of an immutable binding.
IfS istrue, throw aTypeError exception.
Returnunused.
Note
An example of ECMAScript code that results in a missing binding at step1 is:
functionf() {eval("var x; x = (delete x, 0);"); }
9.1.1.1.6 GetBindingValue (N,S )
The GetBindingValue concrete method of aDeclarative Environment RecordenvRec takes argumentsN (a String) andS (a Boolean) and returns either anormal completion containing anECMAScript language value or athrow completion. It returns the value of its bound identifier whose name isN. If the binding exists but is uninitialized aReferenceError is thrown, regardless of the value ofS. It performs the following steps when called:
If the binding forN inenvRec is an uninitialized binding, throw aReferenceError exception.
Return the value currently bound toN inenvRec.
9.1.1.1.7 DeleteBinding (N )
The DeleteBinding concrete method of aDeclarative Environment RecordenvRec takes argumentN (a String) and returns anormal completion containing a Boolean. It can only delete bindings that have been explicitly designated as being subject to deletion. It performs the following steps when called:
If the binding forN inenvRec cannot be deleted, returnfalse.
Remove the binding forN fromenvRec.
Returntrue.
9.1.1.1.8 HasThisBinding ( )
The HasThisBinding concrete method of aDeclarative Environment RecordenvRec takes no arguments and returnsfalse. It performs the following steps when called:
The HasSuperBinding concrete method of aDeclarative Environment RecordenvRec takes no arguments and returnsfalse. It performs the following steps when called:
The WithBaseObject concrete method of aDeclarative Environment RecordenvRec takes no arguments and returnsundefined. It performs the following steps when called:
Returnundefined.
9.1.1.2 Object Environment Records
EachObject Environment Record is associated with an object called itsbinding object. An Object Environment Record binds the set of string identifier names that directly correspond to theproperty names of its binding object.Property keys that are not strings in the form of anIdentifierName are not included in the set of bound identifiers. Both own and inherited properties are included in the set regardless of the setting of their[[Enumerable]] attribute. Because properties can be dynamically added and deleted from objects, the set of identifiers bound by an Object Environment Record may potentially change as a side-effect of any operation that adds or deletes properties. Any bindings that are created as a result of such a side-effect are considered to be a mutable binding even if the Writable attribute of the corresponding property isfalse. Immutable bindings do not exist for Object Environment Records.
Object Environment Records created forwith statements (14.11) can provide their binding object as an implicitthis value for use in function calls. The capability is controlled by a Boolean[[IsWithEnvironment]] field.
Object Environment Records have the additional state fields listed inTable 15.
Indicates whether thisEnvironment Record is created for awith statement.
9.1.1.2.1 HasBinding (N )
The HasBinding concrete method of anObject Environment RecordenvRec takes argumentN (a String) and returns either anormal completion containing a Boolean or athrow completion. It determines if its associated binding object has a property whose name isN. It performs the following steps when called:
LetbindingObject beenvRec.[[BindingObject]].
LetfoundBinding be ? HasProperty(bindingObject,N).
The CreateMutableBinding concrete method of anObject Environment RecordenvRec takes argumentsN (a String) andD (a Boolean) and returns either anormal completion containingunused or athrow completion. It creates in anEnvironment Record's associated binding object a property whose name isN and initializes it to the valueundefined. IfD istrue, the new property's[[Configurable]] attribute is set totrue; otherwise it is set tofalse. It performs the following steps when called:
NormallyenvRec will not have a binding forN but if it does, the semantics ofDefinePropertyOrThrow may result in an existing binding being replaced or shadowed or cause anabrupt completion to be returned.
9.1.1.2.3 CreateImmutableBinding (N,S )
The CreateImmutableBinding concrete method of anObject Environment Record is never used within this specification.
In this specification, all uses of CreateMutableBinding forObject Environment Records are immediately followed by a call to InitializeBinding for the same name. Hence, this specification does not explicitly track the initialization state of bindings inObject Environment Records.
9.1.1.2.5 SetMutableBinding (N,V,S )
The SetMutableBinding concrete method of anObject Environment RecordenvRec takes argumentsN (a String),V (anECMAScript language value), andS (a Boolean) and returns either anormal completion containingunused or athrow completion. It attempts to set the value of theEnvironment Record's associated binding object's property whose name isN to the valueV. A property namedN normally already exists but if it does not or is not currently writable, error handling is determined byS. It performs the following steps when called:
The GetBindingValue concrete method of anObject Environment RecordenvRec takes argumentsN (a String) andS (a Boolean) and returns either anormal completion containing anECMAScript language value or athrow completion. It returns the value of its associated binding object's property whose name isN. The property should already exist but if it does not the result depends uponS. It performs the following steps when called:
The DeleteBinding concrete method of anObject Environment RecordenvRec takes argumentN (a String) and returns either anormal completion containing a Boolean or athrow completion. It can only delete bindings that correspond to properties of the environment object whose[[Configurable]] attribute have the valuetrue. It performs the following steps when called:
LetbindingObject beenvRec.[[BindingObject]].
Return ? bindingObject.[[Delete]](N).
9.1.1.2.8 HasThisBinding ( )
The HasThisBinding concrete method of anObject Environment RecordenvRec takes no arguments and returnsfalse. It performs the following steps when called:
The HasSuperBinding concrete method of anObject Environment RecordenvRec takes no arguments and returnsfalse. It performs the following steps when called:
The WithBaseObject concrete method of anObject Environment RecordenvRec takes no arguments and returns an Object orundefined. It performs the following steps when called:
AFunction Environment Record is aDeclarative Environment Record that is used to represent the top-level scope of a function and, if the function is not anArrowFunction, provides athis binding. If a function is not anArrowFunction function and referencessuper, its Function Environment Record also contains the state that is used to performsuper method invocations from within the function.
Function Environment Records have the additional state fields listed inTable 16.
If thisEnvironment Record was created by the[[Construct]] internal method,[[NewTarget]] is the value of the[[Construct]]newTarget parameter. Otherwise, its value isundefined.
Function Environment Records support all of theDeclarative Environment Record methods listed inTable 14 and share the same specifications for all of those methods except for HasThisBinding and HasSuperBinding. In addition, Function Environment Records support the methods listed inTable 17:
The HasThisBinding concrete method of aFunction Environment RecordenvRec takes no arguments and returns a Boolean. It performs the following steps when called:
The HasSuperBinding concrete method of aFunction Environment RecordenvRec takes no arguments and returns a Boolean. It performs the following steps when called:
The abstract operation GetSuperBase takes argumentenvRec (aFunction Environment Record) and returns an Object,null, orundefined. It returns the object that is the base forsuper property accesses bound inenvRec. The valueundefined indicates that such accesses will produce runtime errors. It performs the following steps when called:
AGlobal Environment Record is used to represent the outer most scope that is shared by all of the ECMAScriptScript elements that are processed in a commonrealm. A Global Environment Record provides the bindings for built-in globals (clause19), properties of theglobal object, and for all top-level declarations (8.2.9,8.2.11) that occur within aScript.
The HasBinding concrete method of aGlobal Environment RecordenvRec takes argumentN (a String) and returns either anormal completion containing a Boolean or athrow completion. It determines if the argument identifier is one of the identifiers bound by the record. It performs the following steps when called:
LetDclRec beenvRec.[[DeclarativeRecord]].
If ! DclRec.HasBinding(N) istrue, returntrue.
LetObjRec beenvRec.[[ObjectRecord]].
Return ? ObjRec.HasBinding(N).
9.1.1.4.2 CreateMutableBinding (N,D )
The CreateMutableBinding concrete method of aGlobal Environment RecordenvRec takes argumentsN (a String) andD (a Boolean) and returns either anormal completion containingunused or athrow completion. It creates a new mutable binding for the nameN that is uninitialized. The binding is created in the associated DeclarativeRecord. A binding forN must not already exist in the DeclarativeRecord. IfD istrue, the new binding is marked as being subject to deletion. It performs the following steps when called:
LetDclRec beenvRec.[[DeclarativeRecord]].
If ! DclRec.HasBinding(N) istrue, throw aTypeError exception.
Return ! DclRec.CreateMutableBinding(N,D).
9.1.1.4.3 CreateImmutableBinding (N,S )
The CreateImmutableBinding concrete method of aGlobal Environment RecordenvRec takes argumentsN (a String) andS (a Boolean) and returns either anormal completion containingunused or athrow completion. It creates a new immutable binding for the nameN that is uninitialized. A binding must not already exist in thisEnvironment Record forN. IfS istrue, the new binding is marked as a strict binding. It performs the following steps when called:
LetDclRec beenvRec.[[DeclarativeRecord]].
If ! DclRec.HasBinding(N) istrue, throw aTypeError exception.
Return ! DclRec.CreateImmutableBinding(N,S).
9.1.1.4.4 InitializeBinding (N,V )
The InitializeBinding concrete method of aGlobal Environment RecordenvRec takes argumentsN (a String) andV (anECMAScript language value) and returns either anormal completion containingunused or athrow completion. It is used to set the bound value of the current binding of the identifier whose name isN to the valueV. An uninitialized binding forN must already exist. It performs the following steps when called:
The SetMutableBinding concrete method of aGlobal Environment RecordenvRec takes argumentsN (a String),V (anECMAScript language value), andS (a Boolean) and returns either anormal completion containingunused or athrow completion. It attempts to change the bound value of the current binding of the identifier whose name isN to the valueV. If the binding is an immutable binding andS istrue, aTypeError is thrown. A property namedN normally already exists but if it does not or is not currently writable, error handling is determined byS. It performs the following steps when called:
LetDclRec beenvRec.[[DeclarativeRecord]].
If ! DclRec.HasBinding(N) istrue, then
Return ? DclRec.SetMutableBinding(N,V,S).
LetObjRec beenvRec.[[ObjectRecord]].
Return ? ObjRec.SetMutableBinding(N,V,S).
9.1.1.4.6 GetBindingValue (N,S )
The GetBindingValue concrete method of aGlobal Environment RecordenvRec takes argumentsN (a String) andS (a Boolean) and returns either anormal completion containing anECMAScript language value or athrow completion. It returns the value of its bound identifier whose name isN. If the binding is an uninitialized binding throw aReferenceError exception. A property namedN normally already exists but if it does not or is not currently writable, error handling is determined byS. It performs the following steps when called:
LetDclRec beenvRec.[[DeclarativeRecord]].
If ! DclRec.HasBinding(N) istrue, then
Return ? DclRec.GetBindingValue(N,S).
LetObjRec beenvRec.[[ObjectRecord]].
Return ? ObjRec.GetBindingValue(N,S).
9.1.1.4.7 DeleteBinding (N )
The DeleteBinding concrete method of aGlobal Environment RecordenvRec takes argumentN (a String) and returns either anormal completion containing a Boolean or athrow completion. It can only delete bindings that have been explicitly designated as being subject to deletion. It performs the following steps when called:
The HasThisBinding concrete method of aGlobal Environment RecordenvRec takes no arguments and returnstrue. It performs the following steps when called:
The HasSuperBinding concrete method of aGlobal Environment RecordenvRec takes no arguments and returnsfalse. It performs the following steps when called:
The WithBaseObject concrete method of aGlobal Environment RecordenvRec takes no arguments and returnsundefined. It performs the following steps when called:
The abstract operation HasLexicalDeclaration takes argumentsenvRec (aGlobal Environment Record) andN (a String) and returns a Boolean. It determines if the argument identifier has a binding inenvRec that was created using a lexical declaration such as aLexicalDeclaration or aClassDeclaration. It performs the following steps when called:
The abstract operation HasRestrictedGlobalProperty takes argumentsenvRec (aGlobal Environment Record) andN (a String) and returns either anormal completion containing a Boolean or athrow completion. It determines if the argument identifier is the name of a property of theglobal object that must not be shadowed by a global lexical binding. It performs the following steps when called:
LetObjRec beenvRec.[[ObjectRecord]].
LetglobalObject beObjRec.[[BindingObject]].
LetexistingProp be ? globalObject.[[GetOwnProperty]](N).
Properties may exist upon aglobal object that were directly created rather than being declared using a var or function declaration. A global lexical binding may not be created that has the same name as a non-configurable property of theglobal object. The global property"undefined" is an example of such a property.
9.1.1.4.14 CanDeclareGlobalVar (envRec,N )
The abstract operation CanDeclareGlobalVar takes argumentsenvRec (aGlobal Environment Record) andN (a String) and returns either anormal completion containing a Boolean or athrow completion. It determines if a correspondingCreateGlobalVarBinding call would succeed if called for the same argumentN. Redundant var declarations and var declarations for pre-existingglobal object properties are allowed. It performs the following steps when called:
IfIsDataDescriptor(existingProp) istrue andexistingProp has attribute values {[[Writable]]:true,[[Enumerable]]:true }, returntrue.
Returnfalse.
9.1.1.4.16 CreateGlobalVarBinding (envRec,N,D )
The abstract operation CreateGlobalVarBinding takes argumentsenvRec (aGlobal Environment Record),N (a String), andD (a Boolean) and returns either anormal completion containingunused or athrow completion. It creates and initializes a mutable binding in the associatedObject Environment Record. If a binding already exists, it is reused and assumed to be initialized. It performs the following steps when called:
Global function declarations are always represented as own properties of theglobal object. If possible, an existing own property is reconfigured to have a standard set of attribute values. Step7 is equivalent to what calling the InitializeBinding concrete method would do and ifglobalObject is a Proxy will produce the same sequence of Proxy trap calls.
9.1.1.5 Module Environment Records
AModule Environment Record is aDeclarative Environment Record that is used to represent the outer scope of an ECMAScriptModule. In additional to normal mutable and immutable bindings, Module Environment Records also provide immutable import bindings which are bindings that provide indirect access to a target binding that exists in anotherEnvironment Record.
Module Environment Records support all of theDeclarative Environment Record methods listed inTable 14 and share the same specifications for all of those methods except for GetBindingValue, DeleteBinding, HasThisBinding and GetThisBinding. In addition, Module Environment Records support the methods listed inTable 20:
The GetBindingValue concrete method of aModule Environment RecordenvRec takes argumentsN (a String) andS (a Boolean) and returns either anormal completion containing anECMAScript language value or athrow completion. It returns the value of its bound identifier whose name isN. However, if the binding is an indirect binding the value of the target binding is returned. If the binding exists but is uninitialized aReferenceError is thrown. It performs the following steps when called:
The HasThisBinding concrete method of aModule Environment RecordenvRec takes no arguments and returnstrue. It performs the following steps when called:
The abstract operation CreateImportBinding takes argumentsenvRec (aModule Environment Record),N (a String),M (aModule Record), andN2 (a String) and returnsunused. It creates a new initialized immutable indirect binding for the nameN. A binding must not already exist inenvRec forN.N2 is the name of a binding that exists inM'sModule Environment Record. Accesses to the value of the new binding will indirectly access the bound value of the target binding. It performs the following steps when called:
Assert:envRec does not already have a binding forN.
Assert: WhenM.[[Environment]] is instantiated, it will have a direct binding forN2.
Create an immutable indirect binding inenvRec forN that referencesM andN2 as its target binding and record that the binding is initialized.
The abstract operation NewObjectEnvironment takes argumentsO (an Object),W (a Boolean), andE (anEnvironment Record ornull) and returns anObject Environment Record. It performs the following steps when called:
The abstract operation NewFunctionEnvironment takes argumentsF (an ECMAScriptfunction object) andnewTarget (an Object orundefined) and returns aFunction Environment Record. It performs the following steps when called:
The abstract operation NewGlobalEnvironment takes argumentsG (an Object) andthisValue (an Object) and returns aGlobal Environment Record. It performs the following steps when called:
The abstract operation ResolvePrivateIdentifier takes argumentsprivateEnv (aPrivateEnvironment Record) andidentifier (a String) and returns aPrivate Name. It performs the following steps when called:
Before it is evaluated, all ECMAScript code must be associated with arealm. Conceptually, arealm consists of a set of intrinsic objects, an ECMAScript global environment, all of the ECMAScript code that is loaded within the scope of that global environment, and other associated state and resources.
Arealm is represented in this specification as aRealm Record with the fields specified inTable 22:
Template objects are canonicalized separately for eachrealm using itsRealm Record's[[TemplateMap]]. Each[[Site]] value is aParse Node that is aTemplateLiteral. The associated[[Array]] value is the corresponding template object that is passed to a tag function.
Note 1
Once aParse Node becomes unreachable, the corresponding[[Array]] is also unreachable, and it would be unobservable if an implementation removed the pair from the[[TemplateMap]] list.
A map from the specifier strings imported by thisrealm to the resolvedModule Record. The list does not contain two differentRecordsr1 andr2 such thatModuleRequestsEqual(r1,r2) istrue.
Field reserved for use byhosts that need to associate additional information with aRealm Record.
9.3.1 InitializeHostDefinedRealm ( )
The abstract operation InitializeHostDefinedRealm takes no arguments and returns either anormal completion containingunused or athrow completion. It performs the following steps when called:
Set fields ofrealmRec.[[Intrinsics]] with the values listed inTable 6. The field names are the names listed in column one of the table. The value of each field is a new object value fully and recursively populated with property values as defined by the specification of each object in clauses19 through28. All object property values are newly created object values. All values that are built-infunction objects are created by performingCreateBuiltinFunction(steps,length,name,slots,realmRec,prototype) wheresteps is the definition of that function provided by this specification,name is the initial value of the function's"name" property,length is the initial value of the function's"length" property,slots is a list of the names, if any, of the function's specified internal slots, andprototype is the specified value of the function's[[Prototype]] internal slot. The creation of the intrinsics and their properties must be ordered to avoid any dependencies upon objects that have not yet been created.
Letdesc be the fully populated dataProperty Descriptor for the property, containing the specified attributes for the property. For properties listed in19.2,19.3, or19.4 the value of the[[Value]] attribute is the corresponding intrinsic object fromrealmRec.
Anexecution context is a specification device that is used to track the runtime evaluation of code by an ECMAScript implementation. At any point in time, there is at most one execution context peragent that is actually executing code. This is known as theagent'srunning execution context. All references to therunning execution context in this specification denote therunning execution context of thesurrounding agent.
Theexecution context stack is used to track execution contexts. Therunning execution context is always the top element of this stack. A new execution context is created whenever control is transferred from the executable code associated with the currentlyrunning execution context to executable code that is not associated with that execution context. The newly created execution context is pushed onto the stack and becomes therunning execution context.
An execution context contains whatever implementation specific state is necessary to track the execution progress of its associated code. Each execution context has at least the state components listed inTable 23.
Table 23: State Components for All Execution Contexts
Component
Purpose
code evaluation state
Any state needed to perform, suspend, and resume evaluation of the code associated with thisexecution context.
Evaluation of code by therunning execution context may be suspended at various points defined within this specification. Once therunning execution context has been suspended a different execution context may become therunning execution context and commence evaluating its code. At some later time a suspended execution context may again become therunning execution context and continue evaluating its code at the point where it had previously been suspended. Transition of therunning execution context status among execution contexts usually occurs in stack-like last-in/first-out manner. However, some ECMAScript features require non-LIFO transitions of therunning execution context.
In most situations only therunning execution context (the top of theexecution context stack) is directly manipulated by algorithms within this specification. Hence when the terms “LexicalEnvironment”, and “VariableEnvironment” are used without qualification they are in reference to those components of therunning execution context.
An execution context is purely a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation. It is impossible for ECMAScript code to directly access or observe an execution context.
9.4.1 GetActiveScriptOrModule ( )
The abstract operation GetActiveScriptOrModule takes no arguments and returns aScript Record, aModule Record, ornull. It is used to determine the running script or module, based on therunning execution context. It performs the following steps when called:
If no suchexecution context exists, returnnull; otherwise returnec's ScriptOrModule.
9.4.2 ResolveBinding (name [ ,env ] )
The abstract operation ResolveBinding takes argumentname (a String) and optional argumentenv (anEnvironment Record orundefined) and returns either anormal completion containing aReference Record or athrow completion. It is used to determine the binding ofname.env can be used to explicitly provide theEnvironment Record that is to be searched for the binding. It performs the following steps when called:
The result of ResolveBinding is always aReference Record whose[[ReferencedName]] field isname.
9.4.3 GetThisEnvironment ( )
The abstract operation GetThisEnvironment takes no arguments and returns anEnvironment Record. It finds theEnvironment Record that currently supplies the binding of thekeywordthis. It performs the following steps when called:
The abstract operation GetNewTarget takes no arguments and returns an Object orundefined. It determines the NewTarget value using the LexicalEnvironment of therunning execution context. It performs the following steps when called:
The abstract operation GetGlobalObject takes no arguments and returns an Object. It returns theglobal object used by the currentlyrunning execution context. It performs the following steps when called:
At some future point in time, when there is no running context in theagent for which the job is scheduled and thatagent'sexecution context stack is empty, the implementation must:
Host environments are not required to treatJobs uniformly with respect to scheduling. For example, web browsers and Node.js treat Promise-handlingJobs as a higher priority than other work; future features may addJobs that are not treated at such a high priority.
At any particular time,scriptOrModule (aScript Record, aModule Record, ornull) is theactive script or module if all of the following conditions are true:
The specific choice ofRealm is up to thehost environment. This initialexecution context andRealm is only in use before any callback function is invoked. When a callback function related to aJob, like a Promise handler, is invoked, the invocation pushes its ownexecution context andRealm.
Particular kinds ofJobs have additional conformance requirements.
The WHATWG HTML specification (https://html.spec.whatwg.org/), for example, uses thehost-defined value to propagate the incumbent settings object for Promise callbacks.
JobCallback Records have the fields listed inTable 26.
The default implementation of HostMakeJobCallback performs the following steps when called:
Return theJobCallback Record {[[Callback]]:callback,[[HostDefined]]:empty }.
ECMAScripthosts that are not web browsers must use the default implementation of HostMakeJobCallback.
Note
This is called at the time that the callback is passed to the function that is responsible for its being eventually scheduled and run. For example,promise.then(thenAction) calls MakeJobCallback onthenAction at the time of invokingPromise.prototype.then, not at the time of scheduling the reactionJob.
ECMAScripthosts that are not web browsers must use the default implementation of HostCallJobCallback.
9.5.4 HostEnqueueGenericJob (job,realm )
Thehost-defined abstract operation HostEnqueueGenericJob takes argumentsjob (aJobAbstract Closure) andrealm (aRealm Record) and returnsunused. It schedulesjob in therealmrealm in theagent signified byrealm.[[AgentSignifier]] to be performed at some future time. TheAbstract Closures used with this algorithm are intended to be scheduled without additional constraints, such as priority and ordering.
An implementation of HostEnqueueGenericJob must conform to the requirements in9.5.
9.5.5 HostEnqueuePromiseJob (job,realm )
Thehost-defined abstract operation HostEnqueuePromiseJob takes argumentsjob (aJobAbstract Closure) andrealm (aRealm Record ornull) and returnsunused. It schedulesjob to be performed at some future time. TheAbstract Closures used with this algorithm are intended to be related to the handling of Promises, or otherwise, to be scheduled with equal priority to Promise handling operations.
An implementation of HostEnqueuePromiseJob must conform to the requirements in9.5 as well as the following:
LetscriptOrModule beGetActiveScriptOrModule() at the time HostEnqueuePromiseJob is invoked. Ifrealm is notnull, each timejob is invoked the implementation must performimplementation-defined steps such thatscriptOrModule is theactive script or module at the time ofjob's invocation.
Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.
Thehost-defined abstract operation HostEnqueueTimeoutJob takes argumentstimeoutJob (aJobAbstract Closure),realm (aRealm Record), andmilliseconds (a non-negativefinite Number) and returnsunused. It schedulestimeoutJob in therealmrealm in theagent signified byrealm.[[AgentSignifier]] to be performed after at leastmilliseconds milliseconds.
An implementation of HostEnqueueTimeoutJob must conform to the requirements in9.5.
The default value computed for theisLittleEndian parameter when it is needed by the algorithmsGetValueFromBuffer andSetValueInBuffer. The choice isimplementation-defined and should be the alternative that is most efficient for the implementation. Once the value has been observed it cannot change.
Initially 0, used to assign unique incrementing values to the[[AsyncEvaluationOrder]] field of modules that are asynchronous or have asynchronous dependencies.
Once the values of[[Signifier]],[[IsLockFree1]], and[[IsLockFree2]] have been observed by anyagent in theagent cluster they cannot change.
Note 2
The values of[[IsLockFree1]] and[[IsLockFree2]] are not necessarily determined by the hardware, but may also reflect implementation choices that can vary over time and between ECMAScript implementations.
There is no[[IsLockFree4]] field: 4-byte atomic operations are always lock-free.
In practice, if an atomic operation is implemented with any type of lock the operation is not lock-free. Lock-free does not imply wait-free: there is no upper bound on how many machine steps may be required to complete a lock-free atomic operation.
That an atomic access of sizen is lock-free does not imply anything about the (perceived) atomicity of non-atomic accesses of sizen, specifically, non-atomic accesses may still be performed as a sequence of several separate memory accesses. SeeReadSharedMemory andWriteSharedMemory for details.
Note 3
Anagent is a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation.
9.6.1 AgentSignifier ( )
The abstract operation AgentSignifier takes no arguments and returns anagent signifier. It performs the following steps when called:
In some environments it may not be reasonable for a givenagent to suspend. For example, in a web browser environment, it may be reasonable to disallow suspending a document's main event handling thread, while still allowing workers' event handling threads to suspend.
9.6.3 IncrementModuleAsyncEvaluationCount ( )
The abstract operation IncrementModuleAsyncEvaluationCount takes no arguments and returns aninteger. It performs the following steps when called:
This value is only used to keep track of the relative evaluation order between pending modules. An implementation may unobservably reset[[ModuleAsyncEvaluationCount]] to 0 whenever there are no pending modules.
9.7 Agent Clusters
Anagent cluster is a maximal set ofagents that can communicate by operating on shared memory.
Note 1
Programs within differentagents may share memory by unspecified means. At a minimum, the backing memory for SharedArrayBuffers can be shared among theagents in the cluster.
There may beagents that can communicate by message passing that cannot share memory; they are never in the same agent cluster.
Theagents in a cluster need not all be alive at some particular point in time. IfagentA creates anotheragentB, after whichA terminates andB createsagentC, the threeagents are in the same cluster ifA could share some memory withB andB could share some memory withC.
Allagents within a cluster must have the same value for the[[LittleEndian]] field in their respectiveAgent Records.
Note 3
If differentagents within an agent cluster have different values of[[LittleEndian]] it becomes hard to use shared memory for multi-byte data.
Allagents within a cluster must have the same values for the[[IsLockFree1]] field in their respectiveAgent Records; similarly for the[[IsLockFree2]] field.
Allagents within a cluster must have different values for the[[Signifier]] field in their respectiveAgent Records.
An embedding may deactivate (stop forward progress) or activate (resume forward progress) anagent without theagent's knowledge or cooperation. If the embedding does so, it must not leave someagents in the cluster active while otheragents in the cluster are deactivated indefinitely.
Note 4
The purpose of the preceding restriction is to avoid a situation where anagent deadlocks or starves because anotheragent has been deactivated. For example, if an HTML shared worker that has a lifetime independent of documents in any windows were allowed to share memory with the dedicated worker of such an independent document, and the document and its dedicated worker were to be deactivated while the dedicated worker holds a lock (say, the document is pushed into its window's history), and the shared worker then tries to acquire the lock, then the shared worker will be blocked until the dedicated worker is activated again, if ever. Meanwhile other workers trying to access the shared worker from other windows will starve.
The implication of the restriction is that it will not be possible to share memory betweenagents that don't belong to the same suspend/wake collective within the embedding.
An embedding may terminate anagent without any of theagent's cluster's otheragents' prior knowledge or cooperation. If anagent is terminated not by programmatic action of its own or of anotheragent in the cluster but by forces external to the cluster, then the embedding must choose one of two strategies: Either terminate all theagents in the cluster, or provide reliable APIs that allow theagents in the cluster to coordinate so that at least one remaining member of the cluster will be able to detect the termination, with the termination data containing enough information to identify theagent that was terminated.
Note 5
Examples of that type of termination are: operating systems or users terminatingagents that are running in separate processes; the embedding itself terminating anagent that is running in-process with the otheragents when per-agent resource accounting indicates that theagent is runaway.
Each of the following specification values, and values transitively reachable from them, belong to exactly one agent cluster.
An agent cluster is a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation.
9.8 Forward Progress
For anagent tomake forward progress is for it to perform an evaluation step according to this specification.
Anagent becomesblocked when itsrunning execution context waits synchronously and indefinitely for an external event. Onlyagents whoseAgent Record's[[CanBlock]] field istrue can become blocked in this sense. Anunblockedagent is one that is not blocked.
Implementations must ensure that:
every unblockedagent with a dedicatedexecuting thread eventually makes forward progress
anagent does not cause anotheragent to become blocked except via explicit APIs that provide blocking.
Note
This, along with the liveness guarantee in thememory model, ensures that allseq-cst writes eventually become observable to allagents.
9.9 Processing Model of WeakRef and FinalizationRegistry Targets
9.9.1 Objectives
This specification does not make any guarantees that any object or symbol will be garbage collected. Objects or symbols which are notlive may be released after long periods of time, or never at all. For this reason, this specification uses the term "may" when describing behaviour triggered by garbage collection.
The semantics ofWeakRefs andFinalizationRegistrys is based on two operations which happen at particular points in time:
WhenWeakRef.prototype.deref is called, the referent (ifundefined is not returned) is kept alive so that subsequent, synchronous accesses also return the same value. This list is reset when synchronous work is done using theClearKeptObjects abstract operation.
Some ECMAScript implementations include garbage collector implementations which run in the background, including when ECMAScript is idle. Letting thehost environment scheduleCleanupFinalizationRegistry allows it to resume ECMAScript execution in order to run finalizer work, which may free up held values, reducing overall memory usage.
9.9.2 Liveness
For some set of objects and/or symbolsS ahypothetical WeakRef-oblivious execution with respect toS is an execution whereby the abstract operationWeakRefDeref of aWeakRef whose referent is an element ofS always returnsundefined.
Note 1
WeakRef-obliviousness, together with liveness, capture two notions. One, that aWeakRef itself does not keep its referent alive. Two, that cycles in liveness does not imply that a value is live. To be concrete, if determiningv's liveness depends on determining the liveness of aWeakRef referent,r,r's liveness cannot assumev's liveness, which would be circular reasoning.
Note 2
WeakRef-obliviousness is defined on sets of objects or symbols instead of individual values to account for cycles. If it were defined on individual values, then aWeakRef referent in a cycle will be considered live even though its identity is only observed via otherWeakRef referents in the cycle.
Note 3
Colloquially, we say that an individual object or symbol is live if every set containing it is live.
At any point during evaluation, a set of objects and/or symbolsS is consideredlive if either of the following conditions is met:
Any element inS is included in anyagent's[[KeptAlive]]List.
There exists a valid future hypothetical WeakRef-oblivious execution with respect toS that observes the identity of any value inS.
Note 4
The second condition above intends to capture the intuition that a value is live if its identity is observable via non-WeakRef means. A value's identity may be observed by observing a strict equality comparison or observing the value being used as key in a Map.
Note 5
Presence of an object or a symbol in a field, an internal slot, or a property does not imply that the value is live. For example if the value in question is never passed back to the program, then it cannot be observed.
This is the case for keys in a WeakMap, members of a WeakSet, as well as the[[WeakRefTarget]] and[[UnregisterToken]] fields of aFinalizationRegistry Cell record.
The above definition implies that, if a key in a WeakMap is not live, then its corresponding value is not necessarily live either.
Note 6
Liveness is the lower bound for guaranteeing whichWeakRefs engines must not empty. Liveness as defined here is undecidable. In practice, engines use conservative approximations such as reachability. There is expected to be significant implementation leeway.
9.9.3 Execution
At any time, if a set of objects and/or symbolsS is notlive, an ECMAScript implementation may perform the following steps atomically:
For each elementvalue ofS, do
For eachWeakRefref such thatref.[[WeakRefTarget]] isvalue, do
Setref.[[WeakRefTarget]] toempty.
For eachFinalizationRegistryfg such thatfg.[[Cells]] contains aRecordcell such thatcell.[[WeakRefTarget]] isvalue, do
For each WeakMapmap such thatmap.[[WeakMapData]] contains aRecordr such thatr.[[Key]] isvalue, do
Setr.[[Key]] toempty.
Setr.[[Value]] toempty.
For each WeakSetset such thatset.[[WeakSetData]] containsvalue, do
Replace the element ofset.[[WeakSetData]] whose value isvalue with an element whose value isempty.
Note 1
Together with the definition of liveness, this clause prescribes optimizations that an implementation may apply regardingWeakRefs.
It is possible to access an object without observing its identity. Optimizations such as dead variable elimination and scalar replacement on properties of non-escaping objects whose identity is not observed are allowed. These optimizations are thus allowed to observably emptyWeakRefs that point to such objects.
On the other hand, if an object's identity is observable, and that object is in the[[WeakRefTarget]] internal slot of aWeakRef, optimizations such as rematerialization that observably empty theWeakRef are prohibited.
Implementations are not obligated to emptyWeakRefs for maximal sets of non-live objects or symbols.
If an implementation chooses a non-live setS in which to emptyWeakRefs, this definition requires that it emptiesWeakRefs for all values inS simultaneously. In other words, it is not conformant for an implementation to empty aWeakRef pointing to a valuev without emptying out otherWeakRefs that, if not emptied, could result in an execution that observes the value ofv.
An implementation of HostEnqueueFinalizationRegistryCleanupJob schedulescleanupJob to be performed at some future time, if possible. It must also conform to the requirements in9.5.
9.10 ClearKeptObjects ( )
The abstract operation ClearKeptObjects takes no arguments and returnsunused. ECMAScript implementations are expected to call ClearKeptObjects when a synchronous sequence of ECMAScript executions completes. It performs the following steps when called:
When the abstract operation AddToKeptObjects is called with a target object or symbol, it adds the target to a list that will point strongly at the target untilClearKeptObjects is called.
The abstract operation CanBeHeldWeakly takes argumentv (anECMAScript language value) and returns a Boolean. It returnstrue if and only ifv is suitable for use as a weak reference. Only values that are suitable for use as a weak reference may be a key of a WeakMap, an element of a WeakSet, the target of aWeakRef, or one of the targets of aFinalizationRegistry. It performs the following steps when called:
A language value withoutlanguage identity can be manifested without prior reference and is unsuitable for use as a weak reference. A Symbol value produced bySymbol.for, unlike other Symbol values, does not have language identity and is unsuitable for use as a weak reference.Well-known symbols are likely to never be collected, but are nonetheless treated as suitable for use as a weak reference because they are limited in number and therefore manageable by a variety of implementation approaches. However, any value associated to a well-known symbol in alive WeakMap is unlikely to be collected and could “leak” memory resources in implementations.