This Ecma Standard defines the ECMAScript 2021 Language. It is the twelfth edition of the ECMAScript Language Specification. Since publication of the first edition in 1997, ECMAScript has grown to be one of the world's most widely used general-purpose programming languages. It is best known as the language embedded in web browsers but has also been widely adopted for server and embedded applications.
ECMAScript is based on several originating technologies, the most well-known being JavaScript (Netscape) and JScript (Microsoft). The language was invented by Brendan Eich at Netscape and first appeared in that company's Navigator 2.0 browser. It has appeared in all subsequent browsers from Netscape and in all browsers from Microsoft starting with Internet Explorer 3.0.
The development of the ECMAScript Language Specification started in November 1996. The first edition of this Ecma Standard was adopted by the Ecma General Assembly of June 1997.
That Ecma Standard was submitted to ISO/IEC JTC 1 for adoption under the fast-track procedure, and approved as international standard ISO/IEC 16262, in April 1998. The Ecma General Assembly of June 1998 approved the second edition of ECMA-262 to keep it fully aligned with ISO/IEC 16262. Changes between the first and the second edition are editorial in nature.
The third edition of the Standard introduced powerful regular expressions, better string handling, new control statements, try/catch exception handling, tighter definition of errors, formatting for numeric output and minor changes in anticipation of future language growth. The third edition of the ECMAScript standard was adopted by the Ecma General Assembly of December 1999 and published as ISO/IEC 16262:2002 in June 2002.
After publication of the third edition, ECMAScript achieved massive adoption in conjunction with the World Wide Web where it has become the programming language that is supported by essentially all web browsers. Significant work was done to develop a fourth edition of ECMAScript. However, that work was not completed and not published as the fourth edition of ECMAScript but some of it was incorporated into the development of the sixth edition.
The fifth edition of ECMAScript (published as ECMA-262 5th edition) codified de facto interpretations of the language specification that have become common among browser implementations and added support for new features that had emerged since the publication of the third edition. Such features include accessor properties, reflective creation and inspection of objects, program control of property attributes, additional array manipulation functions, support for the JSON object encoding format, and a strict mode that provides enhanced error checking and program security. The fifth edition was adopted by the Ecma General Assembly of December 2009.
The fifth edition was submitted to ISO/IEC JTC 1 for adoption under the fast-track procedure, and approved as international standard ISO/IEC 16262:2011. Edition 5.1 of the ECMAScript Standard incorporated minor corrections and is the same text as ISO/IEC 16262:2011. The 5.1 Edition was adopted by the Ecma General Assembly of June 2011.
Focused development of the sixth edition started in 2009, as the fifth edition was being prepared for publication. However, this was preceded by significant experimentation and language enhancement design efforts dating to the publication of the third edition in 1999. In a very real sense, the completion of the sixth edition is the culmination of a fifteen year effort. The goals for this edition included providing better support for large applications, library creation, and for use of ECMAScript as a compilation target for other languages. Some of its major enhancements included modules, class declarations, lexical block scoping, iterators and generators, promises for asynchronous programming, destructuring patterns, and proper tail calls. The ECMAScript library of built-ins was expanded to support additional data abstractions including maps, sets, and arrays of binary numeric values as well as additional support for Unicode supplemental characters in strings and regular expressions. The built-ins were also made extensible via subclassing. The sixth edition provides the foundation for regular, incremental language and library enhancements. The sixth edition was adopted by the General Assembly of June 2015.
ECMAScript 2016 was the first ECMAScript edition released under Ecma TC39's new yearly release cadence and open development process. A plain-text source document was built from the ECMAScript 2015 source document to serve as the base for further development entirely on GitHub. Over the year of this standard's development, hundreds of pull requests and issues were filed representing thousands of bug fixes, editorial fixes and other improvements. Additionally, numerous software tools were developed to aid in this effort including Ecmarkup, Ecmarkdown, and Grammarkdown. ES2016 also included support for a new exponentiation operator and adds a new method to Array.prototype
called includes
.
ECMAScript 2017 introduced Async Functions, Shared Memory, and Atomics along with smaller language and library enhancements, bug fixes, and editorial updates. Async functions improve the asynchronous programming experience by providing syntax for promise-returning functions. Shared Memory and Atomics introduce a new memory model that allows multi-agent programs to communicate using atomic operations that ensure a well-defined execution order even on parallel CPUs. It also included new static methods on Object: Object.values
, Object.entries
, and Object.getOwnPropertyDescriptors
.
ECMAScript 2018 introduced support for asynchronous iteration via the AsyncIterator protocol and async generators. It also included four new regular expression features: the dotAll
flag, named capture groups, Unicode property escapes, and look-behind assertions. Lastly it included object rest and spread properties.
ECMAScript 2019 introduced a few new built-in functions: flat
and flatMap
on Array.prototype
for flattening arrays, Object.fromEntries
for directly turning the return value of Object.entries
into a new Object, and trimStart
and trimEnd
on String.prototype
as better-named alternatives to the widely implemented but non-standard String.prototype.trimLeft
and trimRight
built-ins. In addition, it included a few minor updates to syntax and semantics. Updated syntax included optional catch binding parameters and allowing U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) in string literals to align with JSON. Other updates included requiring that Array.prototype.sort
be a stable sort, requiring that JSON.stringify
return well-formed UTF-8 regardless of input, and clarifying Function.prototype.toString
by requiring that it either return the corresponding original source text or a standard placeholder.
ECMAScript 2020, the 11th edition, introduces the matchAll
method for Strings, to produce an iterator for all match objects generated by a global regular expression; import()
, a syntax to asynchronously import Modules with a dynamic specifier; BigInt
, a new number primitive for working with arbitrary precision integers; Promise.allSettled
, a new Promise combinator that does not short-circuit; globalThis
, a universal way to access the global this
value; dedicated export * as ns from 'module'
syntax for use within modules; increased standardization of for-in
enumeration order; import.meta
, a host-populated object available in Modules that may contain contextual information about the Module; as well as adding two new syntax features to improve working with “nullish” values (null
or undefined
): nullish coalescing, a value selection operator; and optional chaining, a property access and function invocation operator that short-circuits if the value to access/invoke is nullish.
This specification, the 12th edition, introduces the replaceAll
method for Strings; Promise.any
, a Promise combinator that short-circuits when an input value is fulfilled; AggregateError
, a new Error type to represent multiple errors at once; logical assignment operators (??=
, &&=
, ||=
); WeakRef
, for referring to a target object without preserving it from garbage collection, and FinalizationRegistry
, to manage registration and unregistration of cleanup operations performed when target objects are garbage collected; separators for numeric literals (1_000
); and Array.prototype.sort
was made more precise, reducing the amount of cases that result in an implementation-defined sort order.
Dozens of individuals representing many organizations have made very significant contributions within Ecma TC39 to the development of this edition and to the prior editions. In addition, a vibrant community has emerged supporting TC39's ECMAScript efforts. This community has reviewed numerous drafts, filed thousands of bug reports, performed implementation experiments, contributed test suites, and educated the world-wide developer community about ECMAScript. Unfortunately, it is impossible to identify and acknowledge every person and organization who has contributed to this effort.
Allen Wirfs-Brock
ECMA-262, Project Editor, 6th Edition
Brian Terlson
ECMA-262, Project Editor, 7th through 10th Editions
Jordan Harband
ECMA-262, Project Editor, 10th through 12th Editions
This Standard defines the ECMAScript 2021 general-purpose programming language.
A conforming implementation of ECMAScript must provide and support all the types, values, objects, properties, functions, and program syntax and semantics described in this specification.
A conforming implementation of ECMAScript must interpret source text input in conformance with the latest version of the Unicode Standard and ISO/IEC 10646.
A conforming implementation of ECMAScript that provides an application programming interface (API) that supports programs that need to adapt to the linguistic and cultural conventions used by different human languages and countries must implement the interface defined by the most recent edition of ECMA-402 that is compatible with this specification.
A conforming implementation of ECMAScript may provide additional types, values, objects, properties, and functions beyond those described in this specification. In particular, a conforming implementation of ECMAScript may provide properties not described in this specification, and values for those properties, for objects that are described in this specification.
A conforming implementation of ECMAScript may support program and regular expression syntax not described in this specification. In particular, a conforming implementation of ECMAScript may support program syntax that makes use of any “future reserved words” noted in subclause 12.6.2 of this specification.
A conforming implementation of ECMAScript must not implement any extension that is listed as a Forbidden Extension in subclause 17.1.
A conforming implementation of ECMAScript must not redefine any facilities that are not implementation-defined, implementation-approximated, or host-defined.
A conforming implementation of ECMAScript may choose to implement or not implement Normative Optional subclauses. If any Normative Optional behaviour is implemented, all of the behaviour in the containing Normative Optional clause must be implemented. A Normative Optional clause is denoted in this specification with the words "Normative Optional" in a coloured box, as shown below.
Example clause contents.
The following referenced documents are indispensable for the application of this document. For dated references, only the edition cited applies. For undated references, the latest edition of the referenced document (including any amendments) applies.
ISO/IEC 10646 Information Technology — Universal Multiple-Octet Coded Character Set (UCS) plus Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, and Amendment 4:2008, plus additional amendments and corrigenda, or successor
ECMA-402, ECMAScript 2015 Internationalization API Specification.
https://ecma-international.org/publications/standards/Ecma-402.htm
ECMA-404, The JSON Data Interchange Format.
https://ecma-international.org/publications/standards/Ecma-404.htm
This section contains a non-normative overview of the ECMAScript language.
ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. ECMAScript as defined here is not intended to be computationally self-sufficient; indeed, there are no provisions in this specification for input of external data or output of computed results. Instead, it is expected that the computational environment of an ECMAScript program will provide not only the objects and other facilities described in this specification but also certain environment-specific objects, whose description and behaviour are beyond the scope of this specification except to indicate that they may provide certain properties that can be accessed and certain functions that can be called from an ECMAScript program.
ECMAScript was originally designed to be used as a scripting language, but has become widely used as a general-purpose programming language. A scripting language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control. In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language. A scripting language is intended for use by both professional and non-professional programmers.
ECMAScript was originally designed to be a Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client-server architecture. ECMAScript is now used to provide core scripting capabilities for a variety of host environments. Therefore the core language is specified in this document apart from any particular host environment.
ECMAScript usage has moved beyond simple scripting and it is now used for the full spectrum of programming tasks in many different environments and scales. As the usage of ECMAScript has expanded, so have the features and facilities it provides. ECMAScript is now a fully featured general-purpose programming language.
A web browser provides an ECMAScript host environment for client-side computation including, for instance, objects that represent windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output. Further, the host environment provides a means to attach scripting code to events such as change of focus, page and image loading, unloading, error and abort, selection, form submission, and mouse actions. Scripting code appears within the HTML and the displayed page is a combination of user interface elements and fixed and computed text and images. The scripting code is reactive to user interaction, and there is no need for a main program.
A web server provides a different host environment for server-side computation including objects representing requests, clients, and files; and mechanisms to lock and share data. By using browser-side and server-side scripting together, it is possible to distribute computation between the client and server while providing a customized user interface for a Web-based application.
Each Web browser and server that supports ECMAScript supplies its own host environment, completing the ECMAScript execution environment.
To aid integrating ECMAScript into host environments, this specification defers the definition of certain facilities (e.g., abstract operations), either in whole or in part, to a source outside of this specification. Editorially, this specification distinguishes the following kinds of deferrals.
An implementation is an external source that further defines facilities enumerated in Annex D or those that are marked as implementation-defined or implementation-approximated. In informal use, an implementation refers to a concrete artefact, such as a particular web browser.
An implementation-defined facility is one that defers its definition to an external source without further qualification. This specification does not make any recommendations for particular behaviours, and conforming implementations are free to choose any behaviour within the constraints put forth by this specification.
An implementation-approximated facility is one that defers its definition to an external source while recommending an ideal behaviour. While conforming implementations are free to choose any behaviour within the constraints put forth by this specification, they are encouraged to strive to approximate the ideal. Some mathematical operations, such as Math.exp
, are implementation-approximated.
A host is an external source that further defines facilities listed in Annex D but does not further define other implementation-defined or implementation-approximated facilities. In informal use, a host refers to the set of all implementations, such as the set of all web browsers, that interface with this specification in the same way via Annex D. A host is often an external specification, such as WHATWG HTML (https://html.spec.whatwg.org/). In other words, facilities that are host-defined are often further defined in external specifications.
A host hook is an abstract operation that is defined in whole or in part by an external source. All host hooks must be listed in Annex D.
A host-defined facility is one that defers its definition to an external source without further qualification and is listed in Annex D. Implementations that are not hosts may also provide definitions for host-defined facilities.
A host environment is a particular choice of definition for all host-defined facilities. A host environment typically includes objects or functions which allow obtaining input and providing output as host-defined properties of the global object.
This specification follows the editorial convention of always using the most specific term. For example, if a facility is host-defined, it should not be referred to as implementation-defined.
Both hosts and implementations may interface with this specification via the language types, specification types, abstract operations, grammar productions, intrinsic objects, and intrinsic symbols defined herein.
The following is an informal overview of ECMAScript—not all parts of the language are described. This overview is not part of the standard proper.
ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects. In ECMAScript, an object is a collection of zero or more properties each with attributes that determine how each property can be used—for example, when the Writable attribute for a property is set to false, any attempt by executed ECMAScript code to assign a different value to the property fails. Properties are containers that hold other objects, primitive values, or functions. A primitive value is a member of one of the following built-in types: Undefined, Null, Boolean, Number, BigInt, String, and Symbol; an object is a member of the built-in type Object; and a function is a callable object. A function that is associated with an object via a property is called a method.
ECMAScript defines a collection of built-in objects that round out the definition of ECMAScript entities. These built-in objects include the global object; objects that are fundamental to the runtime semantics of the language including Object
, Function
, Boolean
, Symbol
, and various Error
objects; objects that represent and manipulate numeric values including Math
, Number
, and Date
; the text processing objects String
and RegExp
; objects that are indexed collections of values including Array
and nine different kinds of Typed Arrays whose elements all have a specific numeric data representation; keyed collections including Map
and Set
objects; objects supporting structured data including the JSON
object, ArrayBuffer
, SharedArrayBuffer
, and DataView
; objects supporting control abstractions including generator functions and Promise
objects; and reflection objects including Proxy
and Reflect
.
ECMAScript also defines a set of built-in operators. ECMAScript operators include various unary operations, multiplicative operators, additive operators, bitwise shift operators, relational operators, equality operators, binary bitwise operators, binary logical operators, assignment operators, and the comma operator.
Large ECMAScript programs are supported by modules which allow a program to be divided into multiple sequences of statements and declarations. Each module explicitly identifies declarations it uses that need to be provided by other modules and which of its declarations are available for use by other modules.
ECMAScript syntax intentionally resembles Java syntax. ECMAScript syntax is relaxed to enable it to serve as an easy-to-use scripting language. For example, a variable is not required to have its type declared nor are types associated with properties, and defined functions are not required to have their declarations appear textually before calls to them.
Even though ECMAScript includes syntax for class definitions, ECMAScript objects are not fundamentally class-based such as those in C++, Smalltalk, or Java. Instead objects may be created in various ways including via a literal notation or via constructors which create objects and then execute code that initializes all or part of them by assigning initial values to their properties. Each constructor is a function that has a property named "prototype" that is used to implement prototype-based inheritance and shared properties. Objects are created by using constructors in new expressions; for example, new Date(2009, 11)
creates a new Date object. Invoking a constructor without using new has consequences that depend on the constructor. For example, Date()
produces a string representation of the current date and time rather than an object.
Every object created by a constructor has an implicit reference (called the object's prototype) to the value of its constructor's "prototype" property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. When a reference is made to a property in an object, that reference is to the property of that name in the first object in the prototype chain that contains a property of that name. In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.
Figure 1: Object/Prototype Relationships
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behaviour. In ECMAScript, the state and methods are carried by objects, while structure, behaviour, and state are all inherited.
All objects that do not directly contain a particular property that their prototype contains share that property and its value. Figure 1 illustrates this:
CF is a constructor (and also an object). Five objects have been created by using new
expressions: cf1, cf2, cf3, cf4, and cf5. Each of these objects contains properties named "q1" and "q2". The dashed lines represent the implicit prototype relationship; so, for example, cf3's prototype is CFp. The constructor, CF, has two properties itself, named "P1" and "P2", which are not visible to CFp, cf1, cf2, cf3, cf4, or cf5. The property named "CFP1" in CFp is shared by cf1, cf2, cf3, cf4, and cf5 (but not by CF), as are any properties found in CFp's implicit prototype chain that are not named "q1", "q2", or "CFP1". Notice that there is no implicit prototype link between CF and CFp.
Unlike most class-based object languages, properties can be added to objects dynamically by assigning values to them. That is, constructors are not required to name or assign values to all or any of the constructed object's properties. In the above diagram, one could add a new shared property for cf1, cf2, cf3, cf4, and cf5 by assigning a new value to the property in CFp.
Although ECMAScript objects are not inherently class-based, it is often convenient to define class-like abstractions based upon a common pattern of constructor functions, prototype objects, and methods. The ECMAScript built-in objects themselves follow such a class-like pattern. Beginning with ECMAScript 2015, the ECMAScript language includes syntactic class definitions that permit programmers to concisely define objects that conform to the same class-like abstraction pattern used by the built-in objects.
The ECMAScript Language recognizes the possibility that some users of the language may wish to restrict their usage of some features available in the language. They might do so in the interests of security, to avoid what they consider to be error-prone features, to get enhanced error checking, or for other reasons of their choosing. In support of this possibility, ECMAScript defines a strict variant of the language. The strict variant of the language excludes some specific syntactic and semantic features of the regular ECMAScript language and modifies the detailed semantics of some features. The strict variant also specifies additional error conditions that must be reported by throwing error exceptions in situations that are not specified as errors by the non-strict form of the language.
The strict variant of ECMAScript is commonly referred to as the strict mode of the language. Strict mode selection and use of the strict mode syntax and semantics of ECMAScript is explicitly made at the level of individual ECMAScript source text units as described in 11.2.2. Because strict mode is selected at the level of a syntactic source text unit, strict mode only imposes restrictions that have local effect within such a source text unit. Strict mode does not restrict or modify any aspect of the ECMAScript semantics that must operate consistently across multiple source text units. A complete ECMAScript program may be composed of both strict mode and non-strict mode ECMAScript source text units. In this case, strict mode only applies when actually executing code that is defined within a strict mode source text unit.
In order to conform to this specification, an ECMAScript implementation must implement both the full unrestricted ECMAScript language and the strict variant of the ECMAScript language as defined by this specification. In addition, an implementation must support the combination of unrestricted and strict mode source text units into a single composite program.
For the purposes of this document, the following terms and definitions apply.
an implementation-approximated facility is defined in whole or in part by an external source but has a recommended, ideal behaviour in this specification
an implementation-defined facility is defined in whole or in part by an external source to this specification
same as implementation-defined
Note
Editorially, see clause 4.2.
set of data values as defined in clause 6
member of one of the types Undefined, Null, Boolean, Number, BigInt, Symbol, or String as defined in clause 6
Note
A primitive value is a datum that is represented directly at the lowest level of the language implementation.
member of the type Object
Note
An object is a collection of properties and has a single prototype object. The prototype may be the null value.
function object that creates and initializes objects
Note
The value of a constructor's "prototype" property is a prototype object that is used to implement inheritance and shared properties.
object that provides shared properties for other objects
Note
When a constructor creates an object, that object implicitly references the constructor's "prototype" property for the purpose of resolving property references. The constructor's "prototype" property can be referenced by the program expression constructor.prototype
, and properties added to an object's prototype are shared, through inheritance, by all objects sharing the prototype. Alternatively, a new object may be created with an explicitly specified prototype by using the Object.create
built-in function.
object that has the default behaviour for the essential internal methods that must be supported by all objects
object that does not have the default behaviour for one or more of the essential internal methods
Note
Any object that is not an ordinary object is an exotic object.
object whose semantics are defined by this specification
object specified and supplied by an ECMAScript implementation
Note
Standard built-in objects are defined in this specification. An ECMAScript implementation may specify and supply additional kinds of built-in objects. A built-in constructor is a built-in object that is also a constructor.
primitive value used when a variable has not been assigned a value
type whose sole value is the undefined value
primitive value that represents the intentional absence of any object value
type whose sole value is the null value
member of the Boolean type
Note
There are only two Boolean values, true and false.
type consisting of the primitive values true and false
member of the Object type that is an instance of the standard built-in Boolean constructor
Note
A Boolean object is created by using the Boolean constructor in a new
expression, supplying a Boolean value as an argument. The resulting object has an internal slot whose value is the Boolean value. A Boolean object can be coerced to a Boolean value.
primitive value that is a finite ordered sequence of zero or more 16-bit unsigned integer values
Note
A String value is a member of the String type. Each integer value in the sequence usually represents a single 16-bit unit of UTF-16 text. However, ECMAScript does not place any restrictions or requirements on the values except that they must be 16-bit unsigned integers.
set of all possible String values
member of the Object type that is an instance of the standard built-in String constructor
Note
A String object is created by using the String constructor in a new
expression, supplying a String value as an argument. The resulting object has an internal slot whose value is the String value. A String object can be coerced to a String value by calling the String constructor as a function (22.1.1.1).
primitive value corresponding to a double-precision 64-bit binary format IEEE 754-2019 value
Note
A Number value is a member of the Number type and is a direct representation of a number.
set of all possible Number values including the special “Not-a-Number” (NaN) value, positive infinity, and negative infinity
member of the Object type that is an instance of the standard built-in Number constructor
Note
A Number object is created by using the Number constructor in a new
expression, supplying a Number value as an argument. The resulting object has an internal slot whose value is the Number value. A Number object can be coerced to a Number value by calling the Number constructor as a function (21.1.1.1).
Number value that is the positive infinite Number value
Number value that is an IEEE 754-2019 “Not-a-Number” value
primitive value corresponding to an arbitrary-precision integer value
set of all possible BigInt values
member of the Object type that is an instance of the standard built-in BigInt constructor
primitive value that represents a unique, non-String Object property key
set of all possible Symbol values
member of the Object type that is an instance of the standard built-in Symbol constructor
member of the Object type that may be invoked as a subroutine
Note
In addition to its properties, a function contains executable code and state that determine how it behaves when invoked. A function's code may or may not be written in ECMAScript.
built-in object that is a function
Note
Examples of built-in functions include parseInt
and Math.exp
. A host or implementation may provide additional built-in functions that are not described in this specification.
part of an object that associates a key (either a String value or a Symbol value) and a value
Note
Depending upon the form of the property the value may be represented either directly as a data value (a primitive value, an object, or a function object) or indirectly by a pair of accessor functions.
function that is the value of a property
Note
When a function is called as a method of an object, the object is passed to the function as its this value.
method that is a built-in function
Note
Standard built-in methods are defined in this specification. A host or implementation may provide additional built-in methods that are not described in this specification.
internal value that defines some characteristic of a property
property that is directly contained by its object
property of an object that is not an own property but is a property (either own or inherited) of the object's prototype
The remainder of this specification is organized as follows:
Clause 5 defines the notational conventions used throughout the specification.
Clauses 6 through 10 define the execution environment within which ECMAScript programs operate.
Clauses 11 through 17 define the actual ECMAScript programming language including its syntactic encoding and the execution semantics of all language features.
Clauses 18 through 28 define the ECMAScript standard library. They include the definitions of all of the standard objects that are available for use by ECMAScript programs as they execute.
Clause 29 describes the memory consistency model of accesses on SharedArrayBuffer-backed memory and methods of the Atomics object.
A context-free grammar consists of a number of productions. Each production has an abstract symbol called a nonterminal as its left-hand side, and a sequence of zero or more nonterminal and terminal symbols as its right-hand side. For each grammar, the terminal symbols are drawn from a specified alphabet.
A chain production is a production that has exactly one nonterminal symbol on its right-hand side along with zero or more terminal symbols.
Starting from a sentence consisting of a single distinguished nonterminal, called the goal symbol, a given context-free grammar specifies a language, namely, the (perhaps infinite) set of possible sequences of terminal symbols that can result from repeatedly replacing any nonterminal in the sequence with a right-hand side of a production for which the nonterminal is the left-hand side.
A lexical grammar for ECMAScript is given in clause 12. This grammar has as its terminal symbols Unicode code points that conform to the rules for SourceCharacter defined in 11.1. It defines a set of productions, starting from the goal symbol InputElementDiv, InputElementTemplateTail, or InputElementRegExp, or InputElementRegExpOrTemplateTail, that describe how sequences of such code points are translated into a sequence of input elements.
Input elements other than white space and comments form the terminal symbols for the syntactic grammar for ECMAScript and are called ECMAScript tokens. These tokens are the reserved words, identifiers, literals, and punctuators of the ECMAScript language. Moreover, line terminators, although not considered to be tokens, also become part of the stream of input elements and guide the process of automatic semicolon insertion (12.9). Simple white space and single-line comments are discarded and do not appear in the stream of input elements for the syntactic grammar. A MultiLineComment (that is, a comment of the form /*
…*/
regardless of whether it spans more than one line) is likewise simply discarded if it contains no line terminator; but if a MultiLineComment contains one or more line terminators, then it is replaced by a single line terminator, which becomes part of the stream of input elements for the syntactic grammar.
A RegExp grammar for ECMAScript is given in 22.2.1. This grammar also has as its terminal symbols the code points as defined by SourceCharacter. It defines a set of productions, starting from the goal symbol Pattern, that describe how sequences of code points are translated into regular expression patterns.
Productions of the lexical and RegExp grammars are distinguished by having two colons “::” as separating punctuation. The lexical and RegExp grammars share some productions.
Another grammar is used for translating Strings into numeric values. This grammar is similar to the part of the lexical grammar having to do with numeric literals and has as its terminal symbols SourceCharacter. This grammar appears in 7.1.4.1.
Productions of the numeric string grammar are distinguished by having three colons “:::” as punctuation.
The syntactic grammar for ECMAScript is given in clauses 13 through 16. This grammar has ECMAScript tokens defined by the lexical grammar as its terminal symbols (5.1.2). It defines a set of productions, starting from two alternative goal symbols Script and Module, that describe how sequences of tokens form syntactically correct independent components of ECMAScript programs.
When a stream of code points is to be parsed as an ECMAScript Script or Module, it is first converted to a stream of input elements by repeated application of the lexical grammar; this stream of input elements is then parsed by a single application of the syntactic grammar. The input stream is syntactically in error if the tokens in the stream of input elements cannot be parsed as a single instance of the goal nonterminal (Script or Module), with no tokens left over.
When a parse is successful, it constructs a parse tree, a rooted tree structure in which each node is a Parse Node. Each Parse Node is an instance of a symbol in the grammar; it represents a span of the source text that can be derived from that symbol. The root node of the parse tree, representing the whole of the source text, is an instance of the parse's goal symbol. When a Parse Node is an instance of a nonterminal, it is also an instance of some production that has that nonterminal as its left-hand side. Moreover, it has zero or more children, one for each symbol on the production's right-hand side: each child is a Parse Node that is an instance of the corresponding symbol.
New Parse Nodes are instantiated for each invocation of the parser and never reused between parses even of identical source text. Parse Nodes are considered the same Parse Node if and only if they represent the same span of source text, are instances of the same grammar symbol, and resulted from the same parser invocation.
Note 1
Parsing the same String multiple times will lead to different Parse Nodes. For example, consider:
let str = "1 + 1;";
eval(str);
eval(str);
Each call to eval
converts the value of str
into an ECMAScript source text and performs an independent parse that creates its own separate tree of Parse Nodes. The trees are distinct even though each parse operates upon a source text that was derived from the same String value.
Note 2
Parse Nodes are specification artefacts, and implementations are not required to use an analogous data structure.
Productions of the syntactic grammar are distinguished by having just one colon “:” as punctuation.
The syntactic grammar as presented in clauses 13 through 16 is not a complete account of which token sequences are accepted as a correct ECMAScript Script or Module. Certain additional token sequences are also accepted, namely, those that would be described by the grammar if only semicolons were added to the sequence in certain places (such as before line terminator characters). Furthermore, certain token sequences that are described by the grammar are not considered acceptable if a line terminator character appears in certain “awkward” places.
In certain cases, in order to avoid ambiguities, the syntactic grammar uses generalized productions that permit token sequences that do not form a valid ECMAScript Script or Module. For example, this technique is used for object literals and object destructuring patterns. In such cases a more restrictive supplemental grammar is provided that further restricts the acceptable token sequences. Typically, an early error rule will then define an error condition if "P is not covering an N", where P is a Parse Node (an instance of the generalized production) and N is a nonterminal from the supplemental grammar. Here, the sequence of tokens originally matched by P is parsed again using N as the goal symbol. (If N takes grammatical parameters, then they are set to the same values used when P was originally parsed.) An error occurs if the sequence of tokens cannot be parsed as a single instance of N, with no tokens left over. Subsequently, algorithms access the result of the parse using a phrase of the form "the N that is covered by P". This will always be a Parse Node (an instance of N, unique for a given P), since any parsing failure would have been detected by an early error rule.
Terminal symbols are shown in fixed width
font, both in the productions of the grammars and throughout this specification whenever the text directly refers to such a terminal symbol. These are to appear in a script exactly as written. All terminal symbol code points specified in this way are to be understood as the appropriate Unicode code points from the Basic Latin range, as opposed to any similar-looking code points from other Unicode ranges. A code point in a terminal symbol cannot be expressed by a \
UnicodeEscapeSequence.
Nonterminal symbols are shown in italic type. The definition of a nonterminal (also called a “production”) is introduced by the name of the nonterminal being defined followed by one or more colons. (The number of colons indicates to which grammar the production belongs.) One or more alternative right-hand sides for the nonterminal then follow on succeeding lines. For example, the syntactic definition:
WhileStatement : while ( Expression ) Statement
states that the nonterminal WhileStatement represents the token while
, followed by a left parenthesis token, followed by an Expression, followed by a right parenthesis token, followed by a Statement. The occurrences of Expression and Statement are themselves nonterminals. As another example, the syntactic definition:
ArgumentList : AssignmentExpression ArgumentList , AssignmentExpression
states that an ArgumentList may represent either a single AssignmentExpression or an ArgumentList, followed by a comma, followed by an AssignmentExpression. This definition of ArgumentList is recursive, that is, it is defined in terms of itself. The result is that an ArgumentList may contain any positive number of arguments, separated by commas, where each argument expression is an AssignmentExpression. Such recursive definitions of nonterminals are common.
The subscripted suffix “opt”, which may appear after a terminal or nonterminal, indicates an optional symbol. The alternative containing the optional symbol actually specifies two right-hand sides, one that omits the optional element and one that includes it. This means that:
VariableDeclaration : BindingIdentifier Initializeropt
is a convenient abbreviation for:
VariableDeclaration : BindingIdentifier BindingIdentifier Initializer
and that:
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
is a convenient abbreviation for:
ForStatement : for ( LexicalDeclaration ; Expressionopt ) Statement for ( LexicalDeclaration Expression ; Expressionopt ) Statement
which in turn is an abbreviation for:
ForStatement : for ( LexicalDeclaration ; ) Statement for ( LexicalDeclaration ; Expression ) Statement for ( LexicalDeclaration Expression ; ) Statement for ( LexicalDeclaration Expression ; Expression ) Statement
so, in this example, the nonterminal ForStatement actually has four alternative right-hand sides.
A production may be parameterized by a subscripted annotation of the form “[parameters]”, which may appear as a suffix to the nonterminal symbol defined by the production. “parameters” may be either a single name or a comma separated list of names. A parameterized production is shorthand for a set of productions defining all combinations of the parameter names, preceded by an underscore, appended to the parameterized nonterminal symbol. This means that:
StatementList[Return] : ReturnStatement ExpressionStatement
is a convenient abbreviation for:
StatementList : ReturnStatement ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement
and that:
StatementList[Return, In] : ReturnStatement ExpressionStatement
is an abbreviation for:
StatementList : ReturnStatement ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement StatementList_In : ReturnStatement ExpressionStatement StatementList_Return_In : ReturnStatement ExpressionStatement
Multiple parameters produce a combinatory number of productions, not all of which are necessarily referenced in a complete grammar.
References to nonterminals on the right-hand side of a production can also be parameterized. For example:
StatementList : ReturnStatement ExpressionStatement[+In]
is equivalent to saying:
StatementList : ReturnStatement ExpressionStatement_In
and:
StatementList : ReturnStatement ExpressionStatement[~In]
is equivalent to:
StatementList : ReturnStatement ExpressionStatement
A nonterminal reference may have both a parameter list and an “opt” suffix. For example:
VariableDeclaration : BindingIdentifier Initializer[+In]opt
is an abbreviation for:
VariableDeclaration : BindingIdentifier BindingIdentifier Initializer_In
Prefixing a parameter name with “?” on a right-hand side nonterminal reference makes that parameter value dependent upon the occurrence of the parameter name on the reference to the current production's left-hand side symbol. For example:
VariableDeclaration[In] : BindingIdentifier Initializer[?In]
is an abbreviation for:
VariableDeclaration : BindingIdentifier Initializer VariableDeclaration_In : BindingIdentifier Initializer_In
If a right-hand side alternative is prefixed with “[+parameter]” that alternative is only available if the named parameter was used in referencing the production's nonterminal symbol. If a right-hand side alternative is prefixed with “[~parameter]” that alternative is only available if the named parameter was not used in referencing the production's nonterminal symbol. This means that:
StatementList[Return] : [+Return]ReturnStatement ExpressionStatement
is an abbreviation for:
StatementList : ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement
and that:
StatementList[Return] : [~Return]ReturnStatement ExpressionStatement
is an abbreviation for:
StatementList : ReturnStatement ExpressionStatement StatementList_Return : ExpressionStatement
When the words “one of” follow the colon(s) in a grammar definition, they signify that each of the terminal symbols on the following line or lines is an alternative definition. For example, the lexical grammar for ECMAScript contains the production:
NonZeroDigit :: one of 1 2 3 4 5 6 7 8 9
which is merely a convenient abbreviation for:
NonZeroDigit :: 1 2 3 4 5 6 7 8 9
If the phrase “[empty]” appears as the right-hand side of a production, it indicates that the production's right-hand side contains no terminals or nonterminals.
If the phrase “[lookahead = seq]” appears in the right-hand side of a production, it indicates that the production may only be used if the token sequence seq is a prefix of the immediately following input token sequence. Similarly, “[lookahead ∈ set]”, where set is a finite nonempty set of token sequences, indicates that the production may only be used if some element of set is a prefix of the immediately following token sequence. For convenience, the set can also be written as a nonterminal, in which case it represents the set of all token sequences to which that nonterminal could expand. It is considered an editorial error if the nonterminal could expand to infinitely many distinct token sequences.
These conditions may be negated. “[lookahead ≠ seq]” indicates that the containing production may only be used if seq is not a prefix of the immediately following input token sequence, and “[lookahead ∉ set]” indicates that the production may only be used if no element of set is a prefix of the immediately following token sequence.
As an example, given the definitions:
DecimalDigit :: one of 0 1 2 3 4 5 6 7 8 9 DecimalDigits :: DecimalDigit DecimalDigits DecimalDigit
the definition:
LookaheadExample :: n [lookahead ∉ { 1, 3, 5, 7, 9 }] DecimalDigits DecimalDigit [lookahead ∉ DecimalDigit]
matches either the letter n
followed by one or more decimal digits the first of which is even, or a decimal digit not followed by another decimal digit.
Note that when these phrases are used in the syntactic grammar, it may not be possible to unambiguously identify the immediately following token sequence because determining later tokens requires knowing which lexical goal symbol to use at later positions. As such, when these are used in the syntactic grammar, it is considered an editorial error for a token sequence seq to appear in a lookahead restriction (including as part of a set of sequences) if the choices of lexical goal symbols to use could change whether or not seq would be a prefix of the resulting token sequence.
If the phrase “[no LineTerminator here]” appears in the right-hand side of a production of the syntactic grammar, it indicates that the production is a restricted production: it may not be used if a LineTerminator occurs in the input stream at the indicated position. For example, the production:
ThrowStatement : throw [no LineTerminator here] Expression ;
indicates that the production may not be used if a LineTerminator occurs in the script between the throw
token and the Expression.
Unless the presence of a LineTerminator is forbidden by a restricted production, any number of occurrences of LineTerminator may appear between any two consecutive tokens in the stream of input elements without affecting the syntactic acceptability of the script.
When an alternative in a production of the lexical grammar or the numeric string grammar appears to be a multi-code point token, it represents the sequence of code points that would make up such a token.
The right-hand side of a production may specify that certain expansions are not permitted by using the phrase “but not” and then indicating the expansions to be excluded. For example, the production:
Identifier :: IdentifierName but not ReservedWord
means that the nonterminal Identifier may be replaced by any sequence of code points that could replace IdentifierName provided that the same sequence of code points could not replace ReservedWord.
Finally, a few nonterminal symbols are described by a descriptive phrase in sans-serif type in cases where it would be impractical to list all the alternatives:
SourceCharacter :: any Unicode code point
The specification often uses a numbered list to specify steps in an algorithm. These algorithms are used to precisely specify the required semantics of ECMAScript language constructs. The algorithms are not intended to imply the use of any specific implementation technique. In practice, there may be more efficient algorithms available to implement a given feature.
Algorithms may be explicitly parameterized with an ordered, comma-separated sequence of alias names which may be used within the algorithm steps to reference the argument passed in that position. Optional parameters are denoted with surrounding brackets ([ , name ]) and are no different from required parameters within algorithm steps. A rest parameter may appear at the end of a parameter list, denoted with leading ellipsis (, ...name). The rest parameter captures all of the arguments provided following the required and optional parameters into a List. If there are no such additional arguments, that List is empty.
Algorithm steps may be subdivided into sequential substeps. Substeps are indented and may themselves be further divided into indented substeps. Outline numbering conventions are used to identify substeps with the first level of substeps labelled with lower case alphabetic characters and the second level of substeps labelled with lower case roman numerals. If more than three levels are required these rules repeat with the fourth level using numeric labels. For example:
- Top-level step
- Substep.
- Substep.
- Subsubstep.
- Subsubsubstep
- Subsubsubsubstep
- Subsubsubsubsubstep
- Subsubsubsubstep
- Subsubsubstep
- Subsubstep.
A step or substep may be written as an “if” predicate that conditions its substeps. In this case, the substeps are only applied if the predicate is true. If a step or substep begins with the word “else”, it is a predicate that is the negation of the preceding “if” predicate step at the same level.
A step may specify the iterative application of its substeps.
A step that begins with “Assert:” asserts an invariant condition of its algorithm. Such assertions are used to make explicit algorithmic invariants that would otherwise be implicit. Such assertions add no additional semantic requirements and hence need not be checked by an implementation. They are used simply to clarify algorithms.
Algorithm steps may declare named aliases for any value using the form “Let x be someValue”. These aliases are reference-like in that both x and someValue refer to the same underlying data and modifications to either are visible to both. Algorithm steps that want to avoid this reference-like behaviour should explicitly make a copy of the right-hand side: “Let x be a copy of someValue” creates a shallow copy of someValue.
Once declared, an alias may be referenced in any subsequent steps and must not be referenced from steps prior to the alias's declaration. Aliases may be modified using the form “Set x to someOtherValue”.
In order to facilitate their use in multiple parts of this specification, some algorithms, called abstract operations, are named and written in parameterized functional form so that they may be referenced by name from within other algorithms. Abstract operations are typically referenced using a functional application style such as OperationName(arg1, arg2). Some abstract operations are treated as polymorphically dispatched methods of class-like specification abstractions. Such method-like abstract operations are typically referenced using a method application style such as someValue.OperationName(arg1, arg2).
A syntax-directed operation is a named operation whose definition consists of algorithms, each of which is associated with one or more productions from one of the ECMAScript grammars. A production that has multiple alternative definitions will typically have a distinct algorithm for each alternative. When an algorithm is associated with a grammar production, it may reference the terminal and nonterminal symbols of the production alternative as if they were parameters of the algorithm. When used in this manner, nonterminal symbols refer to the actual alternative definition that is matched when parsing the source text. The source text matched by a grammar production is the portion of the source text that starts at the beginning of the first terminal that participated in the match and ends at the end of the last terminal that participated in the match.
When an algorithm is associated with a production alternative, the alternative is typically shown without any “[ ]” grammar annotations. Such annotations should only affect the syntactic recognition of the alternative and have no effect on the associated semantics for the alternative.
Syntax-directed operations are invoked with a parse node and, optionally, other parameters by using the conventions on steps 1, 3, and 4 in the following algorithm:
- Let status be SyntaxDirectedOperation of SomeNonTerminal.
- Let someParseNode be the parse of some source text.
- Perform SyntaxDirectedOperation of someParseNode.
- Perform SyntaxDirectedOperation of someParseNode passing "value" as the argument.
Unless explicitly specified otherwise, all chain productions have an implicit definition for every operation that might be applied to that production's left-hand side nonterminal. The implicit definition simply reapplies the same operation with the same parameters, if any, to the chain production's sole right-hand side nonterminal and then returns the result. For example, assume that some algorithm has a step of the form: “Return the result of evaluating Block” and that there is a production:
Block : { StatementList }
but the Evaluation operation does not associate an algorithm with that production. In that case, the Evaluation operation implicitly includes an association of the form:
Runtime Semantics: Evaluation
Block : { StatementList }
- Return the result of evaluating StatementList.
Algorithms which specify semantics that must be called at runtime are called runtime semantics. Runtime semantics are defined by abstract operations or syntax-directed operations. Such algorithms always return a completion record.
The algorithms of this specification often implicitly return Completion Records whose [[Type]] is normal. Unless it is otherwise obvious from the context, an algorithm statement that returns a value that is not a Completion Record, such as:
- Return "Infinity".
means the same thing as:
- Return NormalCompletion("Infinity").
However, if the value expression of a “return” statement is a Completion Record construction literal, the resulting Completion Record is returned. If the value expression is a call to an abstract operation, the “return” statement simply returns the Completion Record produced by the abstract operation.
The abstract operation Completion(completionRecord) is used to emphasize that a previously computed Completion Record is being returned. The Completion abstract operation takes a single argument, completionRecord, and performs the following steps:
- Assert: completionRecord is a Completion Record.
- Return completionRecord as the Completion Record of this abstract operation.
A “return” statement without a value in an algorithm step means the same thing as:
- Return NormalCompletion(undefined).
Any reference to a Completion Record value that is in a context that does not explicitly require a complete Completion Record value is equivalent to an explicit reference to the [[Value]] field of the Completion Record value unless the Completion Record is an abrupt completion.
Algorithms steps that say to throw an exception, such as
- Throw a TypeError exception.
mean the same things as:
- Return ThrowCompletion(a newly created TypeError object).
Algorithms steps that say or are otherwise equivalent to:
- ReturnIfAbrupt(argument).
mean the same thing as:
- If argument is an abrupt completion, return argument.
- Else if argument is a Completion Record, set argument to argument.[[Value]].
Algorithms steps that say or are otherwise equivalent to:
- ReturnIfAbrupt(AbstractOperation()).
mean the same thing as:
- Let hygienicTemp be AbstractOperation().
- If hygienicTemp is an abrupt completion, return hygienicTemp.
- Else if hygienicTemp is a Completion Record, set hygienicTemp to hygienicTemp.[[Value]].
Where hygienicTemp is ephemeral and visible only in the steps pertaining to ReturnIfAbrupt.
Algorithms steps that say or are otherwise equivalent to:
- Let result be AbstractOperation(ReturnIfAbrupt(argument)).
mean the same thing as:
- If argument is an abrupt completion, return argument.
- If argument is a Completion Record, set argument to argument.[[Value]].
- Let result be AbstractOperation(argument).
Invocations of abstract operations and syntax-directed operations that are prefixed by ?
indicate that ReturnIfAbrupt should be applied to the resulting Completion Record. For example, the step:
- ? OperationName().
is equivalent to the following step:
- ReturnIfAbrupt(OperationName()).
Similarly, for method application style, the step:
- ? someValue.OperationName().
is equivalent to:
- ReturnIfAbrupt(someValue.OperationName()).
Similarly, prefix !
is used to indicate that the following invocation of an abstract or syntax-directed operation will never return an abrupt completion and that the resulting Completion Record's [[Value]] field should be used in place of the return value of the operation. For example, the step:
- Let val be ! OperationName().
is equivalent to the following steps:
- Let val be OperationName().
- Assert: val is never an abrupt completion.
- If val is a Completion Record, set val to val.[[Value]].
Syntax-directed operations for runtime semantics make use of this shorthand by placing !
or ?
before the invocation of the operation:
- Perform ! SyntaxDirectedOperation of NonTerminal.
Context-free grammars are not sufficiently powerful to express all the rules that define whether a stream of input elements form a valid ECMAScript Script or Module that may be evaluated. In some situations additional rules are needed that may be expressed using either ECMAScript algorithm conventions or prose requirements. Such rules are always associated with a production of a grammar and are called the static semantics of the production.
Static Semantic Rules have names and typically are defined using an algorithm. Named Static Semantic Rules are associated with grammar productions and a production that has multiple alternative definitions will typically have for each alternative a distinct algorithm for each applicable named static semantic rule.
A special kind of static semantic rule is an Early Error Rule. Early error rules define early error conditions (see clause 17) that are associated with specific grammar productions. Evaluation of most early error rules are not explicitly invoked within the algorithms of this specification. A conforming implementation must, prior to the first evaluation of a Script or Module, validate all of the early error rules of the productions used to parse that Script or Module. If any of the early error rules are violated the Script or Module is invalid and cannot be evaluated.
This specification makes reference to these kinds of numeric values:
- Mathematical values: Arbitrary real numbers, used as the default numeric type.
- Extended mathematical values: Mathematical values together with +∞ and -∞.
- Numbers: IEEE 754-2019 double-precision floating point values.
- BigInts: ECMAScript values representing arbitrary integers in a one-to-one correspondence.
In the language of this specification, numerical values are distinguished among different numeric kinds using subscript suffixes. The subscript 𝔽 refers to Numbers, and the subscript ℤ refers to BigInts. Numeric values without a subscript suffix refer to mathematical values.
Numeric operators such as +, ×, =, and ≥ refer to those operations as determined by the type of the operands. When applied to mathematical values, the operators refer to the usual mathematical operations. When applied to Numbers, the operators refer to the relevant operations within IEEE 754-2019. When applied to BigInts, the operators refer to the usual mathematical operations applied to the mathematical value of the BigInt.
In general, when this specification refers to a numerical value, such as in the phrase, "the length of y" or "the integer represented by the four hexadecimal digits ...", without explicitly specifying a numeric kind, the phrase refers to a mathematical value. Phrases which refer to a Number or a BigInt value are explicitly annotated as such; for example, "the Number value for the number of code points in …" or "the BigInt value for …".
Numeric operators applied to mixed-type operands (such as a Number and a mathematical value) are not defined and should be considered an editorial error in this specification.
This specification denotes most numeric values in base 10; it also uses numeric values of the form 0x followed by digits 0-9 or A-F as base-16 values.
When the term integer is used in this specification, it refers to a mathematical value which is in the set of integers, unless otherwise stated. When the term integral Number is used in this specification, it refers to a Number value whose mathematical value is in the set of integers.
Conversions between mathematical values and Numbers or BigInts are always explicit in this document. A conversion from a mathematical value or extended mathematical value x to a Number is denoted as "the Number value for x" or 𝔽(x), and is defined in 6.1.6.1. A conversion from an integer x to a BigInt is denoted as "the BigInt value for x" or ℤ(x). A conversion from a Number or BigInt x to a mathematical value is denoted as "the mathematical value of x", or ℝ(x). The mathematical value of +0𝔽 and -0𝔽 is the mathematical value 0. The mathematical value of non-finite values is not defined. The extended mathematical value of x is the mathematical value of x for finite values, and is +∞ and -∞ for +∞𝔽 and -∞𝔽 respectively; it is not defined for NaN.
The mathematical function abs(x) produces the absolute value of x, which is -x if x < 0 and otherwise is x itself.
The mathematical function min(x1, x2, … , xN) produces the mathematically smallest of x1 through xN. The mathematical function max(x1, x2, ..., xN) produces the mathematically largest of x1 through xN. The domain and range of these mathematical functions are the extended mathematical values.
The notation “x modulo y” (y must be finite and non-zero) computes a value k of the same sign as y (or zero) such that abs(k) < abs(y) and x - k = q × y for some integer q.
The phrase "the result of clamping x between lower and upper" (where x is an extended mathematical value and lower and upper are mathematical values such that lower ≤ upper) produces lower if x < lower, produces upper if x > upper, and otherwise produces x.
The mathematical function floor(x) produces the largest integer (closest to +∞) that is not larger than x.
Mathematical functions min, max, abs, and floor are not defined for Numbers and BigInts, and any usage of those methods that have non-mathematical value arguments would be an editorial error in this specification.
Note
In this specification, ECMAScript language values are displayed in bold. Examples include null, true, or "hello". These are distinguished from longer ECMAScript code sequences such as Function.prototype.apply
or let n = 42;
.
Values which are internal to the specification and not directly observable from ECMAScript code are indicated with a sans-serif typeface. For instance, a Completion Record's [[Type]] field takes on values like normal, return, or throw.
Algorithms within this specification manipulate values each of which has an associated type. The possible value types are exactly those defined in this clause. Types are further subclassified into ECMAScript language types and specification types.
Within this specification, the notation “Type(x)” is used as shorthand for “the type of x” where “type” refers to the ECMAScript language and specification types defined in this clause. When the term “empty” is used as if it was naming a value, it is equivalent to saying “no value of any type”.
An ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. The ECMAScript language types are Undefined, Null, Boolean, String, Symbol, Number, BigInt, and Object. An ECMAScript language value is a value that is characterized by an ECMAScript language type.
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
The Null type has exactly one value, called null.
The Boolean type represents a logical entity having two values, called true and false.
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values (“elements”) up to a maximum length of 253 - 1 elements. The String type is generally used to represent textual data in a running ECMAScript program, in which case each element in the String is treated as a UTF-16 code unit value. Each element is regarded as occupying a position within the sequence. These positions are indexed with non-negative integers. The first element (if any) is at index 0, the next element (if any) at index 1, and so on. The length of a String is the number of elements (i.e., 16-bit values) within it. The empty String has length zero and therefore contains no elements.
ECMAScript operations that do not interpret String contents apply no further semantics. Operations that do interpret String values treat each element as a single UTF-16 code unit. However, ECMAScript does not restrict the value of or relationships between these code units, so operations that further interpret String contents as sequences of Unicode code points encoded in UTF-16 must account for ill-formed subsequences. Such operations apply special treatment to every code unit with a numeric value in the inclusive range 0xD800 to 0xDBFF (defined by the Unicode Standard as a leading surrogate, or more formally as a high-surrogate code unit) and every code unit with a numeric value in the inclusive range 0xDC00 to 0xDFFF (defined as a trailing surrogate, or more formally as a low-surrogate code unit) using the following rules:
- A code unit that is not a leading surrogate and not a trailing surrogate is interpreted as a code point with the same value.
- A sequence of two code units, where the first code unit c1 is a leading surrogate and the second code unit c2 a trailing surrogate, is a surrogate pair and is interpreted as a code point with the value (c1 - 0xD800) × 0x400 + (c2 - 0xDC00) + 0x10000. (See 11.1.3)
- A code unit that is a leading surrogate or trailing surrogate, but is not part of a surrogate pair, is interpreted as a code point with the same value.
The function String.prototype.normalize
(see 22.1.3.13) can be used to explicitly normalize a String value. String.prototype.localeCompare
(see 22.1.3.10) internally normalizes String values, but no other operations implicitly normalize the strings upon which they operate. Only operations that are explicitly specified to be language or locale sensitive produce language-sensitive results.
Note
The rationale behind this design was to keep the implementation of Strings as simple and high-performing as possible. If ECMAScript source text is in Normalized Form C, string literals are guaranteed to also be normalized, as long as they do not contain any Unicode escape sequences.
In this specification, the phrase "the string-concatenation of A, B, ..." (where each argument is a String value, a code unit, or a sequence of code units) denotes the String value whose sequence of code units is the concatenation of the code units (in order) of each of the arguments (in order).
The phrase "the substring of S from inclusiveStart to exclusiveEnd" (where S is a String value or a sequence of code units and inclusiveStart and exclusiveEnd are integers) denotes the String value consisting of the consecutive code units of S beginning at index inclusiveStart and ending immediately before index exclusiveEnd (which is the empty String when inclusiveStart = exclusiveEnd). If the "to" suffix is omitted, the length of S is used as the value of exclusiveEnd.
The abstract operation StringIndexOf takes arguments string (a String), searchValue (a String), and fromIndex (a non-negative integer). It performs the following steps when called:
- Assert: Type(string) is String.
- Assert: Type(searchValue) is String.
- Assert: fromIndex is a non-negative integer.
- Let len be the length of string.
- If searchValue is the empty String and fromIndex ≤ len, return fromIndex.
- Let searchLen be the length of searchValue.
- For each integer i starting with fromIndex such that i ≤ len - searchLen, in ascending order, do
- Let candidate be the substring of string from i to i + searchLen.
- If candidate is the same sequence of code units as searchValue, return i.
- Return -1.
Note 1
If searchValue is the empty String and fromIndex is less than or equal to the length of string, this algorithm returns fromIndex. The empty String is effectively found at every position within a string, including after the last code unit.
Note 2
This algorithm always returns -1 if fromIndex > the length of string.
The Symbol type is the set of all non-String values that may be used as the key of an Object property (6.1.7).
Each possible Symbol value is unique and immutable.
Each Symbol value immutably holds an associated value called [[Description]] that is either undefined or a String value.
Well-known symbols are built-in Symbol values that are explicitly referenced by algorithms of this specification. They are typically used as the keys of properties whose values serve as extension points of a specification algorithm. Unless otherwise specified, well-known symbols values are shared by all realms (9.2).
Within this specification a well-known symbol is referred to by using a notation of the form @@name, where “name” is one of the values listed in Table 1.
Table 1: Well-known Symbols
Specification Name | [[Description]] | Value and Purpose |
---|---|---|
@@asyncIterator | "Symbol.asyncIterator" | A method that returns the default AsyncIterator for an object. Called by the semantics of the for -await -of statement. |
@@hasInstance | "Symbol.hasInstance" | A method that determines if a constructor object recognizes an object as one of the constructor's instances. Called by the semantics of the instanceof operator. |
@@isConcatSpreadable | "Symbol.isConcatSpreadable" | A Boolean valued property that if true indicates that an object should be flattened to its array elements by Array.prototype.concat . |
@@iterator | "Symbol.iterator" | A method that returns the default Iterator for an object. Called by the semantics of the for-of statement. |
@@match | "Symbol.match" | A regular expression method that matches the regular expression against a string. Called by the String.prototype.match method. |
@@matchAll | "Symbol.matchAll" | A regular expression method that returns an iterator, that yields matches of the regular expression against a string. Called by the String.prototype.matchAll method. |
@@replace | "Symbol.replace" | A regular expression method that replaces matched substrings of a string. Called by the String.prototype.replace method. |
@@search | "Symbol.search" | A regular expression method that returns the index within a string that matches the regular expression. Called by the String.prototype.search method. |
@@species | "Symbol.species" | A function valued property that is the constructor function that is used to create derived objects. |
@@split | "Symbol.split" | A regular expression method that splits a string at the indices that match the regular expression. Called by the String.prototype.split method. |
@@toPrimitive | "Symbol.toPrimitive" | A method that converts an object to a corresponding primitive value. Called by the ToPrimitive abstract operation. |
@@toStringTag | "Symbol.toStringTag" | A String valued property that is used in the creation of the default string description of an object. Accessed by the built-in method Object.prototype.toString . |
@@unscopables | "Symbol.unscopables" | An object valued property whose own and inherited property names are property names that are excluded from the with environment bindings of the associated object. |
ECMAScript has two built-in numeric types: Number and BigInt. In this specification, every numeric type T contains a multiplicative identity value denoted T::unit. The specification types also have the following abstract operations, likewise denoted T::op for a given operation with specification name op. All argument types are T. The "Result" column shows the return type, along with an indication if it is possible for some invocations of the operation to return an abrupt completion.
Table 2: Numeric Type Operations
Invocation Synopsis | Example source | Invoked by the Evaluation semantics of ... | Result |
---|---|---|---|
T::unaryMinus(x) | -x |
Unary - Operator |
T |
T::bitwiseNOT(x) | ~x |
Bitwise NOT Operator ( ~ ) |
T |
T::exponentiate(x, y) | x ** y |
Exponentiation Operator and Math.pow ( base, exponent ) | T, may throw RangeError |
T::multiply(x, y) | x * y |
Multiplicative Operators | T |
T::divide(x, y) | x / y |
Multiplicative Operators | T, may throw RangeError |
T::remainder(x, y) | x % y |
Multiplicative Operators | T, may throw RangeError |
T::add(x, y) | x ++ |
||
++ x |
|||
x + y |
Postfix Increment Operator, Prefix Increment Operator, and The Addition Operator ( + ) |
T | |
T::subtract(x, y) | x -- |
||
-- x |
|||
x - y |
Postfix Decrement Operator, Prefix Decrement Operator, and The Subtraction Operator ( - ) |
T | |
T::leftShift(x, y) | x << y |
The Left Shift Operator ( << ) |
T |
T::signedRightShift(x, y) | x >> y |
The Signed Right Shift Operator ( >> ) |
T |
T::unsignedRightShift(x, y) | x >>> y |
The Unsigned Right Shift Operator ( >>> ) |
T, may throw TypeError |
T::lessThan(x, y) | x < y |
||
x > y |
|||
x <= y |
|||
x >= y |
Relational Operators, via Abstract Relational Comparison | Boolean or undefined (for unordered inputs) | |
T::equal(x, y) | x == y |
||
x != y |
|||
x === y |
|||
x !== y |
Equality Operators, via Strict Equality Comparison | Boolean | |
T::sameValue(x, y) | Object internal methods, via SameValue ( x, y ), to test exact value equality | Boolean | |
T::sameValueZero(x, y) | Array, Map, and Set methods, via SameValueZero ( x, y ), to test value equality ignoring differences among members of the zero cohort (i.e., -0𝔽 and +0𝔽) | Boolean | |
T::bitwiseAND(x, y) | x & y |
Binary Bitwise Operators | T |
T::bitwiseXOR(x, y) | x ^ y |
Binary Bitwise Operators | T |
T::bitwiseOR(x, y) | `x | y` | Binary Bitwise Operators |
T::toString(x) | String(x) |
Many expressions and built-in functions, via ToString ( argument ) | String |
The T::unit value and T::op operations are not a part of the ECMAScript language; they are defined here solely to aid the specification of the semantics of the ECMAScript language. Other abstract operations are defined throughout this specification.
Because the numeric types are in general not convertible without loss of precision or truncation, the ECMAScript language provides no implicit conversion among these types. Programmers must explicitly call Number
and BigInt
functions to convert among types when calling a function which requires another type.
Note
The first and subsequent editions of ECMAScript have provided, for certain operators, implicit numeric conversions that could lose precision or truncate. These legacy implicit conversions are maintained for backward compatibility, but not provided for BigInt in order to minimize opportunity for programmer error, and to leave open the option of generalized value types in a future edition.
The Number type has exactly 18,437,736,874,454,810,627 (that is, 264 - 253 + 3) values, representing the double-precision 64-bit format IEEE 754-2019 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic, except that the 9,007,199,254,740,990 (that is, 253 - 2) distinct “Not-a-Number” values of the IEEE Standard are represented in ECMAScript as a single special NaN value. (Note that the NaN value is produced by the program expression NaN
.) In some implementations, external code might be able to detect a difference between various Not-a-Number values, but such behaviour is implementation-defined; to ECMAScript code, all NaN values are indistinguishable from each other.
Note
The bit pattern that might be observed in an ArrayBuffer (see 25.1) or a SharedArrayBuffer (see 25.2) after a Number value has been stored into it is not necessarily the same as the internal representation of that Number value used by the ECMAScript implementation.
There are two other special values, called positive Infinity and negative Infinity. For brevity, these values are also referred to for expository purposes by the symbols +∞𝔽 and -∞𝔽, respectively. (Note that these two infinite Number values are produced by the program expressions +Infinity
(or simply Infinity
) and -Infinity
.)
The other 18,437,736,874,454,810,624 (that is, 264 - 253) values are called the finite numbers. Half of these are positive numbers and half are negative numbers; for every finite positive Number value there is a corresponding negative value having the same magnitude.
Note that there is both a positive zero and a negative zero. For brevity, these values are also referred to for expository purposes by the symbols +0𝔽 and -0𝔽, respectively. (Note that these two different zero Number values are produced by the program expressions +0
(or simply 0
) and -0
.)
The 18,437,736,874,454,810,622 (that is, 264 - 253 - 2) finite non-zero values are of two kinds:
18,428,729,675,200,069,632 (that is, 264 - 254) of them are normalized, having the form
s × m × 2e
where s is 1 or -1, m is an integer such that 252 ≤ m < 253, and e is an integer such that -1074 ≤ e ≤ 971.
The remaining 9,007,199,254,740,990 (that is, 253 - 2) values are denormalized, having the form
s × m × 2e
where s is 1 or -1, m is an integer such that 0 < m < 252, and e is -1074.
Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the Number type. The integer 0 has two representations in the Number type: +0𝔽 and -0𝔽.
A finite number has an odd significand if it is non-zero and the integer m used to express it (in one of the two forms shown above) is odd. Otherwise, it has an even significand.
In this specification, the phrase “the Number value for x” where x represents an exact real mathematical quantity (which might even be an irrational number such as π) means a Number value chosen in the following manner. Consider the set of all finite values of the Number type, with -0𝔽 removed and with two additional values added to it that are not representable in the Number type, namely 21024 (which is +1 × 253 × 2971) and -21024 (which is -1 × 253 × 2971). Choose the member of this set that is closest in value to x. If two values of the set are equally close, then the one with an even significand is chosen; for this purpose, the two extra values 21024 and -21024 are considered to have even significands. Finally, if 21024 was chosen, replace it with +∞𝔽; if -21024 was chosen, replace it with -∞𝔽; if +0𝔽 was chosen, replace it with -0𝔽 if and only if x < 0; any other chosen value is used unchanged. The result is the Number value for x. (This procedure corresponds exactly to the behaviour of the IEEE 754-2019 roundTiesToEven mode.)
The Number value for +∞ is +∞𝔽, and the Number value for -∞ is -∞𝔽.
Some ECMAScript operators deal only with integers in specific ranges such as -231 through 231 - 1, inclusive, or in the range 0 through 216 - 1, inclusive. These operators accept any value of the Number type but first convert each such value to an integer value in the expected range. See the descriptions of the numeric conversion operations in 7.1.
The Number::unit value is 1𝔽.
The abstract operation Number::unaryMinus takes argument x (a Number). It performs the following steps when called:
- If x is NaN, return NaN.
- Return the result of negating x; that is, compute a Number with the same magnitude but opposite sign.
The abstract operation Number::bitwiseNOT takes argument x (a Number). It performs the following steps when called:
- Let oldValue be ! ToInt32(x).
- Return the result of applying bitwise complement to oldValue. The mathematical value of the result is exactly representable as a 32-bit two's complement bit string.
The abstract operation Number::exponentiate takes arguments base (a Number) and exponent (a Number). It returns an implementation-approximated value representing the result of raising base to the exponent power. It performs the following steps when called:
- If exponent is NaN, return NaN.
- If exponent is +0𝔽 or exponent is -0𝔽, return 1𝔽.
- If base is NaN, return NaN.
- If base is +∞𝔽, then
- If exponent > +0𝔽, return +∞𝔽. Otherwise, return +0𝔽.
- If base is -∞𝔽, then
- If exponent > +0𝔽, then
- If exponent is an odd integral Number, return -∞𝔽. Otherwise, return +∞𝔽.
- Else,
- If exponent is an odd integral Number, return -0𝔽. Otherwise, return +0𝔽.
- If exponent > +0𝔽, then
- If base is +0𝔽, then
- If exponent > +0𝔽, return +0𝔽. Otherwise, return +∞𝔽.
- If base is -0𝔽, then
- If exponent > +0𝔽, then
- If exponent is an odd integral Number, return -0𝔽. Otherwise, return +0𝔽.
- Else,
- If exponent is an odd integral Number, return -∞𝔽. Otherwise, return +∞𝔽.
- If exponent > +0𝔽, then
- Assert: base is finite and is neither +0𝔽 nor -0𝔽.
- If exponent is +∞𝔽, then
- If exponent is -∞𝔽, then 1. If abs(ℝ(base)) > 1, return +0𝔽. 2. If abs(ℝ(base)) is 1, return NaN. 3. If abs(ℝ(base)) < 1, return +∞𝔽.
- Assert: exponent is finite and is neither +0𝔽 nor -0𝔽.
- If base < +0𝔽 and exponent is not an integral Number, return NaN.
- Return an implementation-approximated value representing the result of raising ℝ(base) to the ℝ(exponent) power.
Note
The result of base **
exponent when base is 1𝔽 or -1𝔽 and exponent is +∞𝔽 or -∞𝔽, or when base is 1𝔽 and exponent is NaN, differs from IEEE 754-2019. The first edition of ECMAScript specified a result of NaN for this operation, whereas later versions of IEEE 754-2019 specified 1𝔽. The historical ECMAScript behaviour is preserved for compatibility reasons.
The abstract operation Number::multiply takes arguments x (a Number) and y (a Number). It performs multiplication according to the rules of IEEE 754-2019 binary double-precision arithmetic, producing the product of x and y. It performs the following steps when called:
- If x is NaN or y is NaN, return NaN.
- If x is +∞𝔽 or x is -∞𝔽, then
- If y is +0𝔽 or y is -0𝔽, return NaN.
- If y > +0𝔽, return x.
- Return -x.
- If y is +∞𝔽 or y is -∞𝔽, then
- If x is +0𝔽 or x is -0𝔽, return NaN.
- If x > +0𝔽, return y.
- Return -y.
- Return 𝔽(ℝ(x) × ℝ(y)).
Note
Finite-precision multiplication is commutative, but not always associative.
The abstract operation Number::divide takes arguments x (a Number) and y (a Number). It performs division according to the rules of IEEE 754-2019 binary double-precision arithmetic, producing the quotient of x and y where x is the dividend and y is the divisor. It performs the following steps when called:
- If x is NaN or y is NaN, return NaN.
- If x is +∞𝔽 or x is -∞𝔽, then
- If y is +∞𝔽 or y is -∞𝔽, return NaN.
- If y is +0𝔽 or y > +0𝔽, return x.
- Return -x.
- If y is +∞𝔽, then
- If x is +0𝔽 or x > +0𝔽, return +0𝔽. Otherwise, return -0𝔽.
- If y is -∞𝔽, then
- If x is +0𝔽 or x > +0𝔽, return -0𝔽. Otherwise, return +0𝔽.
- If x is +0𝔽 or x is -0𝔽, then
- If y is +0𝔽 or y is -0𝔽, return NaN.
- If y > +0𝔽, return x.
- Return -x.
- If y is +0𝔽, then
- If x > +0𝔽, return +∞𝔽. Otherwise, return -∞𝔽.
- If y is -0𝔽, then
- If x > +0𝔽, return -∞𝔽. Otherwise, return +∞𝔽.
- Return 𝔽(ℝ(x) / ℝ(y)).
The abstract operation Number::remainder takes arguments n (a Number) and d (a Number). It yields the remainder from an implied division of its operands where n is the dividend and d is the divisor. It performs the following steps when called:
- If n is NaN or d is NaN, return NaN.
- If n is +∞𝔽 or n is -∞𝔽, return NaN.
- If d is +∞𝔽 or d is -∞𝔽, return n.
- If d is +0𝔽 or d is -0𝔽, return NaN.
- If n is +0𝔽 or n is -0𝔽, return n.
- Assert: n and d are finite and non-zero.
- Let r be ℝ(n) - (ℝ(d) × q) where q is an integer that is negative if and only if n and d have opposite sign, and whose magnitude is as large as possible without exceeding the magnitude of ℝ(n) / ℝ(d).
- Return 𝔽(r).
Note 1
In C and C++, the remainder operator accepts only integral operands; in ECMAScript, it also accepts floating-point operands.
Note 2
The result of a floating-point remainder operation as computed by the %
operator is not the same as the “remainder” operation defined by
. The
“remainder” operation computes the remainder from a rounding division, not a truncating division, and so its behaviour is not analogous to that of the usual
integer
remainder operator. Instead the ECMAScript language defines %
on floating-point operations to behave in a manner analogous to that of the Java
integer
remainder operator; this may be compared with the C library function fmod.
The abstract operation Number::add takes arguments x (a Number) and y (a Number). It performs addition according to the rules of IEEE 754-2019 binary double-precision arithmetic, producing the sum of its arguments. It performs the following steps when called:
- If x is NaN or y is NaN, return NaN.
- If x is +∞𝔽 and y is -∞𝔽, return NaN.
- If x is -∞𝔽 and y is +∞𝔽, return NaN.
- If x is +∞𝔽 or x is -∞𝔽, return x.
- If y is +∞𝔽 or y is -∞𝔽, return y.
- Assert: x and y are both finite.
- If x is -0𝔽 and y is -0𝔽, return -0𝔽.
- Return 𝔽(ℝ(x) + ℝ(y)).
Note
Finite-precision addition is commutative, but not always associative.
The abstract operation Number::subtract takes arguments x (a Number) and y (a Number). It performs subtraction, producing the difference of its operands; x is the minuend and y is the subtrahend. It performs the following steps when called:
- Return Number::add(x, Number::unaryMinus(y)).
Note
It is always the case that x - y
produces the same result as x + (-y)
.
The abstract operation Number::leftShift takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- Let lnum be ! ToInt32(x).
- Let rnum be ! ToUint32(y).
- Let shiftCount be ℝ(rnum) modulo 32.
- Return the result of left shifting lnum by shiftCount bits. The mathematical value of the result is exactly representable as a 32-bit two's complement bit string.
The abstract operation Number::signedRightShift takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- Let lnum be ! ToInt32(x).
- Let rnum be ! ToUint32(y).
- Let shiftCount be ℝ(rnum) modulo 32.
- Return the result of performing a sign-extending right shift of lnum by shiftCount bits. The most significant bit is propagated. The mathematical value of the result is exactly representable as a 32-bit two's complement bit string.
The abstract operation Number::unsignedRightShift takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- Let lnum be ! ToUint32(x).
- Let rnum be ! ToUint32(y).
- Let shiftCount be ℝ(rnum) modulo 32.
- Return the result of performing a zero-filling right shift of lnum by shiftCount bits. Vacated bits are filled with zero. The mathematical value of the result is exactly representable as a 32-bit unsigned bit string.
The abstract operation Number::lessThan takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- If x is NaN, return undefined.
- If y is NaN, return undefined.
- If x and y are the same Number value, return false.
- If x is +0𝔽 and y is -0𝔽, return false.
- If x is -0𝔽 and y is +0𝔽, return false.
- If x is +∞𝔽, return false.
- If y is +∞𝔽, return true.
- If y is -∞𝔽, return false.
- If x is -∞𝔽, return true.
- Assert: x and y are finite and non-zero.
- If ℝ(x) < ℝ(y), return true. Otherwise, return false.
The abstract operation Number::equal takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0𝔽 and y is -0𝔽, return true.
- If x is -0𝔽 and y is +0𝔽, return true.
- Return false.
The abstract operation Number::sameValue takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- If x is NaN and y is NaN, return true.
- If x is +0𝔽 and y is -0𝔽, return false.
- If x is -0𝔽 and y is +0𝔽, return false.
- If x is the same Number value as y, return true.
- Return false.
The abstract operation Number::sameValueZero takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- If x is NaN and y is NaN, return true.
- If x is +0𝔽 and y is -0𝔽, return true.
- If x is -0𝔽 and y is +0𝔽, return true.
- If x is the same Number value as y, return true.
- Return false.
The abstract operation NumberBitwiseOp takes arguments op (a sequence of Unicode code points), x, and y. It performs the following steps when called:
- Assert: op is
&
,^
, or|
. - Let lnum be ! ToInt32(x).
- Let rnum be ! ToInt32(y).
- Let lbits be the 32-bit two's complement bit string representing ℝ(lnum).
- Let rbits be the 32-bit two's complement bit string representing ℝ(rnum).
- If op is
&
, let result be the result of applying the bitwise AND operation to lbits and rbits. - Else if op is
^
, let result be the result of applying the bitwise exclusive OR (XOR) operation to lbits and rbits. - Else, op is
|
. Let result be the result of applying the bitwise inclusive OR operation to lbits and rbits. - Return the Number value for the integer represented by the 32-bit two's complement bit string result.
The abstract operation Number::bitwiseAND takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- Return NumberBitwiseOp(
&
, x, y).
The abstract operation Number::bitwiseXOR takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- Return NumberBitwiseOp(
^
, x, y).
The abstract operation Number::bitwiseOR takes arguments x (a Number) and y (a Number). It performs the following steps when called:
- Return NumberBitwiseOp(
|
, x, y).
The abstract operation Number::toString takes argument x (a Number). It converts x to String format. It performs the following steps when called:
- If x is NaN, return the String "NaN".
- If x is +0𝔽 or -0𝔽, return the String "0".
- If x < +0𝔽, return the string-concatenation of "-" and ! Number::toString(-x).
- If x is +∞𝔽, return the String "Infinity".
- Otherwise, let n, k, and s be integers such that k ≥ 1, 10k - 1 ≤ s < 10k, s × 10n - k is ℝ(x), and k is as small as possible. Note that k is the number of digits in the decimal representation of s, that s is not divisible by 10, and that the least significant digit of s is not necessarily uniquely determined by these criteria.
- If k ≤ n ≤ 21, return the string-concatenation of:
- the code units of the k digits of the decimal representation of s (in order, with no leading zeroes)
- n - k occurrences of the code unit 0x0030 (DIGIT ZERO)
- If 0 < n ≤ 21, return the string-concatenation of:
- the code units of the most significant n digits of the decimal representation of s
- the code unit 0x002E (FULL STOP)
- the code units of the remaining k - n digits of the decimal representation of s
- If -6 < n ≤ 0, return the string-concatenation of:
- the code unit 0x0030 (DIGIT ZERO)
- the code unit 0x002E (FULL STOP)
- -n occurrences of the code unit 0x0030 (DIGIT ZERO)
- the code units of the k digits of the decimal representation of s
- Otherwise, if k = 1, return the string-concatenation of:
- the code unit of the single digit of s
- the code unit 0x0065 (LATIN SMALL LETTER E)
- the code unit 0x002B (PLUS SIGN) or the code unit 0x002D (HYPHEN-MINUS) according to whether n - 1 is positive or negative
- the code units of the decimal representation of the integer abs(n - 1) (with no leading zeroes)
- Return the string-concatenation of: - the code units of the most significant digit of the decimal representation of s - the code unit 0x002E (FULL STOP) - the code units of the remaining k - 1 digits of the decimal representation of s - the code unit 0x0065 (LATIN SMALL LETTER E) - the code unit 0x002B (PLUS SIGN) or the code unit 0x002D (HYPHEN-MINUS) according to whether n - 1 is positive or negative - the code units of the decimal representation of the integer abs(n - 1) (with no leading zeroes)
Note 1
The following observations may be useful as guidelines for implementations, but are not part of the normative requirements of this Standard:
- If x is any Number value other than -0𝔽, then ToNumber(ToString(x)) is exactly the same Number value as x.
- The least significant digit of s is not always uniquely determined by the requirements listed in step 5.
Note 2
For implementations that provide more accurate conversions than required by the rules above, it is recommended that the following alternative version of step 5 be used as a guideline:
- Otherwise, let n, k, and s be integers such that k ≥ 1, 10k - 1 ≤ s < 10k, s × 10n - k is ℝ(x), and k is as small as possible. If there are multiple possibilities for s, choose the value of s for which s × 10n - k is closest in value to ℝ(x). If there are two such possible values of s, choose the one that is even. Note that k is the number of digits in the decimal representation of s and that s is not divisible by 10.
Note 3
Implementers of ECMAScript may find useful the paper and code written by David M. Gay for binary-to-decimal conversion of floating-point numbers:
Gay, David M. Correctly Rounded Binary-Decimal and Decimal-Binary Conversions. Numerical Analysis, Manuscript 90-10. AT&T Bell Laboratories (Murray Hill, New Jersey). 30 November 1990. Available as
http://ampl.com/REFS/abstracts.html#rounding. Associated code available as
http://netlib.sandia.gov/fp/dtoa.c and as
http://netlib.sandia.gov/fp/g_fmt.c and may also be found at the various netlib
mirror sites.
The BigInt type represents an integer value. The value may be any size and is not limited to a particular bit-width. Generally, where not otherwise noted, operations are designed to return exact mathematically-based answers. For binary operations, BigInts act as two's complement binary strings, with negative numbers treated as having bits set infinitely to the left.
The BigInt::unit value is 1ℤ.
The abstract operation BigInt::unaryMinus takes argument x (a BigInt). It performs the following steps when called:
- If x is 0ℤ, return 0ℤ.
- Return the BigInt value that represents the negation of ℝ(x).
The abstract operation BigInt::bitwiseNOT takes argument x (a BigInt). It returns the one's complement of x; that is, -x - 1ℤ.
The abstract operation BigInt::exponentiate takes arguments base (a BigInt) and exponent (a BigInt). It performs the following steps when called:
- If exponent < 0ℤ, throw a RangeError exception.
- If base is 0ℤ and exponent is 0ℤ, return 1ℤ.
- Return the BigInt value that represents ℝ(base) raised to the power ℝ(exponent).
The abstract operation BigInt::multiply takes arguments x (a BigInt) and y (a BigInt). It returns the BigInt value that represents the result of multiplying x and y.
Note
Even if the result has a much larger bit width than the input, the exact mathematical answer is given.
The abstract operation BigInt::divide takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- If y is 0ℤ, throw a RangeError exception.
- Let quotient be ℝ(x) / ℝ(y).
- Return the BigInt value that represents quotient rounded towards 0 to the next integer value.
The abstract operation BigInt::remainder takes arguments n (a BigInt) and d (a BigInt). It performs the following steps when called:
- If d is 0ℤ, throw a RangeError exception.
- If n is 0ℤ, return 0ℤ.
- Let r be the BigInt defined by the mathematical relation r = n - (d × q) where q is a BigInt that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.
- Return r.
Note
The sign of the result equals the sign of the dividend.
The abstract operation BigInt::add takes arguments x (a BigInt) and y (a BigInt). It returns the BigInt value that represents the sum of x and y.
The abstract operation BigInt::subtract takes arguments x (a BigInt) and y (a BigInt). It returns the BigInt value that represents the difference x minus y.
The abstract operation BigInt::leftShift takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- If y < 0ℤ, then
- Return the BigInt value that represents ℝ(x) × 2y.
Note
Semantics here should be equivalent to a bitwise shift, treating the BigInt as an infinite length string of binary two's complement digits.
The abstract operation BigInt::signedRightShift takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- Return BigInt::leftShift(x, -y).
The abstract operation BigInt::unsignedRightShift takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- Throw a TypeError exception.
The abstract operation BigInt::lessThan takes arguments x (a BigInt) and y (a BigInt). It returns true if ℝ(x) < ℝ(y) and false otherwise.
The abstract operation BigInt::equal takes arguments x (a BigInt) and y (a BigInt). It returns true if ℝ(x) = ℝ(y) and false otherwise.
The abstract operation BigInt::sameValue takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- Return BigInt::equal(x, y).
The abstract operation BigInt::sameValueZero takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- Return BigInt::equal(x, y).
The abstract operation BinaryAnd takes arguments x and y. It performs the following steps when called:
The abstract operation BinaryOr takes arguments x and y. It performs the following steps when called:
The abstract operation BinaryXor takes arguments x and y. It performs the following steps when called:
- Assert: x is 0 or 1.
- Assert: y is 0 or 1.
- If x is 1 and y is 0, return 1.
- Else if x is 0 and y is 1, return 1.
- Else, return 0.
The abstract operation BigIntBitwiseOp takes arguments op (a sequence of Unicode code points), x (a BigInt), and y (a BigInt). It performs the following steps when called:
- Assert: op is
&
,^
, or|
. - Set x to ℝ(x).
- Set y to ℝ(y).
- Let result be 0.
- Let shift be 0.
- Repeat, until (x = 0 or x = -1) and (y = 0 or y = -1),
- If op is
&
, let tmp be BinaryAnd(x modulo 2, y modulo 2). - Else if op is
|
, let tmp be BinaryOr(x modulo 2, y modulo 2). - Else,
- If tmp ≠ 0, then 1. Set result to result - 2shift. 2. NOTE: This extends the sign.
- Return the BigInt value for result.
The abstract operation BigInt::bitwiseAND takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- Return BigIntBitwiseOp(
&
, x, y).
The abstract operation BigInt::bitwiseXOR takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- Return BigIntBitwiseOp(
^
, x, y).
The abstract operation BigInt::bitwiseOR takes arguments x (a BigInt) and y (a BigInt). It performs the following steps when called:
- Return BigIntBitwiseOp(
|
, x, y).
The abstract operation BigInt::toString takes argument x (a BigInt). It converts x to String format. It performs the following steps when called:
- If x < 0ℤ, return the string-concatenation of the String "-" and ! BigInt::toString(-x).
- Return the String value consisting of the code units of the digits of the decimal representation of x.
An Object is logically a collection of properties. Each property is either a data property, or an accessor property:
- A data property associates a key value with an ECMAScript language value and a set of Boolean attributes.
- An accessor property associates a key value with one or two accessor functions, and a set of Boolean attributes. The accessor functions are used to store or retrieve an ECMAScript language value that is associated with the property.
Properties are identified using key values. A property key value is either an ECMAScript String value or a Symbol value. All String and Symbol values, including the empty String, are valid as property keys. A property name is a property key that is a String value.
An integer index is a String-valued property key that is a canonical numeric String (see 7.1.21) and whose numeric value is either +0𝔽 or a positive integral Number ≤ 𝔽(253 - 1). An array index is an integer index whose numeric value i is in the range +0𝔽 ≤ i < 𝔽(232 - 1).
Property keys are used to access properties and their values. There are two kinds of access for properties: get and set, corresponding to value retrieval and assignment, respectively. The properties accessible via get and set access includes both own properties that are a direct part of an object and inherited properties which are provided by another associated object via a property inheritance relationship. Inherited properties may be either own or inherited properties of the associated object. Each own property of an object must each have a key value that is distinct from the key values of the other own properties of that object.
All objects are logically collections of properties, but there are multiple forms of objects that differ in their semantics for accessing and manipulating their properties. Please see 6.1.7.2 for definitions of the multiple forms of objects.
Attributes are used in this specification to define and explain the state of Object properties. A data property associates a key value with the attributes listed in Table 3.
Table 3: Attributes of a Data Property
Attribute Name | Value Domain | Description |
---|---|---|
[[Value]] | Any ECMAScript language type | The value retrieved by a get access of the property. |
[[Writable]] | Boolean | If false, attempts by ECMAScript code to change the property's [[Value]] attribute using [[Set]] will not succeed. |
[[Enumerable]] | Boolean | If true, the property will be enumerated by a for-in enumeration (see 14.7.5). Otherwise, the property is said to be non-enumerable. |
[[Configurable]] | Boolean | If false, attempts to delete the property, change the property to be an accessor property, or change its attributes (other than [[Value]], or changing [[Writable]] to false) will fail. |
An accessor property associates a key value with the attributes listed in Table 4.
Table 4: Attributes of an Accessor Property
Attribute Name | Value Domain | Description |
---|---|---|
[[Get]] | Object | Undefined |
[[Set]] | Object | Undefined |
[[Enumerable]] | Boolean | If true, the property is to be enumerated by a for-in enumeration (see 14.7.5). Otherwise, the property is said to be non-enumerable. |
[[Configurable]] | Boolean | If false, attempts to delete the property, change the property to be a data property, or change its attributes will fail. |
If the initial values of a property's attributes are not explicitly specified by this specification, the default value defined in Table 5 is used.
Table 5: Default Attribute Values
Attribute Name | Default Value |
---|---|
[[Value]] | undefined |
[[Get]] | undefined |
[[Set]] | undefined |
[[Writable]] | false |
[[Enumerable]] | false |
[[Configurable]] | false |
The actual semantics of objects, in ECMAScript, are specified via algorithms called internal methods. Each object in an ECMAScript engine is associated with a set of internal methods that defines its runtime behaviour. These internal methods are not part of the ECMAScript language. They are defined by this specification purely for expository purposes. However, each object within an implementation of ECMAScript must behave as specified by the internal methods associated with it. The exact manner in which this is accomplished is determined by the implementation.
Internal method names are polymorphic. This means that different object values may perform different algorithms when a common internal method name is invoked upon them. That actual object upon which an internal method is invoked is the “target” of the invocation. If, at runtime, the implementation of an algorithm attempts to use an internal method of an object that the object does not support, a TypeError exception is thrown.
Internal slots correspond to internal state that is associated with objects and used by various ECMAScript specification algorithms. Internal slots are not object properties and they are not inherited. Depending upon the specific internal slot specification, such state may consist of values of any ECMAScript language type or of specific ECMAScript specification type values. Unless explicitly specified otherwise, internal slots are allocated as part of the process of creating an object and may not be dynamically added to an object. Unless specified otherwise, the initial value of an internal slot is the value undefined. Various algorithms within this specification create objects that have internal slots. However, the ECMAScript language provides no direct way to associate internal slots with an object.
Internal methods and internal slots are identified within this specification using names enclosed in double square brackets [[ ]].
Table 6 summarizes the essential internal methods used by this specification that are applicable to all objects created or manipulated by ECMAScript code. Every object must have algorithms for all of the essential internal methods. However, all objects do not necessarily use the same algorithms for those methods.
An ordinary object is an object that satisfies all of the following criteria:
- For the internal methods listed in Table 6, the object uses those defined in 10.1.
- If the object has a [[Call]] internal method, it uses the one defined in 10.2.1.
- If the object has a [[Construct]] internal method, it uses the one defined in 10.2.2.
An exotic object is an object that is not an ordinary object.
This specification recognizes different kinds of exotic objects by those objects' internal methods. An object that is behaviourally equivalent to a particular kind of exotic object (such as an Array exotic object or a bound function exotic object), but does not have the same collection of internal methods specified for that kind, is not recognized as that kind of exotic object.
The “Signature” column of Table 6 and other similar tables describes the invocation pattern for each internal method. The invocation pattern always includes a parenthesized list of descriptive parameter names. If a parameter name is the same as an ECMAScript type name then the name describes the required type of the parameter value. If an internal method explicitly returns a value, its parameter list is followed by the symbol “→” and the type name of the returned value. The type names used in signatures refer to the types defined in clause 6 augmented by the following additional names. “any” means the value may be any ECMAScript language type.
In addition to its parameters, an internal method always has access to the object that is the target of the method invocation.
An internal method implicitly returns a Completion Record, either a normal completion that wraps a value of the return type shown in its invocation pattern, or a throw completion.
Table 6: Essential Internal Methods
Internal Method | Signature | Description |
---|---|---|
[[GetPrototypeOf]] | ( ) → Object | Null |
[[SetPrototypeOf]] | (Object | Null) → Boolean |
[[IsExtensible]] | ( ) → Boolean | Determine whether it is permitted to add additional properties to this object. |
[[PreventExtensions]] | ( ) → Boolean | Control whether new properties may be added to this object. Returns true if the operation was successful or false if the operation was unsuccessful. |
[[GetOwnProperty]] | (propertyKey) → Undefined | Property Descriptor |
[[DefineOwnProperty]] | (propertyKey, PropertyDescriptor) → Boolean | Create or alter the own property, whose key is propertyKey, to have the state described by PropertyDescriptor. Return true if that property was successfully created/updated or false if the property could not be created or updated. |
[[HasProperty]] | (propertyKey) → Boolean | Return a Boolean value indicating whether this object already has either an own or inherited property whose key is propertyKey. |
[[Get]] | (propertyKey, Receiver) → any | Return the value of the property whose key is propertyKey from this object. If any ECMAScript code must be executed to retrieve the property value, Receiver is used as the this value when evaluating the code. |
[[Set]] | (propertyKey, value, Receiver) → Boolean | Set the value of the property whose key is propertyKey to value. If any ECMAScript code must be executed to set the property value, Receiver is used as the this value when evaluating the code. Returns true if the property value was set or false if it could not be set. |
[[Delete]] | (propertyKey) → Boolean | Remove the own property whose key is propertyKey from this object. Return false if the property was not deleted and is still present. Return true if the property was deleted or is not present. |
[[OwnPropertyKeys]] | ( ) → List of propertyKey | Return a List whose elements are all of the own property keys for the object. |
Table 7 summarizes additional essential internal methods that are supported by objects that may be called as functions. A function object is an object that supports the [[Call]] internal method. A constructor is an object that supports the [[Construct]] internal method. Every object that supports [[Construct]] must support [[Call]]; that is, every constructor must be a function object. Therefore, a constructor may also be referred to as a constructor function or constructor function object.
Table 7: Additional Essential Internal Methods of Function Objects
Internal Method | Signature | Description |
---|---|---|
[[Call]] | (any, a List of any) → any | Executes code associated with this object. Invoked via a function call expression. The arguments to the internal method are a this value and a List whose elements are the arguments passed to the function by a call expression. Objects that implement this internal method are callable. |
[[Construct]] | (a List of any, Object) → Object | Creates an object. Invoked via the new operator or a super call. The first argument to the internal method is a List whose elements are the arguments of the constructor invocation or the super call. The second argument is the object to which the new operator was initially applied. Objects that implement this internal method are called constructors. A function object is not necessarily a constructor and such non-constructor function objects do not have a [[Construct]] internal method. |
The semantics of the essential internal methods for ordinary objects and standard exotic objects are specified in clause 10. If any specified use of an internal method of an exotic object is not supported by an implementation, that usage must throw a TypeError exception when attempted.
The Internal Methods of Objects of an ECMAScript engine must conform to the list of invariants specified below. Ordinary ECMAScript Objects as well as all standard exotic objects in this specification maintain these invariants. ECMAScript Proxy objects maintain these invariants by means of runtime checks on the result of traps invoked on the [[ProxyHandler]] object.
Any implementation provided exotic objects must also maintain these invariants for those objects. Violation of these invariants may cause ECMAScript code to have unpredictable behaviour and create security issues. However, violation of these invariants must never compromise the memory safety of an implementation.
An implementation must not allow these invariants to be circumvented in any manner such as by providing alternative interfaces that implement the functionality of the essential internal methods without enforcing their invariants.
- The target of an internal method is the object upon which the internal method is called.
- A target is non-extensible if it has been observed to return false from its [[IsExtensible]] internal method, or true from its [[PreventExtensions]] internal method.
- A non-existent property is a property that does not exist as an own property on a non-extensible target.
- All references to SameValue are according to the definition of the SameValue algorithm.
The value returned by any internal method must be a Completion Record with either:
- [[Type]] = normal, [[Target]] = empty, and [[Value]] = a value of the "normal return type" shown below for that internal method, or
- [[Type]] = throw, [[Target]] = empty, and [[Value]] = any ECMAScript language value.
Note 1
An internal method must not return a completion with [[Type]] = continue, break, or return.
- The normal return type is either Object or Null.
- If target is non-extensible, and [[GetPrototypeOf]] returns a value V, then any future calls to [[GetPrototypeOf]] should return the SameValue as V.
Note 2
An object's prototype chain should have finite length (that is, starting from any object, recursively applying the [[GetPrototypeOf]] internal method to its result should eventually lead to the value null). However, this requirement is not enforceable as an object level invariant if the prototype chain includes any exotic objects that do not use the ordinary object definition of [[GetPrototypeOf]]. Such a circular prototype chain may result in infinite loops when accessing object properties.
- The normal return type is Boolean.
- If target is non-extensible, [[SetPrototypeOf]] must return false, unless V is the SameValue as the target's observed [[GetPrototypeOf]] value.
- The normal return type is Boolean.
- If [[IsExtensible]] returns false, all future calls to [[IsExtensible]] on the target must return false.
- The normal return type is Boolean.
- If [[PreventExtensions]] returns true, all future calls to [[IsExtensible]] on the target must return false and the target is now considered non-extensible.
- The normal return type is either Property Descriptor or Undefined.
- If the Type of the return value is Property Descriptor, the return value must be a fully populated Property Descriptor.
- If P is described as a non-configurable, non-writable own data property, all future calls to [[GetOwnProperty]] ( P ) must return Property Descriptor whose [[Value]] is SameValue as P's [[Value]] attribute.
- If P's attributes other than [[Writable]] may change over time or if the property might be deleted, then P's [[Configurable]] attribute must be true.
- If the [[Writable]] attribute may change from false to true, then the [[Configurable]] attribute must be true.
- If the target is non-extensible and P is non-existent, then all future calls to [[GetOwnProperty]] (P) on the target must describe P as non-existent (i.e. [[GetOwnProperty]] (P) must return undefined).
Note 3
As a consequence of the third invariant, if a property is described as a data property and it may return different values over time, then either or both of the [[Writable]] and [[Configurable]] attributes must be true even if no mechanism to change the value is exposed via the other essential internal methods.
- The normal return type is Boolean.
- [[DefineOwnProperty]] must return false if P has previously been observed as a non-configurable own property of the target, unless either:
- P is a writable data property. A non-configurable writable data property can be changed into a non-configurable non-writable data property.
- All attributes of Desc are the SameValue as P's attributes.
- [[DefineOwnProperty]] (P, Desc) must return false if target is non-extensible and P is a non-existent own property. That is, a non-extensible target object cannot be extended with new properties.
- The normal return type is Boolean.
- If P was previously observed as a non-configurable own data or accessor property of the target, [[HasProperty]] must return true.
- The normal return type is any ECMAScript language type.
- If P was previously observed as a non-configurable, non-writable own data property of the target with value V, then [[Get]] must return the SameValue as V.
- If P was previously observed as a non-configurable own accessor property of the target whose [[Get]] attribute is undefined, the [[Get]] operation must return undefined.
- The normal return type is Boolean.
- If P was previously observed as a non-configurable, non-writable own data property of the target, then [[Set]] must return false unless V is the SameValue as P's [[Value]] attribute.
- If P was previously observed as a non-configurable own accessor property of the target whose [[Set]] attribute is undefined, the [[Set]] operation must return false.
- The normal return type is Boolean.
- If P was previously observed as a non-configurable own data or accessor property of the target, [[Delete]] must return false.
- The normal return type is List.
- The returned List must not contain any duplicate entries.
- The Type of each element of the returned List is either String or Symbol.
- The returned List must contain at least the keys of all non-configurable own properties that have previously been observed.
- If the target is non-extensible, the returned List must contain only the keys of all own properties of the target that are observable using [[GetOwnProperty]].
- The normal return type is any ECMAScript language type.
- The normal return type is Object.
- The target must also have a [[Call]] internal method.
Well-known intrinsics are built-in objects that are explicitly referenced by the algorithms of this specification and which usually have realm-specific identities. Unless otherwise specified each intrinsic object actually corresponds to a set of similar objects, one per realm.
Within this specification a reference such as %name% means the intrinsic object, associated with the current realm, corresponding to the name. A reference such as %name.a.b% means, as if the "b" property of the "a" property of the intrinsic object %name% was accessed prior to any ECMAScript code being evaluated. Determination of the current realm and its intrinsics is described in 9.3. The well-known intrinsics are listed in Table 8.
Table 8: Well-Known Intrinsic Objects
Intrinsic Name | Global Name | ECMAScript Language Association |
---|---|---|
%AggregateError% | AggregateError |
The AggregateError constructor (20.5.7.1) |
%Array% | Array |
The Array constructor (23.1.1) |
%ArrayBuffer% | ArrayBuffer |
The ArrayBuffer constructor (25.1.3) |
%ArrayIteratorPrototype% | The prototype of Array iterator objects (23.1.5) | |
%AsyncFromSyncIteratorPrototype% | The prototype of async-from-sync iterator objects (27.1.4) | |
%AsyncFunction% | The constructor of async function objects (27.7.1) | |
%AsyncGeneratorFunction% | The constructor of async iterator objects (27.4.1) | |
%AsyncIteratorPrototype% | An object that all standard built-in async iterator objects indirectly inherit from | |
%Atomics% | Atomics |
The Atomics object (25.4) |
%BigInt% | BigInt |
The BigInt constructor (21.2.1) |
%BigInt64Array% | BigInt64Array |
The BigInt64Array constructor (23.2) |
%BigUint64Array% | BigUint64Array |
The BigUint64Array constructor (23.2) |
%Boolean% | Boolean |
The Boolean constructor (20.3.1) |
%DataView% | DataView |
The DataView constructor (25.3.2) |
%Date% | Date |
The Date constructor (21.4.2) |
%decodeURI% | decodeURI |
The decodeURI function (19.2.6.2) |
%decodeURIComponent% | decodeURIComponent |
The decodeURIComponent function (19.2.6.3) |
%encodeURI% | encodeURI |
The encodeURI function (19.2.6.4) |
%encodeURIComponent% | encodeURIComponent |
The encodeURIComponent function (19.2.6.5) |
%Error% | Error |
The Error constructor (20.5.1) |
%eval% | eval |
The eval function (19.2.1) |
%EvalError% | EvalError |
The EvalError constructor (20.5.5.1) |
%FinalizationRegistry% | FinalizationRegistry |
The FinalizationRegistry constructor (26.2.1) |
%Float32Array% | Float32Array |
The Float32Array constructor (23.2) |
%Float64Array% | Float64Array |
The Float64Array constructor (23.2) |
%ForInIteratorPrototype% | The prototype of For-In iterator objects (14.7.5.10) | |
%Function% | Function |
The Function constructor (20.2.1) |
%GeneratorFunction% | The constructor of generator objects (27.3.1) | |
%Int8Array% | Int8Array |
The Int8Array constructor (23.2) |
%Int16Array% | Int16Array |
The Int16Array constructor (23.2) |
%Int32Array% | Int32Array |
The Int32Array constructor (23.2) |
%isFinite% | isFinite |
The isFinite function (19.2.2) |
%isNaN% | isNaN |
The isNaN function (19.2.3) |
%IteratorPrototype% | An object that all standard built-in iterator objects indirectly inherit from | |
%JSON% | JSON |
The JSON object (25.5) |
%Map% | Map |
The Map constructor (24.1.1) |
%MapIteratorPrototype% | The prototype of Map iterator objects (24.1.5) | |
%Math% | Math |
The Math object (21.3) |
%Number% | Number |
The Number constructor (21.1.1) |
%Object% | Object |
The Object constructor (20.1.1) |
%parseFloat% | parseFloat |
The parseFloat function (19.2.4) |
%parseInt% | parseInt |
The parseInt function (19.2.5) |
%Promise% | Promise |
The Promise constructor (27.2.3) |
%Proxy% | Proxy |
The Proxy constructor (28.2.1) |
%RangeError% | RangeError |
The RangeError constructor (20.5.5.2) |
%ReferenceError% | ReferenceError |
The ReferenceError constructor (20.5.5.3) |
%Reflect% | Reflect |
The Reflect object (28.1) |
%RegExp% | RegExp |
The RegExp constructor (22.2.3) |
%RegExpStringIteratorPrototype% | The prototype of RegExp String Iterator objects (22.2.7) | |
%Set% | Set |
The Set constructor (24.2.1) |
%SetIteratorPrototype% | The prototype of Set iterator objects (24.2.5) | |
%SharedArrayBuffer% | SharedArrayBuffer |
The SharedArrayBuffer constructor (25.2.2) |
%String% | String |
The String constructor (22.1.1) |
%StringIteratorPrototype% | The prototype of String iterator objects (22.1.5) | |
%Symbol% | Symbol |
The Symbol constructor (20.4.1) |
%SyntaxError% | SyntaxError |
The SyntaxError constructor (20.5.5.4) |
%ThrowTypeError% | A function object that unconditionally throws a new instance of %TypeError% | |
%TypedArray% | The super class of all typed Array constructors (23.2.1) | |
%TypeError% | TypeError |
The TypeError constructor (20.5.5.5) |
%Uint8Array% | Uint8Array |
The Uint8Array constructor (23.2) |
%Uint8ClampedArray% | Uint8ClampedArray |
The Uint8ClampedArray constructor (23.2) |
%Uint16Array% | Uint16Array |
The Uint16Array constructor (23.2) |
%Uint32Array% | Uint32Array |
The Uint32Array constructor (23.2) |
%URIError% | URIError |
The URIError constructor (20.5.5.6) |
%WeakMap% | WeakMap |
The WeakMap constructor (24.3.1) |
%WeakRef% | WeakRef |
The WeakRef constructor (26.1.1) |
%WeakSet% | WeakSet |
The WeakSet constructor (24.4.1) |
Note
Additional entries in Table 82.
A specification type corresponds to meta-values that are used within algorithms to describe the semantics of ECMAScript language constructs and ECMAScript language types. The specification types include Reference, List, Completion, Property Descriptor, Environment Record, Abstract Closure, and Data Block. Specification type values are specification artefacts that do not necessarily correspond to any specific entity within an ECMAScript implementation. Specification type values may be used to describe intermediate results of ECMAScript expression evaluation but such values cannot be stored as properties of objects or values of ECMAScript language variables.
The List type is used to explain the evaluation of argument lists (see 13.3.8) in new
expressions, in function calls, and in other algorithms where a simple ordered list of values is needed. Values of the List type are simply ordered sequences of list elements containing the individual values. These sequences may be of any length. The elements of a list may be randomly accessed using 0-origin indices. For notational convenience an array-like syntax can be used to access List elements. For example, arguments[2] is shorthand for saying the 3rd element of the List arguments.
When an algorithm iterates over the elements of a List without specifying an order, the order used is the order of the elements in the List.
For notational convenience within this specification, a literal syntax can be used to express a new List value. For example, « 1, 2 » defines a List value that has two elements each of which is initialized to a specific value. A new empty List can be expressed as « ».
The Record type is used to describe data aggregations within the algorithms of this specification. A Record type value consists of one or more named fields. The value of each field is either an ECMAScript value or an abstract value represented by a name associated with the Record type. Field names are always enclosed in double brackets, for example [[Value]].
For notational convenience within this specification, an object literal-like syntax can be used to express a Record value. For example, { [[Field1]]: 42, [[Field2]]: false, [[Field3]]: empty } defines a Record value that has three fields, each of which is initialized to a specific value. Field name order is not significant. Any fields that are not explicitly listed are considered to be absent.
In specification text and algorithms, dot notation may be used to refer to a specific field of a Record value. For example, if R is the record shown in the previous paragraph then R.[[Field2]] is shorthand for “the field of R named [[Field2]]”.
Schema for commonly used Record field combinations may be named, and that name may be used as a prefix to a literal Record value to identify the specific kind of aggregations that is being described. For example: PropertyDescriptor { [[Value]]: 42, [[Writable]]: false, [[Configurable]]: true }.
The Set type is used to explain a collection of unordered elements for use in the memory model. Values of the Set type are simple collections of elements, where no element appears more than once. Elements may be added to and removed from Sets. Sets may be unioned, intersected, or subtracted from each other.
The Relation type is used to explain constraints on Sets. Values of the Relation type are Sets of ordered pairs of values from its value domain. For example, a Relation on events is a set of ordered pairs of events. For a Relation R and two values a and b in the value domain of R, a R b is shorthand for saying the ordered pair (a, b) is a member of R. A Relation is least with respect to some conditions when it is the smallest Relation that satisfies those conditions.
A strict partial order is a Relation value R that satisfies the following.
-
For all a, b, and c in R's domain:
- It is not the case that a R a, and
- If a R b and b R c, then a R c.
Note 1
The two properties above are called irreflexivity and transitivity, respectively.
A strict total order is a Relation value R that satisfies the following.
-
For all a, b, and c in R's domain:
- a is identical to b or a R b or b R a, and
- It is not the case that a R a, and
- If a R b and b R c, then a R c.
Note 2
The three properties above are called totality, irreflexivity, and transitivity, respectively.
The Completion type is a Record used to explain the runtime propagation of values and control flow such as the behaviour of statements (break
, continue
, return
and throw
) that perform nonlocal transfers of control.
Values of the Completion type are Record values whose fields are defined by Table 9. Such values are referred to as Completion Records.
Table 9: Completion Record Fields
Field Name | Value | Meaning |
---|---|---|
[[Type]] | One of normal, break, continue, return, or throw | The type of completion that occurred. |
[[Value]] | any ECMAScript language value or empty | The value that was produced. |
[[Target]] | any ECMAScript string or empty | The target label for directed control transfers. |
The term “abrupt completion” refers to any completion with a [[Type]] value other than normal.
Algorithm steps that say
- Let completion be Await(value).
mean the same thing as:
- Let asyncContext be the running execution context.
- Let promise be ? PromiseResolve(%Promise%, value).
- Let stepsFulfilled be the algorithm steps defined in Await Fulfilled Functions.
- Let lengthFulfilled be the number of non-optional parameters of the function definition in Await Fulfilled Functions.
- Let onFulfilled be ! CreateBuiltinFunction(stepsFulfilled, lengthFulfilled, "", « [[AsyncContext]] »).
- Set onFulfilled.[[AsyncContext]] to asyncContext.
- Let stepsRejected be the algorithm steps defined in Await Rejected Functions.
- Let lengthRejected be the number of non-optional parameters of the function definition in Await Rejected Functions.
- Let onRejected be ! CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AsyncContext]] »).
- Set onRejected.[[AsyncContext]] to asyncContext.
- Perform ! PerformPromiseThen(promise, onFulfilled, onRejected).
- Remove asyncContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
- Set the code evaluation state of asyncContext such that when evaluation is resumed with a Completion completion, the following steps of the algorithm that invoked Await will be performed, with completion available.
- Return.
- NOTE: This returns to the evaluation of the operation that had most previously resumed evaluation of asyncContext.
where all aliases in the above steps, with the exception of completion, are ephemeral and visible only in the steps pertaining to Await.
Note
Await can be combined with the ?
and !
prefixes, so that for example
- Let result be ? Await(value).
means the same thing as:
- Let result be Await(value).
- ReturnIfAbrupt(result).
An Await fulfilled function is an anonymous built-in function that is used as part of the Await specification device to deliver the promise fulfillment value to the caller as a normal completion. Each Await fulfilled function has an [[AsyncContext]] internal slot.
When an Await fulfilled function is called with argument value, the following steps are taken:
- Let F be the active function object.
- Let asyncContext be F.[[AsyncContext]].
- Let prevContext be the running execution context.
- Suspend prevContext.
- Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
- Resume the suspended evaluation of asyncContext using NormalCompletion(value) as the result of the operation that suspended it.
- Assert: When we reach this step, asyncContext has already been removed from the execution context stack and prevContext is the currently running execution context.
- Return undefined.
The "length" property of an Await fulfilled function is 1𝔽.
An Await rejected function is an anonymous built-in function that is used as part of the Await specification device to deliver the promise rejection reason to the caller as an abrupt throw completion. Each Await rejected function has an [[AsyncContext]] internal slot.
When an Await rejected function is called with argument reason, the following steps are taken:
- Let F be the active function object.
- Let asyncContext be F.[[AsyncContext]].
- Let prevContext be the running execution context.
- Suspend prevContext.
- Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
- Resume the suspended evaluation of asyncContext using ThrowCompletion(reason) as the result of the operation that suspended it.
- Assert: When we reach this step, asyncContext has already been removed from the execution context stack and prevContext is the currently running execution context.
- Return undefined.
The "length" property of an Await rejected function is 1𝔽.
The abstract operation NormalCompletion with a single argument, such as:
- Return NormalCompletion(argument).
Is a shorthand that is defined as follows:
- Return Completion { [[Type]]: normal, [[Value]]: argument, [[Target]]: empty }.
The abstract operation ThrowCompletion with a single argument, such as:
- Return ThrowCompletion(argument).
Is a shorthand that is defined as follows:
- Return Completion { [[Type]]: throw, [[Value]]: argument, [[Target]]: empty }.
The abstract operation UpdateEmpty takes arguments completionRecord and value. It performs the following steps when called:
- Assert: If completionRecord.[[Type]] is either return or throw, then completionRecord.[[Value]] is not empty.
- If completionRecord.[[Value]] is not empty, return Completion(completionRecord).
- Return Completion { [[Type]]: completionRecord.[[Type]], [[Value]]: value, [[Target]]: completionRecord.[[Target]] }.
The Reference Record type is used to explain the behaviour of such operators as delete
, typeof
, the assignment operators, the super
keyword and other language features. For example, the left-hand operand of an assignment is expected to produce a Reference Record.
A Reference Record is a resolved name or property binding; its fields are defined by Table 10.
Table 10: Reference Record Fields
Field Name | Value | Meaning |
---|---|---|
[[Base]] | One of: |
- any ECMAScript language value except undefined or null,
- an Environment Record, or
- unresolvable.
| The value or Environment Record which holds the binding. A [[Base]] of unresolvable indicates that the binding could not be resolved. |
| [[ReferencedName]] | String or Symbol | The name of the binding. Always a String if [[Base]] value is an Environment Record. |
| [[Strict]] | Boolean | true if the Reference Record originated in strict mode code, false otherwise. |
| [[ThisValue]] | any ECMAScript language value or empty | If not empty, the Reference Record represents a property binding that was expressed using the super
keyword; it is called a Super Reference Record and its [[Base]] value will never be an Environment Record. In that case, the [[ThisValue]] field holds the this value at the time the Reference Record was created. |
The following abstract operations are used in this specification to operate upon References:
The abstract operation IsPropertyReference takes argument V. It performs the following steps when called:
- Assert: V is a Reference Record.
- If V.[[Base]] is unresolvable, return false.
- If Type(V.[[Base]]) is Boolean, String, Symbol, BigInt, Number, or Object, return true; otherwise return false.
The abstract operation IsUnresolvableReference takes argument V. It performs the following steps when called:
- Assert: V is a Reference Record.
- If V.[[Base]] is unresolvable, return true; otherwise return false.
The abstract operation IsSuperReference takes argument V. It performs the following steps when called:
- Assert: V is a Reference Record.
- If V.[[ThisValue]] is not empty, return true; otherwise return false.
The abstract operation GetValue takes argument V. It performs the following steps when called:
- ReturnIfAbrupt(V).
- If V is not a Reference Record, return V.
- If IsUnresolvableReference(V) is true, throw a ReferenceError exception.
- If IsPropertyReference(V) is true, then
- Let baseObj be ! ToObject(V.[[Base]]).
- Return ? baseObj.[[Get]](V.[[ReferencedName]], GetThisValue(V)).
- Else,
- Let base be V.[[Base]].
- Assert: base is an Environment Record.
- Return ? base.GetBindingValue(V.[[ReferencedName]], V.[[Strict]]) (see 9.1).
Note
The object that may be created in step 4.a is not accessible outside of the above abstract operation and the ordinary object [[Get]] internal method. An implementation might choose to avoid the actual creation of the object.
The abstract operation PutValue takes arguments V and W. It performs the following steps when called:
- ReturnIfAbrupt(V).
- ReturnIfAbrupt(W).
- If V is not a Reference Record, throw a ReferenceError exception.
- If IsUnresolvableReference(V) is true, then
- If V.[[Strict]] is true, throw a ReferenceError exception.
- Let globalObj be GetGlobalObject().
- Return ? Set(globalObj, V.[[ReferencedName]], W, false).
- If IsPropertyReference(V) is true, then
- Let baseObj be ! ToObject(V.[[Base]]).
- Let succeeded be ? baseObj.[[Set]](V.[[ReferencedName]], W, GetThisValue(V)).
- If succeeded is false and V.[[Strict]] is true, throw a TypeError exception.
- Return.
- Else,
- Let base be V.[[Base]].
- Assert: base is an Environment Record.
- Return ? base.SetMutableBinding(V.[[ReferencedName]], W, V.[[Strict]]) (see 9.1).
Note
The object that may be created in step 5.a is not accessible outside of the above abstract operation and the ordinary object [[Set]] internal method. An implementation might choose to avoid the actual creation of that object.
The abstract operation GetThisValue takes argument V. It performs the following steps when called:
- Assert: IsPropertyReference(V) is true.
- If IsSuperReference(V) is true, return V.[[ThisValue]]; otherwise return V.[[Base]].
The abstract operation InitializeReferencedBinding takes arguments V and W. It performs the following steps when called:
- ReturnIfAbrupt(V).
- ReturnIfAbrupt(W).
- Assert: V is a Reference Record.
- Assert: IsUnresolvableReference(V) is false.
- Let base be V.[[Base]].
- Assert: base is an Environment Record.
- Return base.InitializeBinding(V.[[ReferencedName]], W).
The Property Descriptor type is used to explain the manipulation and reification of Object property attributes. Values of the Property Descriptor type are Records. Each field's name is an attribute name and its value is a corresponding attribute value as specified in 6.1.7.1. In addition, any field may be present or absent. The schema name used within this specification to tag literal descriptions of Property Descriptor records is “PropertyDescriptor”.
Property Descriptor values may be further classified as data Property Descriptors and accessor Property Descriptors based upon the existence or use of certain fields. A data Property Descriptor is one that includes any fields named either [[Value]] or [[Writable]]. An accessor Property Descriptor is one that includes any fields named either [[Get]] or [[Set]]. Any Property Descriptor may have fields named [[Enumerable]] and [[Configurable]]. A Property Descriptor value may not be both a data Property Descriptor and an accessor Property Descriptor; however, it may be neither. A generic Property Descriptor is a Property Descriptor value that is neither a data Property Descriptor nor an accessor Property Descriptor. A fully populated Property Descriptor is one that is either an accessor Property Descriptor or a data Property Descriptor and that has all of the fields that correspond to the property attributes defined in either Table 3 or Table 4.
The following abstract operations are used in this specification to operate upon Property Descriptor values:
The abstract operation IsAccessorDescriptor takes argument Desc (a Property Descriptor or undefined). It performs the following steps when called:
- If Desc is undefined, return false.
- If both Desc.[[Get]] and Desc.[[Set]] are absent, return false.
- Return true.
The abstract operation IsDataDescriptor takes argument Desc (a Property Descriptor or undefined). It performs the following steps when called:
- If Desc is undefined, return false.
- If both Desc.[[Value]] and Desc.[[Writable]] are absent, return false.
- Return true.
The abstract operation IsGenericDescriptor takes argument Desc (a Property Descriptor or undefined). It performs the following steps when called:
- If Desc is undefined, return false.
- If IsAccessorDescriptor(Desc) and IsDataDescriptor(Desc) are both false, return true.
- Return false.
The abstract operation FromPropertyDescriptor takes argument Desc (a Property Descriptor or undefined). It performs the following steps when called:
- If Desc is undefined, return undefined.
- Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
- Assert: obj is an extensible ordinary object with no own properties.
- If Desc has a [[Value]] field, then
- Perform ! CreateDataPropertyOrThrow(obj, "value", Desc.[[Value]]).
- If Desc has a [[Writable]] field, then
- Perform ! CreateDataPropertyOrThrow(obj, "writable", Desc.[[Writable]]).
- If Desc has a [[Get]] field, then
- Perform ! CreateDataPropertyOrThrow(obj, "get", Desc.[[Get]]).
- If Desc has a [[Set]] field, then
- Perform ! CreateDataPropertyOrThrow(obj, "set", Desc.[[Set]]).
- If Desc has an [[Enumerable]] field, then
- Perform ! CreateDataPropertyOrThrow(obj, "enumerable", Desc.[[Enumerable]]).
- If Desc has a [[Configurable]] field, then
- Perform ! CreateDataPropertyOrThrow(obj, "configurable", Desc.[[Configurable]]).
- Return obj.
The abstract operation ToPropertyDescriptor takes argument Obj. It performs the following steps when called:
- If Type(Obj) is not Object, throw a TypeError exception.
- Let desc be a new Property Descriptor that initially has no fields.
- Let hasEnumerable be ? HasProperty(Obj, "enumerable").
- If hasEnumerable is true, then
- Let hasConfigurable be ? HasProperty(Obj, "configurable").
- If hasConfigurable is true, then
- Let hasValue be ? HasProperty(Obj, "value").
- If hasValue is true, then
- Let value be ? Get(Obj, "value").
- Set desc.[[Value]] to value.
- Let hasWritable be ? HasProperty(Obj, "writable").
- If hasWritable is true, then 1. Let writable be ! ToBoolean(? Get(Obj, "writable")). 2. Set desc.[[Writable]] to writable.
- Let hasGet be ? HasProperty(Obj, "get").
- If hasGet is true, then 1. Let getter be ? Get(Obj, "get"). 2. If IsCallable(getter) is false and getter is not undefined, throw a TypeError exception. 3. Set desc.[[Get]] to getter.
- Let hasSet be ? HasProperty(Obj, "set").
- If hasSet is true, then 1. Let setter be ? Get(Obj, "set"). 2. If IsCallable(setter) is false and setter is not undefined, throw a TypeError exception. 3. Set desc.[[Set]] to setter.
- If desc.[[Get]] is present or desc.[[Set]] is present, then 1. If desc.[[Value]] is present or desc.[[Writable]] is present, throw a TypeError exception.
- Return desc.
The abstract operation CompletePropertyDescriptor takes argument Desc (a Property Descriptor). It performs the following steps when called:
- Assert: Desc is a Property Descriptor.
- Let like be the Record { [[Value]]: undefined, [[Writable]]: false, [[Get]]: undefined, [[Set]]: undefined, [[Enumerable]]: false, [[Configurable]]: false }.
- If IsGenericDescriptor(Desc) is true or IsDataDescriptor(Desc) is true, then
- If Desc does not have a [[Value]] field, set Desc.[[Value]] to like.[[Value]].
- If Desc does not have a [[Writable]] field, set Desc.[[Writable]] to like.[[Writable]].
- Else,
- If Desc does not have a [[Get]] field, set Desc.[[Get]] to like.[[Get]].
- If Desc does not have a [[Set]] field, set Desc.[[Set]] to like.[[Set]].
- If Desc does not have an [[Enumerable]] field, set Desc.[[Enumerable]] to like.[[Enumerable]].
- If Desc does not have a [[Configurable]] field, set Desc.[[Configurable]] to like.[[Configurable]].
- Return Desc.
The Environment Record type is used to explain the behaviour of name resolution in nested functions and blocks. This type and the operations upon it are defined in 9.1.
The Abstract Closure specification type is used to refer to algorithm steps together with a collection of values. Abstract Closures are meta-values and are invoked using function application style such as closure(arg1, arg2). Like abstract operations, invocations perform the algorithm steps described by the Abstract Closure.
In algorithm steps that create an Abstract Closure, values are captured with the verb "capture" followed by a list of aliases. When an Abstract Closure is created, it captures the value that is associated with each alias at that time. In steps that specify the algorithm to be performed when an Abstract Closure is called, each captured value is referred to by the alias that was used to capture the value.
If an Abstract Closure returns a Completion Record, that Completion Record's [[Type]] must be either normal or throw.
Abstract Closures are created inline as part of other algorithms, shown in the following example.
- Let addend be 41.
- Let closure be a new Abstract Closure with parameters (x) that captures addend and performs the following steps when called:
- Return x + addend.
- Let val be closure(1).
- Assert: val is 42.
The Data Block specification type is used to describe a distinct and mutable sequence of byte-sized (8 bit) numeric values. A byte value is an integer value in the range 0 through 255, inclusive. A Data Block value is created with a fixed number of bytes that each have the initial value 0.
For notational convenience within this specification, an array-like syntax can be used to access the individual bytes of a Data Block value. This notation presents a Data Block value as a 0-origined integer-indexed sequence of bytes. For example, if db is a 5 byte Data Block value then db[2] can be used to access its 3rd byte.
A data block that resides in memory that can be referenced from multiple agents concurrently is designated a Shared Data Block. A Shared Data Block has an identity (for the purposes of equality testing Shared Data Block values) that is address-free: it is tied not to the virtual addresses the block is mapped to in any process, but to the set of locations in memory that the block represents. Two data blocks are equal only if the sets of the locations they contain are equal; otherwise, they are not equal and the intersection of the sets of locations they contain is empty. Finally, Shared Data Blocks can be distinguished from Data Blocks.
The semantics of Shared Data Blocks is defined using Shared Data Block events by the memory model. Abstract operations below introduce Shared Data Block events and act as the interface between evaluation semantics and the event semantics of the memory model. The events form a candidate execution, on which the memory model acts as a filter. Please consult the memory model for full semantics.
Shared Data Block events are modeled by Records, defined in the memory model.
The following abstract operations are used in this specification to operate upon Data Block values:
The abstract operation CreateByteDataBlock takes argument size (an integer). It performs the following steps when called:
- Assert: size ≥ 0.
- Let db be a new Data Block value consisting of size bytes. If it is impossible to create such a Data Block, throw a RangeError exception.
- Set all of the bytes of db to 0.
- Return db.
The abstract operation CreateSharedByteDataBlock takes argument size (a non-negative integer). It performs the following steps when called:
- Assert: size ≥ 0.
- Let db be a new Shared Data Block value consisting of size bytes. If it is impossible to create such a Shared Data Block, throw a RangeError exception.
- Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
- Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
- Let zero be « 0 ».
- For each index i of db, do
- Append WriteSharedMemory { [[Order]]: Init, [[NoTear]]: true, [[Block]]: db, [[ByteIndex]]: i, [[ElementSize]]: 1, [[Payload]]: zero } to eventList.
- Return db.
The abstract operation CopyDataBlockBytes takes arguments toBlock, toIndex (a non-negative integer), fromBlock, fromIndex (a non-negative integer), and count (a non-negative integer). It performs the following steps when called:
- Assert: fromBlock and toBlock are distinct Data Block or Shared Data Block values.
- Let fromSize be the number of bytes in fromBlock.
- Assert: fromIndex + count ≤ fromSize.
- Let toSize be the number of bytes in toBlock.
- Assert: toIndex + count ≤ toSize.
- Repeat, while count > 0,
- If fromBlock is a Shared Data Block, then
- Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
- Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
- Let bytes be a List whose sole element is a nondeterministically chosen byte value.
- NOTE: In implementations, bytes is the result of a non-atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the memory model to describe observable behaviour of hardware with weak consistency.
- Let readEvent be ReadSharedMemory { [[Order]]: Unordered, [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }.
- Append readEvent to eventList.
- Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes } to execution.[[ChosenValues]].
- If toBlock is a Shared Data Block, then
- Append WriteSharedMemory { [[Order]]: Unordered, [[NoTear]]: true, [[Block]]: toBlock, [[ByteIndex]]: toIndex, [[ElementSize]]: 1, [[Payload]]: bytes } to eventList.
- Else,
- Set toBlock[toIndex] to bytes[0].
- Else,
- Assert: toBlock is not a Shared Data Block.
- Set toBlock[toIndex] to fromBlock[fromIndex].
- Set toIndex to toIndex + 1.
- Set fromIndex to fromIndex + 1.
- Set count to count - 1.
- If fromBlock is a Shared Data Block, then
- Return NormalCompletion(empty).
These operations are not a part of the ECMAScript language; they are defined here solely to aid the specification of the semantics of the ECMAScript language. Other, more specialized abstract operations are defined throughout this specification.
The ECMAScript language implicitly performs automatic type conversion as needed. To clarify the semantics of certain constructs it is useful to define a set of conversion abstract operations. The conversion abstract operations are polymorphic; they can accept a value of any ECMAScript language type. But no other specification types are used with these operations.
The BigInt type has no implicit conversions in the ECMAScript language; programmers must call BigInt explicitly to convert values from other types.
The abstract operation ToPrimitive takes argument input and optional argument preferredType. It converts its input argument to a non-Object type. If an object is capable of converting to more than one primitive type, it may use the optional hint preferredType to favour that type. It performs the following steps when called:
- Assert: input is an ECMAScript language value.
- If Type(input) is Object, then
- Let exoticToPrim be ? GetMethod(input, @@toPrimitive).
- If exoticToPrim is not undefined, then
- If preferredType is not present, let preferredType be number.
- Return ? OrdinaryToPrimitive(input, preferredType).
- Return input.
Note
When ToPrimitive is called with no hint, then it generally behaves as if the hint were number. However, objects may over-ride this behaviour by defining a @@toPrimitive method. Of the objects defined in this specification only Date objects (see 21.4.4.45) and Symbol objects (see 20.4.3.5) over-ride the default ToPrimitive behaviour. Date objects treat no hint as if the hint were string.
The abstract operation OrdinaryToPrimitive takes arguments O and hint. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: hint is either string or number.
- If hint is string, then
- Let methodNames be « "toString", "valueOf" ».
- Else,
- Let methodNames be « "valueOf", "toString" ».
- For each element name of methodNames, do
- Let method be ? Get(O, name).
- If IsCallable(method) is true, then
- Throw a TypeError exception.
The abstract operation ToBoolean takes argument argument. It converts argument to a value of type Boolean according to Table 11:
Table 11: ToBoolean Conversions
Argument Type | Result |
---|---|
Undefined | Return false. |
Null | Return false. |
Boolean | Return argument. |
Number | If argument is +0𝔽, -0𝔽, or NaN, return false; otherwise return true. |
String | If argument is the empty String (its length is 0), return false; otherwise return true. |
Symbol | Return true. |
BigInt | If argument is 0ℤ, return false; otherwise return true. |
Object | Return true. Note |
An alternate algorithm related to the [[IsHTMLDDA]] internal slot is mandated in section B.3.7.1. |
|
The abstract operation ToNumeric takes argument value. It returns value converted to a Number or a BigInt. It performs the following steps when called:
- Let primValue be ? ToPrimitive(value, number).
- If Type(primValue) is BigInt, return primValue.
- Return ? ToNumber(primValue).
The abstract operation ToNumber takes argument argument. It converts argument to a value of type Number according to Table 12:
Table 12: ToNumber Conversions
Argument Type | Result |
---|---|
Undefined | Return NaN. |
Null | Return +0𝔽. |
Boolean | If argument is true, return 1𝔽. If argument is false, return +0𝔽. |
Number | Return argument (no conversion). |
String | See grammar and conversion algorithm below. |
Symbol | Throw a TypeError exception. |
BigInt | Throw a TypeError exception. |
Object | |
Apply the following steps: |
- Let primValue be ? ToPrimitive(argument, number).
- Return ? ToNumber(primValue).
|
ToNumber applied to Strings applies the following grammar to the input String interpreted as a sequence of UTF-16 encoded code points (6.1.4). If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.
Note 1
The terminal symbols of this grammar are all composed of characters in the Unicode Basic Multilingual Plane (BMP). Therefore, the result of ToNumber will be NaN if the string contains any leading surrogate or trailing surrogate code units, whether paired or unpaired.
StringNumericLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt StrWhiteSpace ::: StrWhiteSpaceChar StrWhiteSpaceopt StrWhiteSpaceChar ::: WhiteSpace LineTerminator StrNumericLiteral ::: StrDecimalLiteral NonDecimalIntegerLiteral[~Sep] StrDecimalLiteral ::: StrUnsignedDecimalLiteral + StrUnsignedDecimalLiteral - StrUnsignedDecimalLiteral StrUnsignedDecimalLiteral ::: Infinity DecimalDigits[~Sep] . DecimalDigits[~Sep]opt ExponentPart[~Sep]opt . DecimalDigits[~Sep] ExponentPart[~Sep]opt DecimalDigits[~Sep] ExponentPart[~Sep]opt
All grammar symbols not explicitly defined above have the definitions used in the Lexical Grammar for numeric literals (12.8.3)
Note 2
Some differences should be noted between the syntax of a StringNumericLiteral and a NumericLiteral:
- A StringNumericLiteral may include leading and/or trailing white space and/or line terminators.
- A StringNumericLiteral that is decimal may have any number of leading
0
digits. - A StringNumericLiteral that is decimal may include a
+
or-
to indicate its sign. - A StringNumericLiteral that is empty or contains only white space is converted to +0𝔽.
Infinity
and-Infinity
are recognized as a StringNumericLiteral but not as a NumericLiteral.- A StringNumericLiteral cannot include a BigIntLiteralSuffix.
The conversion of a String to a Number value is similar overall to the determination of the Number value for a numeric literal (see 12.8.3), but some of the details are different, so the process for converting a String numeric literal to a value of Number type is given here. This value is determined in two steps: first, a mathematical value (MV) is derived from the String numeric literal; second, this mathematical value is rounded as described below. The MV on any grammar symbol, not provided below, is the MV for that symbol defined in 12.8.3.1.
- The MV of StringNumericLiteral ::: [empty] is 0.
- The MV of StringNumericLiteral ::: StrWhiteSpace is 0.
- The MV of StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt is the MV of StrNumericLiteral, no matter whether white space is present or not.
- The MV of StrDecimalLiteral ::: - StrUnsignedDecimalLiteral is the negative of the MV of StrUnsignedDecimalLiteral. (Note that if the MV of StrUnsignedDecimalLiteral is 0, the negative of this MV is also 0. The rounding rule described below handles the conversion of this signless mathematical zero to a floating-point +0𝔽 or -0𝔽 as appropriate.)
- The MV of StrUnsignedDecimalLiteral ::: Infinity is 1010000 (a value so large that it will round to +∞𝔽).
- The MV of StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigits is the MV of the first DecimalDigits plus (the MV of the second DecimalDigits times 10-n), where n is the number of code points in the second DecimalDigits.
- The MV of StrUnsignedDecimalLiteral ::: DecimalDigits . ExponentPart is the MV of DecimalDigits times 10e, where e is the MV of ExponentPart.
- The MV of StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigits ExponentPart is (the MV of the first DecimalDigits plus (the MV of the second DecimalDigits times 10-n)) times 10e, where n is the number of code points in the second DecimalDigits and e is the MV of ExponentPart.
- The MV of StrUnsignedDecimalLiteral ::: . DecimalDigits is the MV of DecimalDigits times 10-n, where n is the number of code points in DecimalDigits.
- The MV of StrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPart is the MV of DecimalDigits times 10e - n, where n is the number of code points in DecimalDigits and e is the MV of ExponentPart.
- The MV of StrUnsignedDecimalLiteral ::: DecimalDigits ExponentPart is the MV of DecimalDigits times 10e, where e is the MV of ExponentPart.
Once the exact MV for a String numeric literal has been determined, it is then rounded to a value of the Number type. If the MV is 0, then the rounded value is +0𝔽 unless the first non white space code point in the String numeric literal is -
, in which case the rounded value is -0𝔽. Otherwise, the rounded value must be the Number value for the MV (in the sense defined in 6.1.6.1), unless the literal includes a StrUnsignedDecimalLiteral and the literal has more than 20 significant digits, in which case the Number value may be either the Number value for the MV of a literal produced by replacing each significant digit after the 20th with a 0 digit or the Number value for the MV of a literal produced by replacing each significant digit after the 20th with a 0 digit and then incrementing the literal at the 20th digit position. A digit is significant if it is not part of an ExponentPart and
- it is not
0
; or - there is a non-zero digit to its left and there is a non-zero digit, not in the ExponentPart, to its right.
The abstract operation ToIntegerOrInfinity takes argument argument. It converts argument to an integer, +∞, or -∞. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0𝔽, or -0𝔽, return 0.
- If number is +∞𝔽, return +∞.
- If number is -∞𝔽, return -∞.
- Let integer be floor(abs(ℝ(number))).
- If number < +0𝔽, set integer to -integer.
- Return integer.
The abstract operation ToInt32 takes argument argument. It converts argument to one of 232 integral Number values in the range 𝔽(-231) through 𝔽(231 - 1), inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.
- Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(ℝ(number))).
- Let int32bit be int modulo 232.
- If int32bit ≥ 231, return 𝔽(int32bit - 232); otherwise return 𝔽(int32bit).
Note
Given the above definition of ToInt32:
- The ToInt32 abstract operation is idempotent: if applied to a result that it produced, the second application leaves that value unchanged.
- ToInt32(ToUint32(x)) is the same value as ToInt32(x) for all values of x. (It is to preserve this latter property that +∞𝔽 and -∞𝔽 are mapped to +0𝔽.)
- ToInt32 maps -0𝔽 to +0𝔽.
The abstract operation ToUint32 takes argument argument. It converts argument to one of 232 integral Number values in the range +0𝔽 through 𝔽(232 - 1), inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.
- Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(ℝ(number))).
- Let int32bit be int modulo 232.
- Return 𝔽(int32bit).
Note
Given the above definition of ToUint32:
- Step 5 is the only difference between ToUint32 and ToInt32.
- The ToUint32 abstract operation is idempotent: if applied to a result that it produced, the second application leaves that value unchanged.
- ToUint32(ToInt32(x)) is the same value as ToUint32(x) for all values of x. (It is to preserve this latter property that +∞𝔽 and -∞𝔽 are mapped to +0𝔽.)
- ToUint32 maps -0𝔽 to +0𝔽.
The abstract operation ToInt16 takes argument argument. It converts argument to one of 216 integral Number values in the range 𝔽(-215) through 𝔽(215 - 1), inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.
- Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(ℝ(number))).
- Let int16bit be int modulo 216.
- If int16bit ≥ 215, return 𝔽(int16bit - 216); otherwise return 𝔽(int16bit).
The abstract operation ToUint16 takes argument argument. It converts argument to one of 216 integral Number values in the range +0𝔽 through 𝔽(216 - 1), inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.
- Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(ℝ(number))).
- Let int16bit be int modulo 216.
- Return 𝔽(int16bit).
Note
Given the above definition of ToUint16:
- The substitution of 216 for 232 in step 4 is the only difference between ToUint32 and ToUint16.
- ToUint16 maps -0𝔽 to +0𝔽.
The abstract operation ToInt8 takes argument argument. It converts argument to one of 28 integral Number values in the range -128𝔽 through 127𝔽, inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.
- Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(ℝ(number))).
- Let int8bit be int modulo 28.
- If int8bit ≥ 27, return 𝔽(int8bit - 28); otherwise return 𝔽(int8bit).
The abstract operation ToUint8 takes argument argument. It converts argument to one of 28 integral Number values in the range +0𝔽 through 255𝔽, inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.
- Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(ℝ(number))).
- Let int8bit be int modulo 28.
- Return 𝔽(int8bit).
The abstract operation ToUint8Clamp takes argument argument. It converts argument to one of 28 integral Number values in the range +0𝔽 through 255𝔽, inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, return +0𝔽.
- If ℝ(number) ≤ 0, return +0𝔽.
- If ℝ(number) ≥ 255, return 255𝔽.
- Let f be floor(ℝ(number)).
- If f + 0.5 < ℝ(number), return 𝔽(f + 1).
- If ℝ(number) < f + 0.5, return 𝔽(f).
- If f is odd, return 𝔽(f + 1).
- Return 𝔽(f).
Note
Unlike the other ECMAScript integer conversion abstract operation, ToUint8Clamp rounds rather than truncates non-integral values and does not convert +∞𝔽 to +0𝔽. ToUint8Clamp does “round half to even” tie-breaking. This differs from Math.round
which does “round half up” tie-breaking.
The abstract operation ToBigInt takes argument argument. It converts argument to a BigInt value, or throws if an implicit conversion from Number would be required. It performs the following steps when called:
- Let prim be ? ToPrimitive(argument, number).
- Return the value that prim corresponds to in Table 13.
Table 13: BigInt Conversions
Argument Type | Result |
---|---|
Undefined | Throw a TypeError exception. |
Null | Throw a TypeError exception. |
Boolean | Return 1n if prim is true and 0n if prim is false. |
BigInt | Return prim. |
Number | Throw a TypeError exception. |
String |
- Let n be ! StringToBigInt(prim).
- If n is NaN, throw a SyntaxError exception.
- Return n.
| | Symbol | Throw a TypeError exception. |
Apply the algorithm in 7.1.4.1 with the following changes:
- Replace the StrUnsignedDecimalLiteral production with DecimalDigits to not allow Infinity, decimal points, or exponents.
- If the MV is NaN, return NaN, otherwise return the BigInt which exactly corresponds to the MV, rather than rounding to a Number.
The abstract operation ToBigInt64 takes argument argument. It converts argument to one of 264 BigInt values in the range ℤ(-263) through ℤ(263-1), inclusive. It performs the following steps when called:
- Let n be ? ToBigInt(argument).
- Let int64bit be ℝ(n) modulo 264.
- If int64bit ≥ 263, return ℤ(int64bit - 264); otherwise return ℤ(int64bit).
The abstract operation ToBigUint64 takes argument argument. It converts argument to one of 264 BigInt values in the range 0ℤ through the BigInt value for ℤ(264-1), inclusive. It performs the following steps when called:
The abstract operation ToString takes argument argument. It converts argument to a value of type String according to Table 14:
Table 14: ToString Conversions
Argument Type | Result |
---|---|
Undefined | Return "undefined". |
Null | Return "null". |
Boolean | |
If argument is true, return "true". |
If argument is false, return "false".
| | Number | Return ! Number::toString(argument). | | String | Return argument. | | Symbol | Throw a TypeError exception. | | BigInt | Return ! BigInt::toString(argument). | | Object |
Apply the following steps:
- Let primValue be ? ToPrimitive(argument, string).
- Return ? ToString(primValue).
|
The abstract operation ToObject takes argument argument. It converts argument to a value of type Object according to Table 15:
Table 15: ToObject Conversions
Argument Type | Result |
---|---|
Undefined | Throw a TypeError exception. |
Null | Throw a TypeError exception. |
Boolean | Return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 20.3 for a description of Boolean objects. |
Number | Return a new Number object whose [[NumberData]] internal slot is set to argument. See 21.1 for a description of Number objects. |
String | Return a new String object whose [[StringData]] internal slot is set to argument. See 22.1 for a description of String objects. |
Symbol | Return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 20.4 for a description of Symbol objects. |
BigInt | Return a new BigInt object whose [[BigIntData]] internal slot is set to argument. See 21.2 for a description of BigInt objects. |
Object | Return argument. |
The abstract operation ToPropertyKey takes argument argument. It converts argument to a value that can be used as a property key. It performs the following steps when called:
- Let key be ? ToPrimitive(argument, string).
- If Type(key) is Symbol, then
- Return key.
- Return ! ToString(key).
The abstract operation ToLength takes argument argument. It converts argument to an integral Number suitable for use as the length of an array-like object. It performs the following steps when called:
- Let len be ? ToIntegerOrInfinity(argument).
- If len ≤ 0, return +0𝔽.
- Return 𝔽(min(len, 253 - 1)).
The abstract operation CanonicalNumericIndexString takes argument argument. It returns argument converted to a Number value if it is a String representation of a Number that would be produced by ToString, or the string "-0". Otherwise, it returns undefined. It performs the following steps when called:
- Assert: Type(argument) is String.
- If argument is "-0", return -0𝔽.
- Let n be ! ToNumber(argument).
- If SameValue(! ToString(n), argument) is false, return undefined.
- Return n.
A canonical numeric string is any String value for which the CanonicalNumericIndexString abstract operation does not return undefined.
The abstract operation ToIndex takes argument value. It returns value argument converted to a non-negative integer if it is a valid integer index value. It performs the following steps when called:
- If value is undefined, then
- Return 0.
- Else,
- Let integerIndex be 𝔽(? ToIntegerOrInfinity(value)).
- If integerIndex < +0𝔽, throw a RangeError exception.
- Let index be ! ToLength(integerIndex).
- If ! SameValue(integerIndex, index) is false, throw a RangeError exception.
- Return ℝ(index).
The abstract operation RequireObjectCoercible takes argument argument. It throws an error if argument is a value that cannot be converted to an Object using ToObject. It is defined by Table 16:
Table 16: RequireObjectCoercible Results
Argument Type | Result |
---|---|
Undefined | Throw a TypeError exception. |
Null | Throw a TypeError exception. |
Boolean | Return argument. |
Number | Return argument. |
String | Return argument. |
Symbol | Return argument. |
BigInt | Return argument. |
Object | Return argument. |
The abstract operation IsArray takes argument argument. It performs the following steps when called:
- If Type(argument) is not Object, return false.
- If argument is an Array exotic object, return true.
- If argument is a Proxy exotic object, then
- If argument.[[ProxyHandler]] is null, throw a TypeError exception.
- Let target be argument.[[ProxyTarget]].
- Return ? IsArray(target).
- Return false.
The abstract operation IsCallable takes argument argument (an ECMAScript language value). It determines if argument is a callable function with a [[Call]] internal method. It performs the following steps when called:
- If Type(argument) is not Object, return false.
- If argument has a [[Call]] internal method, return true.
- Return false.
The abstract operation IsConstructor takes argument argument (an ECMAScript language value). It determines if argument is a function object with a [[Construct]] internal method. It performs the following steps when called:
- If Type(argument) is not Object, return false.
- If argument has a [[Construct]] internal method, return true.
- Return false.
The abstract operation IsExtensible takes argument O (an Object) and returns a completion record which, if its [[Type]] is normal, has a [[Value]] which is a Boolean. It is used to determine whether additional properties can be added to O. It performs the following steps when called:
The abstract operation IsIntegralNumber takes argument argument. It determines if argument is a finite integral Number value. It performs the following steps when called:
- If Type(argument) is not Number, return false.
- If argument is NaN, +∞𝔽, or -∞𝔽, return false.
- If floor(abs(ℝ(argument))) ≠ abs(ℝ(argument)), return false.
- Return true.
The abstract operation IsPropertyKey takes argument argument (an ECMAScript language value). It determines if argument is a value that may be used as a property key. It performs the following steps when called:
The abstract operation IsRegExp takes argument argument. It performs the following steps when called:
- If Type(argument) is not Object, return false.
- Let matcher be ? Get(argument, @@match).
- If matcher is not undefined, return ! ToBoolean(matcher).
- If argument has a [[RegExpMatcher]] internal slot, return true.
- Return false.
The abstract operation IsStringPrefix takes arguments p (a String) and q (a String). It determines if p is a prefix of q. It performs the following steps when called:
- Assert: Type(p) is String.
- Assert: Type(q) is String.
- If q can be the string-concatenation of p and some other String r, return true. Otherwise, return false.
Note
Any String is a prefix of itself, because r may be the empty String.
The abstract operation SameValue takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a completion record whose [[Type]] is normal and whose [[Value]] is a Boolean. It performs the following steps when called:
- If Type(x) is different from Type(y), return false.
- If Type(x) is Number or BigInt, then
- Return ! Type(x)::sameValue(x, y).
- Return ! SameValueNonNumeric(x, y).
Note
This algorithm differs from the Strict Equality Comparison Algorithm in its treatment of signed zeroes and NaNs.
The abstract operation SameValueZero takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a completion record whose [[Type]] is normal and whose [[Value]] is a Boolean. It performs the following steps when called:
- If Type(x) is different from Type(y), return false.
- If Type(x) is Number or BigInt, then
- Return ! Type(x)::sameValueZero(x, y).
- Return ! SameValueNonNumeric(x, y).
Note
SameValueZero differs from SameValue only in its treatment of +0𝔽 and -0𝔽.
The abstract operation SameValueNonNumeric takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a completion record whose [[Type]] is normal and whose [[Value]] is a Boolean. It performs the following steps when called:
- Assert: Type(x) is not Number or BigInt.
- Assert: Type(x) is the same as Type(y).
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- If Type(x) is String, then
- If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false.
- If Type(x) is Boolean, then
- If x and y are both true or both false, return true; otherwise, return false.
- If Type(x) is Symbol, then
- If x and y are both the same Symbol value, return true; otherwise, return false.
- If x and y are the same Object value, return true. Otherwise, return false.
The comparison x < y, where x and y are values, produces true, false, or undefined (which indicates that at least one operand is NaN). In addition to x and y the algorithm takes a Boolean flag named LeftFirst as a parameter. The flag is used to control the order in which operations with potentially visible side-effects are performed upon x and y. It is necessary because ECMAScript specifies left to right evaluation of expressions. The default value of LeftFirst is true and indicates that the x parameter corresponds to an expression that occurs to the left of the y parameter's corresponding expression. If LeftFirst is false, the reverse is the case and operations must be performed upon y before x. Such a comparison is performed as follows:
- If the LeftFirst flag is true, then
- Let px be ? ToPrimitive(x, number).
- Let py be ? ToPrimitive(y, number).
- Else,
- NOTE: The order of evaluation needs to be reversed to preserve left to right evaluation.
- Let py be ? ToPrimitive(y, number).
- Let px be ? ToPrimitive(x, number).
- If Type(px) is String and Type(py) is String, then
- If IsStringPrefix(py, px) is true, return false.
- If IsStringPrefix(px, py) is true, return true.
- Let k be the smallest non-negative integer such that the code unit at index k within px is different from the code unit at index k within py. (There must be such a k, for neither String is a prefix of the other.)
- Let m be the integer that is the numeric value of the code unit at index k within px.
- Let n be the integer that is the numeric value of the code unit at index k within py.
- If m < n, return true. Otherwise, return false.
- Else,
- If Type(px) is BigInt and Type(py) is String, then
- Let ny be ! StringToBigInt(py).
- If ny is NaN, return undefined.
- Return BigInt::lessThan(px, ny).
- If Type(px) is String and Type(py) is BigInt, then
- Let nx be ! StringToBigInt(px).
- If nx is NaN, return undefined.
- Return BigInt::lessThan(nx, py).
- NOTE: Because px and py are primitive values, evaluation order is not important.
- Let nx be ! ToNumeric(px).
- Let ny be ! ToNumeric(py).
- If Type(nx) is the same as Type(ny), return Type(nx)::lessThan(nx, ny).
- Assert: Type(nx) is BigInt and Type(ny) is Number, or Type(nx) is Number and Type(ny) is BigInt.
- If nx or ny is NaN, return undefined.
- If nx is -∞𝔽 or ny is +∞𝔽, return true.
- If nx is +∞𝔽 or ny is -∞𝔽, return false.
- If ℝ(nx) < ℝ(ny), return true; otherwise return false.
- If Type(px) is BigInt and Type(py) is String, then
Note 1
Step 3 differs from step 2.c in the algorithm that handles the addition operator +
(13.15.3) by using the logical-and operation instead of the logical-or operation.
Note 2
The comparison of Strings uses a simple lexicographic ordering on sequences of code unit values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore String values that are canonically equal according to the Unicode standard could test as unequal. In effect this algorithm assumes that both Strings are already in normalized form. Also, note that for strings containing supplementary characters, lexicographic ordering on sequences of UTF-16 code unit values differs from that on sequences of code point values.
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is the same as Type(y), then
- Return the result of performing Strict Equality Comparison x === y.
- If x is null and y is undefined, return true.
- If x is undefined and y is null, return true.
- NOTE: This step is replaced in section B.3.7.2.
- If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
- If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
- If Type(x) is BigInt and Type(y) is String, then
- Let n be ! StringToBigInt(y).
- If n is NaN, return false.
- Return the result of the comparison x == n.
- If Type(x) is String and Type(y) is BigInt, return the result of the comparison y == x.
- If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
- If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
- If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return the result of the comparison x == ? ToPrimitive(y).
- If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return the result of the comparison ? ToPrimitive(x) == y.
- If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then 1. If x or y are any of NaN, +∞𝔽, or -∞𝔽, return false. 2. If ℝ(x) = ℝ(y), return true; otherwise return false.
- Return false.
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- If Type(x) is Number or BigInt, then
- Return ! Type(x)::equal(x, y).
- Return ! SameValueNonNumeric(x, y).
Note
This algorithm differs from the SameValue Algorithm in its treatment of signed zeroes and NaNs.
The abstract operation MakeBasicObject takes argument internalSlotsList. It is the source of all ECMAScript objects that are created algorithmically, including both ordinary objects and exotic objects. It factors out common steps used in creating all objects, and centralizes object creation. It performs the following steps when called:
- Assert: internalSlotsList is a List of internal slot names.
- Let obj be a newly created object with an internal slot for each name in internalSlotsList.
- Set obj's essential internal methods to the default ordinary object definitions specified in 10.1.
- Assert: If the caller will not be overriding both obj's [[GetPrototypeOf]] and [[SetPrototypeOf]] essential internal methods, then internalSlotsList contains [[Prototype]].
- Assert: If the caller will not be overriding all of obj's [[SetPrototypeOf]], [[IsExtensible]], and [[PreventExtensions]] essential internal methods, then internalSlotsList contains [[Extensible]].
- If internalSlotsList contains [[Extensible]], set obj.[[Extensible]] to true.
- Return obj.
Note
Within this specification, exotic objects are created in abstract operations such as ArrayCreate and BoundFunctionCreate by first calling MakeBasicObject to obtain a basic, foundational object, and then overriding some or all of that object's internal methods. In order to encapsulate exotic object creation, the object's essential internal methods are never modified outside those operations.
The abstract operation Get takes arguments O (an Object) and P (a property key). It is used to retrieve the value of a specific property of an object. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Return ? O.[[Get]](P, O).
The abstract operation GetV takes arguments V (an ECMAScript language value) and P (a property key). It is used to retrieve the value of a specific property of an ECMAScript language value. If the value is not an object, the property lookup is performed using a wrapper object appropriate for the type of the value. It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let O be ? ToObject(V).
- Return ? O.[[Get]](P, V).
The abstract operation Set takes arguments O (an Object), P (a property key), V (an ECMAScript language value), and Throw (a Boolean). It is used to set the value of a specific property of an object. V is the new value for the property. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Assert: Type(Throw) is Boolean.
- Let success be ? O.[[Set]](P, V, O).
- If success is false and Throw is true, throw a TypeError exception.
- Return success.
The abstract operation CreateDataProperty takes arguments O (an Object), P (a property key), and V (an ECMAScript language value). It is used to create a new own property of an object. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
- Return ? O.[[DefineOwnProperty]](P, newDesc).
Note
This abstract operation creates a property whose attributes are set to the same defaults used for properties created by the ECMAScript language assignment operator. Normally, the property will not already exist. If it does exist and is not configurable or if O is not extensible, [[DefineOwnProperty]] will return false.
The abstract operation CreateMethodProperty takes arguments O (an Object), P (a property key), and V (an ECMAScript language value). It is used to create a new own property of an object. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }.
- Return ? O.[[DefineOwnProperty]](P, newDesc).
Note
This abstract operation creates a property whose attributes are set to the same defaults used for built-in methods and methods defined using class declaration syntax. Normally, the property will not already exist. If it does exist and is not configurable or if O is not extensible, [[DefineOwnProperty]] will return false.
The abstract operation CreateDataPropertyOrThrow takes arguments O (an Object), P (a property key), and V (an ECMAScript language value). It is used to create a new own property of an object. It throws a TypeError exception if the requested property update cannot be performed. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Let success be ? CreateDataProperty(O, P, V).
- If success is false, throw a TypeError exception.
- Return success.
Note
This abstract operation creates a property whose attributes are set to the same defaults used for properties created by the ECMAScript language assignment operator. Normally, the property will not already exist. If it does exist and is not configurable or if O is not extensible, [[DefineOwnProperty]] will return false causing this operation to throw a TypeError exception.
The abstract operation DefinePropertyOrThrow takes arguments O (an Object), P (a property key), and desc (a Property Descriptor). It is used to call the [[DefineOwnProperty]] internal method of an object in a manner that will throw a TypeError exception if the requested property update cannot be performed. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Let success be ? O.[[DefineOwnProperty]](P, desc).
- If success is false, throw a TypeError exception.
- Return success.
The abstract operation DeletePropertyOrThrow takes arguments O (an Object) and P (a property key). It is used to remove a specific own property of an object. It throws an exception if the property is not configurable. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Let success be ? O.[[Delete]](P).
- If success is false, throw a TypeError exception.
- Return success.
The abstract operation GetMethod takes arguments V (an ECMAScript language value) and P (a property key). It is used to get the value of a specific property of an ECMAScript language value when the value of the property is expected to be a function. It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let func be ? GetV(V, P).
- If func is either undefined or null, return undefined.
- If IsCallable(func) is false, throw a TypeError exception.
- Return func.
The abstract operation HasProperty takes arguments O (an Object) and P (a property key) and returns a completion record which, if its [[Type]] is normal, has a [[Value]] which is a Boolean. It is used to determine whether an object has a property with the specified property key. The property may be either an own or inherited. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Return ? O.[[HasProperty]](P).
The abstract operation HasOwnProperty takes arguments O (an Object) and P (a property key) and returns a completion record which, if its [[Type]] is normal, has a [[Value]] which is a Boolean. It is used to determine whether an object has an own property with the specified property key. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Let desc be ? O.[[GetOwnProperty]](P).
- If desc is undefined, return false.
- Return true.
The abstract operation Call takes arguments F (an ECMAScript language value) and V (an ECMAScript language value) and optional argument argumentsList (a List of ECMAScript language values). It is used to call the [[Call]] internal method of a function object. F is the function object, V is an ECMAScript language value that is the this value of the [[Call]], and argumentsList is the value passed to the corresponding argument of the internal method. If argumentsList is not present, a new empty List is used as its value. It performs the following steps when called:
- If argumentsList is not present, set argumentsList to a new empty List.
- If IsCallable(F) is false, throw a TypeError exception.
- Return ? F.[[Call]](V, argumentsList).
The abstract operation Construct takes argument F (a function object) and optional arguments argumentsList and newTarget. It is used to call the [[Construct]] internal method of a function object. argumentsList and newTarget are the values to be passed as the corresponding arguments of the internal method. If argumentsList is not present, a new empty List is used as its value. If newTarget is not present, F is used as its value. It performs the following steps when called:
- If newTarget is not present, set newTarget to F.
- If argumentsList is not present, set argumentsList to a new empty List.
- Assert: IsConstructor(F) is true.
- Assert: IsConstructor(newTarget) is true.
- Return ? F.[[Construct]](argumentsList, newTarget).
Note
If newTarget is not present, this operation is equivalent to: new F(...argumentsList)
The abstract operation SetIntegrityLevel takes arguments O and level. It is used to fix the set of own properties of an object. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: level is either sealed or frozen.
- Let status be ? O.[[PreventExtensions]]().
- If status is false, return false.
- Let keys be ? O.[[OwnPropertyKeys]]().
- If level is sealed, then
- For each element k of keys, do
- Perform ? DefinePropertyOrThrow(O, k, PropertyDescriptor { [[Configurable]]: false }).
- For each element k of keys, do
- Else,
- Assert: level is frozen.
- For each element k of keys, do
- Let currentDesc be ? O.[[GetOwnProperty]](k).
- If currentDesc is not undefined, then
- If IsAccessorDescriptor(currentDesc) is true, then
- Let desc be the PropertyDescriptor { [[Configurable]]: false }.
- Else,
- Let desc be the PropertyDescriptor { [[Configurable]]: false, [[Writable]]: false }.
- Perform ? DefinePropertyOrThrow(O, k, desc).
- If IsAccessorDescriptor(currentDesc) is true, then
- Return true.
The abstract operation TestIntegrityLevel takes arguments O and level. It is used to determine if the set of own properties of an object are fixed. It performs the following steps when called:
- Assert: Type(O) is Object.
- Assert: level is either sealed or frozen.
- Let extensible be ? IsExtensible(O).
- If extensible is true, return false.
- NOTE: If the object is extensible, none of its properties are examined.
- Let keys be ? O.[[OwnPropertyKeys]]().
- For each element k of keys, do
- Let currentDesc be ? O.[[GetOwnProperty]](k).
- If currentDesc is not undefined, then
- If currentDesc.[[Configurable]] is true, return false.
- If level is frozen and IsDataDescriptor(currentDesc) is true, then
- If currentDesc.[[Writable]] is true, return false.
- Return true.
The abstract operation CreateArrayFromList takes argument elements (a List). It is used to create an Array object whose elements are provided by elements. It performs the following steps when called:
- Assert: elements is a List whose elements are all ECMAScript language values.
- Let array be ! ArrayCreate(0).
- Let n be 0.
- For each element e of elements, do
- Perform ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), e).
- Set n to n + 1.
- Return array.
The abstract operation LengthOfArrayLike takes argument obj. It returns the value of the "length" property of an array-like object (as a non-negative integer). It performs the following steps when called:
An array-like object is any object for which this operation returns an integer rather than an abrupt completion.
Note 1
Typically, an array-like object would also have some properties with
names. However, that is not a requirement of this definition.
Note 2
Array objects and String objects are examples of array-like objects.
The abstract operation CreateListFromArrayLike takes argument obj and optional argument elementTypes (a List of names of ECMAScript Language Types). It is used to create a List value whose elements are provided by the indexed properties of obj. elementTypes contains the names of ECMAScript Language Types that are allowed for element values of the List that is created. It performs the following steps when called:
- If elementTypes is not present, set elementTypes to « Undefined, Null, Boolean, String, Symbol, Number, BigInt, Object ».
- If Type(obj) is not Object, throw a TypeError exception.
- Let len be ? LengthOfArrayLike(obj).
- Let list be a new empty List.
- Let index be 0.
- Repeat, while index < len,
- Return list.
The abstract operation Invoke takes arguments V (an ECMAScript language value) and P (a property key) and optional argument argumentsList (a List of ECMAScript language values). It is used to call a method property of an ECMAScript language value. V serves as both the lookup point for the property and the this value of the call. argumentsList is the list of arguments values passed to the method. If argumentsList is not present, a new empty List is used as its value. It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If argumentsList is not present, set argumentsList to a new empty List.
- Let func be ? GetV(V, P).
- Return ? Call(func, V, argumentsList).
The abstract operation OrdinaryHasInstance takes arguments C (an ECMAScript language value) and O. It implements the default algorithm for determining if O inherits from the instance object inheritance path provided by C. It performs the following steps when called:
- If IsCallable(C) is false, return false.
- If C has a [[BoundTargetFunction]] internal slot, then
- Let BC be C.[[BoundTargetFunction]].
- Return ? InstanceofOperator(O, BC).
- If Type(O) is not Object, return false.
- Let P be ? Get(C, "prototype").
- If Type(P) is not Object, throw a TypeError exception.
- Repeat,
- Set O to ? O.[[GetPrototypeOf]]().
- If O is null, return false.
- If SameValue(P, O) is true, return true.
The abstract operation SpeciesConstructor takes arguments O (an Object) and defaultConstructor (a constructor). It is used to retrieve the constructor that should be used to create new objects that are derived from O. defaultConstructor is the constructor to use if a constructor @@species property cannot be found starting from O. It performs the following steps when called:
- Assert: Type(O) is Object.
- Let C be ? Get(O, "constructor").
- If C is undefined, return defaultConstructor.
- If Type(C) is not Object, throw a TypeError exception.
- Let S be ? Get(C, @@species).
- If S is either undefined or null, return defaultConstructor.
- If IsConstructor(S) is true, return S.
- Throw a TypeError exception.
The abstract operation EnumerableOwnPropertyNames takes arguments O (an Object) and kind (one of key, value, or key+value). It performs the following steps when called:
- Assert: Type(O) is Object.
- Let ownKeys be ? O.[[OwnPropertyKeys]]().
- Let properties be a new empty List.
- For each element key of ownKeys, do
- If Type(key) is String, then
- Let desc be ? O.[[GetOwnProperty]](key).
- If desc is not undefined and desc.[[Enumerable]] is true, then
- If kind is key, append key to properties.
- Else,
- Let value be ? Get(O, key).
- If kind is value, append value to properties.
- Else,
- Assert: kind is key+value.
- Let entry be ! CreateArrayFromList(« key, value »).
- Append entry to properties.
- If Type(key) is String, then
- Return properties.
The abstract operation GetFunctionRealm takes argument obj. It performs the following steps when called:
- Assert: ! IsCallable(obj) is true.
- If obj has a [[Realm]] internal slot, then
- Return obj.[[Realm]].
- If obj is a bound function exotic object, then
- Let target be obj.[[BoundTargetFunction]].
- Return ? GetFunctionRealm(target).
- If obj is a Proxy exotic object, then
- If obj.[[ProxyHandler]] is null, throw a TypeError exception.
- Let proxyTarget be obj.[[ProxyTarget]].
- Return ? GetFunctionRealm(proxyTarget).
- Return the current Realm Record.
Note
Step 5 will only be reached if obj is a non-standard function exotic object that does not have a [[Realm]] internal slot.
The abstract operation CopyDataProperties takes arguments target, source, and excludedItems. It performs the following steps when called:
- Assert: Type(target) is Object.
- Assert: excludedItems is a List of property keys.
- If source is undefined or null, return target.
- Let from be ! ToObject(source).
- Let keys be ? from.[[OwnPropertyKeys]]().
- For each element nextKey of keys, do
- Let excluded be false.
- For each element e of excludedItems, do
- If SameValue(e, nextKey) is true, then
- Set excluded to true.
- If SameValue(e, nextKey) is true, then
- If excluded is false, then
- Let desc be ? from.[[GetOwnProperty]](nextKey).
- If desc is not undefined and desc.[[Enumerable]] is true, then
- Let propValue be ? Get(from, nextKey).
- Perform ! CreateDataPropertyOrThrow(target, nextKey, propValue).
- Return target.
Note
The target passed in here is always a newly created object which is not directly accessible in case of an error being thrown.
See Common Iteration Interfaces (27.1).
The abstract operation GetIterator takes argument obj and optional arguments hint and method. It performs the following steps when called:
- If hint is not present, set hint to sync.
- Assert: hint is either sync or async.
- If method is not present, then
- If hint is async, then
- Set method to ? GetMethod(obj, @@asyncIterator).
- If method is undefined, then
- Let syncMethod be ? GetMethod(obj, @@iterator).
- Let syncIteratorRecord be ? GetIterator(obj, sync, syncMethod).
- Return ! CreateAsyncFromSyncIterator(syncIteratorRecord).
- Otherwise, set method to ? GetMethod(obj, @@iterator).
- If hint is async, then
- Let iterator be ? Call(method, obj).
- If Type(iterator) is not Object, throw a TypeError exception.
- Let nextMethod be ? GetV(iterator, "next").
- Let iteratorRecord be the Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
- Return iteratorRecord.
The abstract operation IteratorNext takes argument iteratorRecord and optional argument value. It performs the following steps when called:
- If value is not present, then
- Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
- Else,
- Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »).
- If Type(result) is not Object, throw a TypeError exception.
- Return result.
The abstract operation IteratorComplete takes argument iterResult. It performs the following steps when called:
The abstract operation IteratorValue takes argument iterResult. It performs the following steps when called:
The abstract operation IteratorStep takes argument iteratorRecord. It requests the next value from iteratorRecord.[[Iterator]] by calling iteratorRecord.[[NextMethod]] and returns either false indicating that the iterator has reached its end or the IteratorResult object if a next value is available. It performs the following steps when called:
- Let result be ? IteratorNext(iteratorRecord).
- Let done be ? IteratorComplete(result).
- If done is true, return false.
- Return result.
The abstract operation IteratorClose takes arguments iteratorRecord and completion. It is used to notify an iterator that it should perform any actions it would normally perform when it has reached its completed state. It performs the following steps when called:
- Assert: Type(iteratorRecord.[[Iterator]]) is Object.
- Assert: completion is a Completion Record.
- Let iterator be iteratorRecord.[[Iterator]].
- Let innerResult be GetMethod(iterator, "return").
- If innerResult.[[Type]] is normal, then
- Let return be innerResult.[[Value]].
- If return is undefined, return Completion(completion).
- Set innerResult to Call(return, iterator).
- If completion.[[Type]] is throw, return Completion(completion).
- If innerResult.[[Type]] is throw, return Completion(innerResult).
- If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception.
- Return Completion(completion).
The abstract operation AsyncIteratorClose takes arguments iteratorRecord and completion. It is used to notify an async iterator that it should perform any actions it would normally perform when it has reached its completed state. It performs the following steps when called:
- Assert: Type(iteratorRecord.[[Iterator]]) is Object.
- Assert: completion is a Completion Record.
- Let iterator be iteratorRecord.[[Iterator]].
- Let innerResult be GetMethod(iterator, "return").
- If innerResult.[[Type]] is normal, then
- Let return be innerResult.[[Value]].
- If return is undefined, return Completion(completion).
- Set innerResult to Call(return, iterator).
- If innerResult.[[Type]] is normal, set innerResult to Await(innerResult.[[Value]]).
- If completion.[[Type]] is throw, return Completion(completion).
- If innerResult.[[Type]] is throw, return Completion(innerResult).
- If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception.
- Return Completion(completion).
The abstract operation CreateIterResultObject takes arguments value and done. It creates an object that supports the IteratorResult interface. It performs the following steps when called:
- Assert: Type(done) is Boolean.
- Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
- Perform ! CreateDataPropertyOrThrow(obj, "value", value).
- Perform ! CreateDataPropertyOrThrow(obj, "done", done).
- Return obj.
The abstract operation CreateListIteratorRecord takes argument list. It creates an Iterator (27.1.1.2) object record whose next method returns the successive elements of list. It performs the following steps when called:
- Let closure be a new Abstract Closure with no parameters that captures list and performs the following steps when called:
- For each element E of list, do
- Perform ? Yield(E).
- Return undefined.
- For each element E of list, do
- Let iterator be ! CreateIteratorFromClosure(closure, empty, %IteratorPrototype%).
- Return Record { [[Iterator]]: iterator, [[NextMethod]]: %GeneratorFunction.prototype.prototype.next%, [[Done]]: false }.
Note
The list iterator object is never directly accessible to ECMAScript code.
The abstract operation IterableToList takes argument items and optional argument method. It performs the following steps when called:
- If method is present, then
- Let iteratorRecord be ? GetIterator(items, sync, method).
- Else,
- Let iteratorRecord be ? GetIterator(items, sync).
- Let values be a new empty List.
- Let next be true.
- Repeat, while next is not false,
- Set next to ? IteratorStep(iteratorRecord).
- If next is not false, then
- Let nextValue be ? IteratorValue(next).
- Append nextValue to the end of the List values.
- Return values.
In addition to those defined in this section, specialized syntax-directed operations are defined throughout this specification.
Note
"*default*" is used within this specification as a synthetic name for hoistable anonymous functions that are defined using export declarations.
BindingIdentifier : Identifier
- Return a List whose sole element is the StringValue of Identifier.
BindingIdentifier : yield
- Return a List whose sole element is "yield".
BindingIdentifier : await
- Return a List whose sole element is "await".
LexicalDeclaration : LetOrConst BindingList ;
- Return the BoundNames of BindingList.
BindingList : BindingList , LexicalBinding
- Let names be the BoundNames of BindingList.
- Append to names the elements of the BoundNames of LexicalBinding.
- Return names.
LexicalBinding : BindingIdentifier Initializeropt
- Return the BoundNames of BindingIdentifier.
LexicalBinding : BindingPattern Initializer
- Return the BoundNames of BindingPattern.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
- Let names be BoundNames of VariableDeclarationList.
- Append to names the elements of BoundNames of VariableDeclaration.
- Return names.
VariableDeclaration : BindingIdentifier Initializeropt
- Return the BoundNames of BindingIdentifier.
VariableDeclaration : BindingPattern Initializer
- Return the BoundNames of BindingPattern.
ObjectBindingPattern : { }
- Return a new empty List.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
- Let names be BoundNames of BindingPropertyList.
- Append to names the elements of BoundNames of BindingRestProperty.
- Return names.
ArrayBindingPattern : [ Elisionopt ]
- Return a new empty List.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
- Return the BoundNames of BindingRestElement.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
- Return the BoundNames of BindingElementList.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
- Let names be BoundNames of BindingElementList.
- Append to names the elements of BoundNames of BindingRestElement.
- Return names.
BindingPropertyList : BindingPropertyList , BindingProperty
- Let names be BoundNames of BindingPropertyList.
- Append to names the elements of BoundNames of BindingProperty.
- Return names.
BindingElementList : BindingElementList , BindingElisionElement
- Let names be BoundNames of BindingElementList.
- Append to names the elements of BoundNames of BindingElisionElement.
- Return names.
BindingElisionElement : Elisionopt BindingElement
- Return BoundNames of BindingElement.
BindingProperty : PropertyName : BindingElement
- Return the BoundNames of BindingElement.
SingleNameBinding : BindingIdentifier Initializeropt
- Return the BoundNames of BindingIdentifier.
BindingElement : BindingPattern Initializeropt
- Return the BoundNames of BindingPattern.
ForDeclaration : LetOrConst ForBinding
- Return the BoundNames of ForBinding.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
- Return the BoundNames of BindingIdentifier.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
- Return « "*default*" ».
FormalParameters : [empty]
- Return a new empty List.
FormalParameters : FormalParameterList , FunctionRestParameter
- Let names be BoundNames of FormalParameterList.
- Append to names the BoundNames of FunctionRestParameter.
- Return names.
FormalParameterList : FormalParameterList , FormalParameter
- Let names be BoundNames of FormalParameterList.
- Append to names the BoundNames of FormalParameter.
- Return names.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
- Let formals be CoveredFormalsList of CoverParenthesizedExpressionAndArrowParameterList.
- Return the BoundNames of formals.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
- Return the BoundNames of BindingIdentifier.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
- Return « "*default*" ».
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
- Return the BoundNames of BindingIdentifier.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
- Return « "*default*" ».
ClassDeclaration : class BindingIdentifier ClassTail
- Return the BoundNames of BindingIdentifier.
ClassDeclaration : class ClassTail
- Return « "*default*" ».
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
- Return the BoundNames of BindingIdentifier.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
- Return « "*default*" ».
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
- Let head be CoveredAsyncArrowHead of CoverCallExpressionAndAsyncArrowHead.
- Return the BoundNames of head.
ImportDeclaration : import ImportClause FromClause ;
- Return the BoundNames of ImportClause.
ImportDeclaration : import ModuleSpecifier ;
- Return a new empty List.
ImportClause : ImportedDefaultBinding , NameSpaceImport
- Let names be the BoundNames of ImportedDefaultBinding.
- Append to names the elements of the BoundNames of NameSpaceImport.
- Return names.
ImportClause : ImportedDefaultBinding , NamedImports
- Let names be the BoundNames of ImportedDefaultBinding.
- Append to names the elements of the BoundNames of NamedImports.
- Return names.
NamedImports : { }
- Return a new empty List.
ImportsList : ImportsList , ImportSpecifier
- Let names be the BoundNames of ImportsList.
- Append to names the elements of the BoundNames of ImportSpecifier.
- Return names.
ImportSpecifier : IdentifierName as ImportedBinding
- Return the BoundNames of ImportedBinding.
ExportDeclaration : export ExportFromClause FromClause ; export NamedExports ;
- Return a new empty List.
ExportDeclaration : export VariableStatement
- Return the BoundNames of VariableStatement.
ExportDeclaration : export Declaration
- Return the BoundNames of Declaration.
ExportDeclaration : export default HoistableDeclaration
- Let declarationNames be the BoundNames of HoistableDeclaration.
- If declarationNames does not include the element "*default*", append "*default*" to declarationNames.
- Return declarationNames.
ExportDeclaration : export default ClassDeclaration
- Let declarationNames be the BoundNames of ClassDeclaration.
- If declarationNames does not include the element "*default*", append "*default*" to declarationNames.
- Return declarationNames.
ExportDeclaration : export default AssignmentExpression ;
- Return « "*default*" ».
HoistableDeclaration : FunctionDeclaration
- Return FunctionDeclaration.
HoistableDeclaration : GeneratorDeclaration
- Return GeneratorDeclaration.
HoistableDeclaration : AsyncFunctionDeclaration
- Return AsyncFunctionDeclaration.
HoistableDeclaration : AsyncGeneratorDeclaration
- Return AsyncGeneratorDeclaration.
Declaration : ClassDeclaration
- Return ClassDeclaration.
Declaration : LexicalDeclaration
- Return LexicalDeclaration.
LexicalDeclaration : LetOrConst BindingList ;
- Return IsConstantDeclaration of LetOrConst.
LetOrConst : let
- Return false.
LetOrConst : const
- Return true.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
- Return false.
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
- Return false.
ExportDeclaration : export ExportFromClause FromClause ; export NamedExports ; export default AssignmentExpression ;
- Return false.
Note
It is not necessary to treat export default
AssignmentExpression as a constant declaration because there is no syntax that permits assignment to the internal bound name used to reference a module's default object.
Block : { }
- Return a new empty List.
StatementList : StatementList StatementListItem
- Let names be LexicallyDeclaredNames of StatementList.
- Append to names the elements of the LexicallyDeclaredNames of StatementListItem.
- Return names.
- If Statement is Statement : LabelledStatement , return LexicallyDeclaredNames of LabelledStatement.
- Return a new empty List.
StatementListItem : Declaration
- Return the BoundNames of Declaration.
CaseBlock : { }
- Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
- If the first CaseClauses is present, let names be the LexicallyDeclaredNames of the first CaseClauses.
- Else, let names be a new empty List.
- Append to names the elements of the LexicallyDeclaredNames of DefaultClause.
- If the second CaseClauses is not present, return names.
- Return the result of appending to names the elements of the LexicallyDeclaredNames of the second CaseClauses.
CaseClauses : CaseClauses CaseClause
- Let names be LexicallyDeclaredNames of CaseClauses.
- Append to names the elements of the LexicallyDeclaredNames of CaseClause.
- Return names.
CaseClause : case Expression : StatementListopt
- If the StatementList is present, return the LexicallyDeclaredNames of StatementList.
- Return a new empty List.
DefaultClause : default : StatementListopt
- If the StatementList is present, return the LexicallyDeclaredNames of StatementList.
- Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
- Return the LexicallyDeclaredNames of LabelledItem.
- Return a new empty List.
LabelledItem : FunctionDeclaration
- Return BoundNames of FunctionDeclaration.
FunctionStatementList : [empty]
- Return a new empty List.
FunctionStatementList : StatementList
- Return TopLevelLexicallyDeclaredNames of StatementList.
- Return a new empty List.
AsyncConciseBody : ExpressionBody
- Return a new empty List.
- Return TopLevelLexicallyDeclaredNames of StatementList.
Note 1
At the top level of a Script, function declarations are treated like var declarations rather than like lexical declarations.
Note 2
The LexicallyDeclaredNames of a Module includes the names of all of its imported bindings.
ModuleItemList : ModuleItemList ModuleItem
- Let names be LexicallyDeclaredNames of ModuleItemList.
- Append to names the elements of the LexicallyDeclaredNames of ModuleItem.
- Return names.
ModuleItem : ImportDeclaration
- Return the BoundNames of ImportDeclaration.
ModuleItem : ExportDeclaration
- If ExportDeclaration is
export
VariableStatement, return a new empty List. - Return the BoundNames of ExportDeclaration.
ModuleItem : StatementListItem
- Return LexicallyDeclaredNames of StatementListItem.
Note 3
At the top level of a Module, function declarations are treated like lexical declarations rather than like var declarations.
StatementList : StatementList StatementListItem
- Let declarations be LexicallyScopedDeclarations of StatementList.
- Append to declarations the elements of the LexicallyScopedDeclarations of StatementListItem.
- Return declarations.
- If Statement is Statement : LabelledStatement , return LexicallyScopedDeclarations of LabelledStatement.
- Return a new empty List.
StatementListItem : Declaration
- Return a List whose sole element is DeclarationPart of Declaration.
CaseBlock : { }
- Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
- If the first CaseClauses is present, let declarations be the LexicallyScopedDeclarations of the first CaseClauses.
- Else, let declarations be a new empty List.
- Append to declarations the elements of the LexicallyScopedDeclarations of DefaultClause.
- If the second CaseClauses is not present, return declarations.
- Return the result of appending to declarations the elements of the LexicallyScopedDeclarations of the second CaseClauses.
CaseClauses : CaseClauses CaseClause
- Let declarations be LexicallyScopedDeclarations of CaseClauses.
- Append to declarations the elements of the LexicallyScopedDeclarations of CaseClause.
- Return declarations.
CaseClause : case Expression : StatementListopt
- If the StatementList is present, return the LexicallyScopedDeclarations of StatementList.
- Return a new empty List.
DefaultClause : default : StatementListopt
- If the StatementList is present, return the LexicallyScopedDeclarations of StatementList.
- Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
- Return the LexicallyScopedDeclarations of LabelledItem.
- Return a new empty List.
LabelledItem : FunctionDeclaration
- Return a List whose sole element is FunctionDeclaration.
FunctionStatementList : [empty]
- Return a new empty List.
FunctionStatementList : StatementList
- Return the TopLevelLexicallyScopedDeclarations of StatementList.
- Return a new empty List.
AsyncConciseBody : ExpressionBody
- Return a new empty List.
- Return TopLevelLexicallyScopedDeclarations of StatementList.
Module : [empty]
- Return a new empty List.
ModuleItemList : ModuleItemList ModuleItem
- Let declarations be LexicallyScopedDeclarations of ModuleItemList.
- Append to declarations the elements of the LexicallyScopedDeclarations of ModuleItem.
- Return declarations.
ModuleItem : ImportDeclaration
- Return a new empty List.
ExportDeclaration : export ExportFromClause FromClause ; export NamedExports ; export VariableStatement
- Return a new empty List.
ExportDeclaration : export Declaration
- Return a List whose sole element is DeclarationPart of Declaration.
ExportDeclaration : export default HoistableDeclaration
- Return a List whose sole element is DeclarationPart of HoistableDeclaration.
ExportDeclaration : export default ClassDeclaration
- Return a List whose sole element is ClassDeclaration.
ExportDeclaration : export default AssignmentExpression ;
- Return a List whose sole element is this ExportDeclaration.
Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
- Return a new empty List.
Block : { }
- Return a new empty List.
StatementList : StatementList StatementListItem
- Let names be VarDeclaredNames of StatementList.
- Append to names the elements of the VarDeclaredNames of StatementListItem.
- Return names.
StatementListItem : Declaration
- Return a new empty List.
VariableStatement : var VariableDeclarationList ;
- Return BoundNames of VariableDeclarationList.
IfStatement : if ( Expression ) Statement else Statement
- Let names be VarDeclaredNames of the first Statement.
- Append to names the elements of the VarDeclaredNames of the second Statement.
- Return names.
IfStatement : if ( Expression ) Statement
- Return the VarDeclaredNames of Statement.
DoWhileStatement : do Statement while ( Expression ) ;
- Return the VarDeclaredNames of Statement.
WhileStatement : while ( Expression ) Statement
- Return the VarDeclaredNames of Statement.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
- Return the VarDeclaredNames of Statement.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
- Let names be BoundNames of VariableDeclarationList.
- Append to names the elements of the VarDeclaredNames of Statement.
- Return names.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
- Return the VarDeclaredNames of Statement.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
- Return the VarDeclaredNames of Statement.
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
- Let names be the BoundNames of ForBinding.
- Append to names the elements of the VarDeclaredNames of Statement.
- Return names.
Note
This section is extended by Annex B.3.6.
WithStatement : with ( Expression ) Statement
- Return the VarDeclaredNames of Statement.
SwitchStatement : switch ( Expression ) CaseBlock
- Return the VarDeclaredNames of CaseBlock.
CaseBlock : { }
- Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
- If the first CaseClauses is present, let names be the VarDeclaredNames of the first CaseClauses.
- Else, let names be a new empty List.
- Append to names the elements of the VarDeclaredNames of DefaultClause.
- If the second CaseClauses is not present, return names.
- Return the result of appending to names the elements of the VarDeclaredNames of the second CaseClauses.
CaseClauses : CaseClauses CaseClause
- Let names be VarDeclaredNames of CaseClauses.
- Append to names the elements of the VarDeclaredNames of CaseClause.
- Return names.
CaseClause : case Expression : StatementListopt
- If the StatementList is present, return the VarDeclaredNames of StatementList.
- Return a new empty List.
DefaultClause : default : StatementListopt
- If the StatementList is present, return the VarDeclaredNames of StatementList.
- Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
- Return the VarDeclaredNames of LabelledItem.
LabelledItem : FunctionDeclaration
- Return a new empty List.
TryStatement : try Block Catch
- Let names be VarDeclaredNames of Block.
- Append to names the elements of the VarDeclaredNames of Catch.
- Return names.
TryStatement : try Block Finally
- Let names be VarDeclaredNames of Block.
- Append to names the elements of the VarDeclaredNames of Finally.
- Return names.
TryStatement : try Block Catch Finally
- Let names be VarDeclaredNames of Block.
- Append to names the elements of the VarDeclaredNames of Catch.
- Append to names the elements of the VarDeclaredNames of Finally.
- Return names.
Catch : catch ( CatchParameter ) Block
- Return the VarDeclaredNames of Block.
FunctionStatementList : [empty]
- Return a new empty List.
FunctionStatementList : StatementList
- Return TopLevelVarDeclaredNames of StatementList.
- Return a new empty List.
AsyncConciseBody : ExpressionBody
- Return a new empty List.
- Return TopLevelVarDeclaredNames of StatementList.
Module : [empty]
- Return a new empty List.
ModuleItemList : ModuleItemList ModuleItem
- Let names be VarDeclaredNames of ModuleItemList.
- Append to names the elements of the VarDeclaredNames of ModuleItem.
- Return names.
ModuleItem : ImportDeclaration
- Return a new empty List.
ModuleItem : ExportDeclaration
- If ExportDeclaration is
export
VariableStatement, return BoundNames of ExportDeclaration. - Return a new empty List.
Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
- Return a new empty List.
Block : { }
- Return a new empty List.
StatementList : StatementList StatementListItem
- Let declarations be VarScopedDeclarations of StatementList.
- Append to declarations the elements of the VarScopedDeclarations of StatementListItem.
- Return declarations.
StatementListItem : Declaration
- Return a new empty List.
VariableDeclarationList : VariableDeclaration
- Return a List whose sole element is VariableDeclaration.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
- Let declarations be VarScopedDeclarations of VariableDeclarationList.
- Append VariableDeclaration to declarations.
- Return declarations.
IfStatement : if ( Expression ) Statement else Statement
- Let declarations be VarScopedDeclarations of the first Statement.
- Append to declarations the elements of the VarScopedDeclarations of the second Statement.
- Return declarations.
IfStatement : if ( Expression ) Statement
- Return the VarScopedDeclarations of Statement.
DoWhileStatement : do Statement while ( Expression ) ;
- Return the VarScopedDeclarations of Statement.
WhileStatement : while ( Expression ) Statement
- Return the VarScopedDeclarations of Statement.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
- Return the VarScopedDeclarations of Statement.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
- Let declarations be VarScopedDeclarations of VariableDeclarationList.
- Append to declarations the elements of the VarScopedDeclarations of Statement.
- Return declarations.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
- Return the VarScopedDeclarations of Statement.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
- Return the VarScopedDeclarations of Statement.
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
- Let declarations be a List whose sole element is ForBinding.
- Append to declarations the elements of the VarScopedDeclarations of Statement.
- Return declarations.
Note
This section is extended by Annex B.3.6.
WithStatement : with ( Expression ) Statement
- Return the VarScopedDeclarations of Statement.
SwitchStatement : switch ( Expression ) CaseBlock
- Return the VarScopedDeclarations of CaseBlock.
CaseBlock : { }
- Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
- If the first CaseClauses is present, let declarations be the VarScopedDeclarations of the first CaseClauses.
- Else, let declarations be a new empty List.
- Append to declarations the elements of the VarScopedDeclarations of DefaultClause.
- If the second CaseClauses is not present, return declarations.
- Return the result of appending to declarations the elements of the VarScopedDeclarations of the second CaseClauses.
CaseClauses : CaseClauses CaseClause
- Let declarations be VarScopedDeclarations of CaseClauses.
- Append to declarations the elements of the VarScopedDeclarations of CaseClause.
- Return declarations.
CaseClause : case Expression : StatementListopt
- If the StatementList is present, return the VarScopedDeclarations of StatementList.
- Return a new empty List.
DefaultClause : default : StatementListopt
- If the StatementList is present, return the VarScopedDeclarations of StatementList.
- Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
- Return the VarScopedDeclarations of LabelledItem.
LabelledItem : FunctionDeclaration
- Return a new empty List.
TryStatement : try Block Catch
- Let declarations be VarScopedDeclarations of Block.
- Append to declarations the elements of the VarScopedDeclarations of Catch.
- Return declarations.
TryStatement : try Block Finally
- Let declarations be VarScopedDeclarations of Block.
- Append to declarations the elements of the VarScopedDeclarations of Finally.
- Return declarations.
TryStatement : try Block Catch Finally
- Let declarations be VarScopedDeclarations of Block.
- Append to declarations the elements of the VarScopedDeclarations of Catch.
- Append to declarations the elements of the VarScopedDeclarations of Finally.
- Return declarations.
Catch : catch ( CatchParameter ) Block
- Return the VarScopedDeclarations of Block.
FunctionStatementList : [empty]
- Return a new empty List.
FunctionStatementList : StatementList
- Return the TopLevelVarScopedDeclarations of StatementList.
- Return a new empty List.
AsyncConciseBody : ExpressionBody
- Return a new empty List.
- Return TopLevelVarScopedDeclarations of StatementList.
Module : [empty]
- Return a new empty List.
ModuleItemList : ModuleItemList ModuleItem
- Let declarations be VarScopedDeclarations of ModuleItemList.
- Append to declarations the elements of the VarScopedDeclarations of ModuleItem.
- Return declarations.
ModuleItem : ImportDeclaration
- Return a new empty List.
ModuleItem : ExportDeclaration
- If ExportDeclaration is
export
VariableStatement, return VarScopedDeclarations of VariableStatement. - Return a new empty List.
StatementList : StatementList StatementListItem
- Let names be TopLevelLexicallyDeclaredNames of StatementList.
- Append to names the elements of the TopLevelLexicallyDeclaredNames of StatementListItem.
- Return names.
- Return a new empty List.
StatementListItem : Declaration
- If Declaration is Declaration : HoistableDeclaration , then
- Return « ».
- Return the BoundNames of Declaration.
Note
At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.
LabelledStatement : LabelIdentifier : LabelledItem
- Return a new empty List.
Block : { }
- Return a new empty List.
StatementList : StatementList StatementListItem
- Let declarations be TopLevelLexicallyScopedDeclarations of StatementList.
- Append to declarations the elements of the TopLevelLexicallyScopedDeclarations of StatementListItem.
- Return declarations.
- Return a new empty List.
StatementListItem : Declaration
- If Declaration is Declaration : HoistableDeclaration , then
- Return « ».
- Return a List whose sole element is Declaration.
LabelledStatement : LabelIdentifier : LabelledItem
- Return a new empty List.
Block : { }
- Return a new empty List.
StatementList : StatementList StatementListItem
- Let names be TopLevelVarDeclaredNames of StatementList.
- Append to names the elements of the TopLevelVarDeclaredNames of StatementListItem.
- Return names.
StatementListItem : Declaration
- If Declaration is Declaration : HoistableDeclaration , then
- Return the BoundNames of HoistableDeclaration.
- Return a new empty List.
- If Statement is Statement : LabelledStatement , return TopLevelVarDeclaredNames of Statement.
- Return VarDeclaredNames of Statement.
Note
At the top level of a function or script, inner function declarations are treated like var declarations.
LabelledStatement : LabelIdentifier : LabelledItem
- Return the TopLevelVarDeclaredNames of LabelledItem.
- If Statement is Statement : LabelledStatement , return TopLevelVarDeclaredNames of Statement.
- Return VarDeclaredNames of Statement.
LabelledItem : FunctionDeclaration
- Return BoundNames of FunctionDeclaration.
Block : { }
- Return a new empty List.
StatementList : StatementList StatementListItem
- Let declarations be TopLevelVarScopedDeclarations of StatementList.
- Append to declarations the elements of the TopLevelVarScopedDeclarations of StatementListItem.
- Return declarations.
- If Statement is Statement : LabelledStatement , return TopLevelVarScopedDeclarations of Statement.
- Return VarScopedDeclarations of Statement.
StatementListItem : Declaration
- If Declaration is Declaration : HoistableDeclaration , then
- Let declaration be DeclarationPart of HoistableDeclaration.
- Return « declaration ».
- Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
- Return the TopLevelVarScopedDeclarations of LabelledItem.
- If Statement is Statement : LabelledStatement , return TopLevelVarScopedDeclarations of Statement.
- Return VarScopedDeclarations of Statement.
LabelledItem : FunctionDeclaration
- Return a List whose sole element is FunctionDeclaration.
With parameter labelSet.
Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
- Return false.
StatementList : StatementList StatementListItem
- Let hasDuplicates be ContainsDuplicateLabels of StatementList with argument labelSet.
- If hasDuplicates is true, return true.
- Return ContainsDuplicateLabels of StatementListItem with argument labelSet.
IfStatement : if ( Expression ) Statement else Statement
- Let hasDuplicate be ContainsDuplicateLabels of the first Statement with argument labelSet.
- If hasDuplicate is true, return true.
- Return ContainsDuplicateLabels of the second Statement with argument labelSet.
IfStatement : if ( Expression ) Statement
- Return ContainsDuplicateLabels of Statement with argument labelSet.
DoWhileStatement : do Statement while ( Expression ) ;
- Return ContainsDuplicateLabels of Statement with argument labelSet.
WhileStatement : while ( Expression ) Statement
- Return ContainsDuplicateLabels of Statement with argument labelSet.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
- Return ContainsDuplicateLabels of Statement with argument labelSet.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
- Return ContainsDuplicateLabels of Statement with argument labelSet.
Note
This section is extended by Annex B.3.6.
WithStatement : with ( Expression ) Statement
- Return ContainsDuplicateLabels of Statement with argument labelSet.
SwitchStatement : switch ( Expression ) CaseBlock
- Return ContainsDuplicateLabels of CaseBlock with argument labelSet.
CaseBlock : { }
- Return false.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
- If the first CaseClauses is present, then
- Let hasDuplicates be ContainsDuplicateLabels of the first CaseClauses with argument labelSet.
- If hasDuplicates is true, return true.
- Let hasDuplicates be ContainsDuplicateLabels of DefaultClause with argument labelSet.
- If hasDuplicates is true, return true.
- If the second CaseClauses is not present, return false.
- Return ContainsDuplicateLabels of the second CaseClauses with argument labelSet.
CaseClauses : CaseClauses CaseClause
- Let hasDuplicates be ContainsDuplicateLabels of CaseClauses with argument labelSet.
- If hasDuplicates is true, return true.
- Return ContainsDuplicateLabels of CaseClause with argument labelSet.
CaseClause : case Expression : StatementListopt
- If the StatementList is present, return ContainsDuplicateLabels of StatementList with argument labelSet.
- Return false.
DefaultClause : default : StatementListopt
- If the StatementList is present, return ContainsDuplicateLabels of StatementList with argument labelSet.
- Return false.
LabelledStatement : LabelIdentifier : LabelledItem
- Let label be the StringValue of LabelIdentifier.
- If label is an element of labelSet, return true.
- Let newLabelSet be a copy of labelSet with label appended.
- Return ContainsDuplicateLabels of LabelledItem with argument newLabelSet.
LabelledItem : FunctionDeclaration
- Return false.
TryStatement : try Block Catch
- Let hasDuplicates be ContainsDuplicateLabels of Block with argument labelSet.
- If hasDuplicates is true, return true.
- Return ContainsDuplicateLabels of Catch with argument labelSet.
TryStatement : try Block Finally
- Let hasDuplicates be ContainsDuplicateLabels of Block with argument labelSet.
- If hasDuplicates is true, return true.
- Return ContainsDuplicateLabels of Finally with argument labelSet.
TryStatement : try Block Catch Finally
- Let hasDuplicates be ContainsDuplicateLabels of Block with argument labelSet.
- If hasDuplicates is true, return true.
- Let hasDuplicates be ContainsDuplicateLabels of Catch with argument labelSet.
- If hasDuplicates is true, return true.
- Return ContainsDuplicateLabels of Finally with argument labelSet.
Catch : catch ( CatchParameter ) Block
- Return ContainsDuplicateLabels of Block with argument labelSet.
FunctionStatementList : [empty]
- Return false.
ModuleItemList : ModuleItemList ModuleItem
- Let hasDuplicates be ContainsDuplicateLabels of ModuleItemList with argument labelSet.
- If hasDuplicates is true, return true.
- Return ContainsDuplicateLabels of ModuleItem with argument labelSet.
ModuleItem : ImportDeclaration ExportDeclaration
- Return false.
With parameter labelSet.
Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
- Return false.
StatementList : StatementList StatementListItem
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of StatementList with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedBreakTarget of StatementListItem with argument labelSet.
IfStatement : if ( Expression ) Statement else Statement
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of the first Statement with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedBreakTarget of the second Statement with argument labelSet.
IfStatement : if ( Expression ) Statement
- Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
DoWhileStatement : do Statement while ( Expression ) ;
- Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
WhileStatement : while ( Expression ) Statement
- Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
- Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
- Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
Note
This section is extended by Annex B.3.6.
BreakStatement : break ;
- Return false.
BreakStatement : break LabelIdentifier ;
- If the StringValue of LabelIdentifier is not an element of labelSet, return true.
- Return false.
WithStatement : with ( Expression ) Statement
- Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
SwitchStatement : switch ( Expression ) CaseBlock
- Return ContainsUndefinedBreakTarget of CaseBlock with argument labelSet.
CaseBlock : { }
- Return false.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
- If the first CaseClauses is present, then
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of the first CaseClauses with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of DefaultClause with argument labelSet.
- If hasUndefinedLabels is true, return true.
- If the second CaseClauses is not present, return false.
- Return ContainsUndefinedBreakTarget of the second CaseClauses with argument labelSet.
CaseClauses : CaseClauses CaseClause
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of CaseClauses with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedBreakTarget of CaseClause with argument labelSet.
CaseClause : case Expression : StatementListopt
- If the StatementList is present, return ContainsUndefinedBreakTarget of StatementList with argument labelSet.
- Return false.
DefaultClause : default : StatementListopt
- If the StatementList is present, return ContainsUndefinedBreakTarget of StatementList with argument labelSet.
- Return false.
LabelledStatement : LabelIdentifier : LabelledItem
- Let label be the StringValue of LabelIdentifier.
- Let newLabelSet be a copy of labelSet with label appended.
- Return ContainsUndefinedBreakTarget of LabelledItem with argument newLabelSet.
LabelledItem : FunctionDeclaration
- Return false.
TryStatement : try Block Catch
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of Block with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedBreakTarget of Catch with argument labelSet.
TryStatement : try Block Finally
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of Block with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedBreakTarget of Finally with argument labelSet.
TryStatement : try Block Catch Finally
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of Block with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of Catch with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedBreakTarget of Finally with argument labelSet.
Catch : catch ( CatchParameter ) Block
- Return ContainsUndefinedBreakTarget of Block with argument labelSet.
FunctionStatementList : [empty]
- Return false.
ModuleItemList : ModuleItemList ModuleItem
- Let hasUndefinedLabels be ContainsUndefinedBreakTarget of ModuleItemList with argument labelSet.
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedBreakTarget of ModuleItem with argument labelSet.
ModuleItem : ImportDeclaration ExportDeclaration
- Return false.
With parameters iterationSet and labelSet.
Statement : VariableStatement EmptyStatement ExpressionStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
- Return false.
BreakableStatement : IterationStatement
- Let newIterationSet be a copy of iterationSet with all the elements of labelSet appended.
- Return ContainsUndefinedContinueTarget of IterationStatement with arguments newIterationSet and « ».
StatementList : StatementList StatementListItem
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of StatementList with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedContinueTarget of StatementListItem with arguments iterationSet and « ».
IfStatement : if ( Expression ) Statement else Statement
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of the first Statement with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedContinueTarget of the second Statement with arguments iterationSet and « ».
IfStatement : if ( Expression ) Statement
- Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
DoWhileStatement : do Statement while ( Expression ) ;
- Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
WhileStatement : while ( Expression ) Statement
- Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
- Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
- Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
Note
This section is extended by Annex B.3.6.
ContinueStatement : continue ;
- Return false.
ContinueStatement : continue LabelIdentifier ;
- If the StringValue of LabelIdentifier is not an element of iterationSet, return true.
- Return false.
WithStatement : with ( Expression ) Statement
- Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
SwitchStatement : switch ( Expression ) CaseBlock
- Return ContainsUndefinedContinueTarget of CaseBlock with arguments iterationSet and « ».
CaseBlock : { }
- Return false.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
- If the first CaseClauses is present, then
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of the first CaseClauses with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of DefaultClause with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- If the second CaseClauses is not present, return false.
- Return ContainsUndefinedContinueTarget of the second CaseClauses with arguments iterationSet and « ».
CaseClauses : CaseClauses CaseClause
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of CaseClauses with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedContinueTarget of CaseClause with arguments iterationSet and « ».
CaseClause : case Expression : StatementListopt
- If the StatementList is present, return ContainsUndefinedContinueTarget of StatementList with arguments iterationSet and « ».
- Return false.
DefaultClause : default : StatementListopt
- If the StatementList is present, return ContainsUndefinedContinueTarget of StatementList with arguments iterationSet and « ».
- Return false.
LabelledStatement : LabelIdentifier : LabelledItem
- Let label be the StringValue of LabelIdentifier.
- Let newLabelSet be a copy of labelSet with label appended.
- Return ContainsUndefinedContinueTarget of LabelledItem with arguments iterationSet and newLabelSet.
LabelledItem : FunctionDeclaration
- Return false.
TryStatement : try Block Catch
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of Block with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedContinueTarget of Catch with arguments iterationSet and « ».
TryStatement : try Block Finally
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of Block with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedContinueTarget of Finally with arguments iterationSet and « ».
TryStatement : try Block Catch Finally
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of Block with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of Catch with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedContinueTarget of Finally with arguments iterationSet and « ».
Catch : catch ( CatchParameter ) Block
- Return ContainsUndefinedContinueTarget of Block with arguments iterationSet and « ».
FunctionStatementList : [empty]
- Return false.
ModuleItemList : ModuleItemList ModuleItem
- Let hasUndefinedLabels be ContainsUndefinedContinueTarget of ModuleItemList with arguments iterationSet and « ».
- If hasUndefinedLabels is true, return true.
- Return ContainsUndefinedContinueTarget of ModuleItem with arguments iterationSet and « ».
ModuleItem : ImportDeclaration ExportDeclaration
- Return false.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
- Let expr be CoveredParenthesizedExpression of CoverParenthesizedExpressionAndArrowParameterList.
- If IsFunctionDefinition of expr is false, return false.
- Return HasName of expr.
FunctionExpression : function ( FormalParameters ) { FunctionBody } GeneratorExpression : function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody } ArrowFunction : ArrowParameters => ConciseBody AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody ClassExpression : class ClassTail
- Return false.
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody } GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } ClassExpression : class BindingIdentifier ClassTail
- Return true.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
- Let expr be CoveredParenthesizedExpression of CoverParenthesizedExpressionAndArrowParameterList.
- Return IsFunctionDefinition of expr.
PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral RegularExpressionLiteral TemplateLiteral MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression AwaitExpression ExponentiationExpression : UpdateExpression ** ExponentiationExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression LogicalANDExpression : LogicalANDExpression && BitwiseORExpression LogicalORExpression : LogicalORExpression || LogicalANDExpression CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression AssignmentExpression : YieldExpression LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression Expression : Expression , AssignmentExpression
- Return false.
AssignmentExpression : ArrowFunction AsyncArrowFunction FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody } ClassExpression : class BindingIdentifieropt ClassTail
- Return true.
The abstract operation IsAnonymousFunctionDefinition takes argument expr (a Parse Node for AssignmentExpression or a Parse Node for Initializer). It determines if its argument is a function definition that does not bind a name. It performs the following steps when called:
- If IsFunctionDefinition of expr is false, return false.
- Let hasName be HasName of expr.
- If hasName is true, return false.
- Return true.
PrimaryExpression : IdentifierReference
- Return true.
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CoverParenthesizedExpressionAndArrowParameterList MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
- Return false.
With parameter name.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
- Let expr be CoveredParenthesizedExpression of CoverParenthesizedExpressionAndArrowParameterList.
- Return the result of performing NamedEvaluation for expr with argument name.
ParenthesizedExpression : ( Expression )
- Assert: IsAnonymousFunctionDefinition(Expression) is true.
- Return the result of performing NamedEvaluation for Expression with argument name.
FunctionExpression : function ( FormalParameters ) { FunctionBody }
- Return InstantiateOrdinaryFunctionExpression of FunctionExpression with argument name.
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
- Return InstantiateGeneratorFunctionExpression of GeneratorExpression with argument name.
AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
- Return InstantiateAsyncGeneratorFunctionExpression of AsyncGeneratorExpression with argument name.
AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
- Return InstantiateAsyncFunctionExpression of AsyncFunctionExpression with argument name.
ArrowFunction : ArrowParameters => ConciseBody
- Return InstantiateArrowFunctionExpression of ArrowFunction with argument name.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
- Return InstantiateAsyncArrowFunctionExpression of AsyncArrowFunction with argument name.
ClassExpression : class ClassTail
- Let value be the result of ClassDefinitionEvaluation of ClassTail with arguments undefined and name.
- ReturnIfAbrupt(value).
- Set value.[[SourceText]] to the source text matched by ClassExpression.
- Return value.
With parameter symbol.
Every grammar production alternative in this specification which is not listed below implicitly has the following default definition of Contains:
- For each child node child of this Parse Node, do
- If child is an instance of symbol, return true.
- If child is an instance of a nonterminal, then
- Let contained be the result of child Contains symbol.
- If contained is true, return true.
- Return false.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
- Return false.
Note 1
Static semantic rules that depend upon substructure generally do not look into function definitions.
ClassTail : ClassHeritageopt { ClassBody }
- If symbol is ClassBody, return true.
- If symbol is ClassHeritage, then
- If ClassHeritage is present, return true; otherwise return false.
- Let inHeritage be ClassHeritage Contains symbol.
- If inHeritage is true, return true.
- Return the result of ComputedPropertyContains for ClassBody with argument symbol.
Note 2
Static semantic rules that depend upon substructure generally do not look into class bodies except for PropertyNames.
ArrowFunction : ArrowParameters => ConciseBody
- If symbol is not one of NewTarget, SuperProperty, SuperCall,
super
orthis
, return false. - If ArrowParameters Contains symbol is true, return true.
- Return ConciseBody Contains symbol.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
- Let formals be CoveredFormalsList of CoverParenthesizedExpressionAndArrowParameterList.
- Return formals Contains symbol.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
- If symbol is not one of NewTarget, SuperProperty, SuperCall,
super
, orthis
, return false. - Return AsyncConciseBody Contains symbol.
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
- If symbol is not one of NewTarget, SuperProperty, SuperCall,
super
, orthis
, return false. - Let head be CoveredAsyncArrowHead of CoverCallExpressionAndAsyncArrowHead.
- If head Contains symbol is true, return true.
- Return AsyncConciseBody Contains symbol.
Note 3
Contains is used to detect new.target
, this
, and super
usage within an ArrowFunction or AsyncArrowFunction.
PropertyDefinition : MethodDefinition
- If symbol is MethodDefinition, return true.
- Return the result of ComputedPropertyContains for MethodDefinition with argument symbol.
LiteralPropertyName : IdentifierName
- Return false.
MemberExpression : MemberExpression . IdentifierName
- If MemberExpression Contains symbol is true, return true.
- Return false.
SuperProperty : super . IdentifierName
- If symbol is the ReservedWord
super
, return true. - Return false.
CallExpression : CallExpression . IdentifierName
- If CallExpression Contains symbol is true, return true.
- Return false.
OptionalChain : ?. IdentifierName
- Return false.
OptionalChain : OptionalChain . IdentifierName
- If OptionalChain Contains symbol is true, return true.
- Return false.
With parameter symbol.
PropertyName : LiteralPropertyName
- Return false.
PropertyName : ComputedPropertyName
- Return the result of ComputedPropertyName Contains symbol.
MethodDefinition : PropertyName ( UniqueFormalParameters ) { FunctionBody } get PropertyName ( ) { FunctionBody } set PropertyName ( PropertySetParameterList ) { FunctionBody }
- Return the result of ComputedPropertyContains for PropertyName with argument symbol.
GeneratorMethod : * PropertyName ( UniqueFormalParameters ) { GeneratorBody }
- Return the result of ComputedPropertyContains for PropertyName with argument symbol.
AsyncGeneratorMethod : async * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody }
- Return the result of ComputedPropertyContains for PropertyName with argument symbol.
ClassElementList : ClassElementList ClassElement
- Let inList be ComputedPropertyContains of ClassElementList with argument symbol.
- If inList is true, return true.
- Return the result of ComputedPropertyContains for ClassElement with argument symbol.
ClassElement : ;
- Return false.
AsyncMethod : async PropertyName ( UniqueFormalParameters ) { AsyncFunctionBody }
- Return the result of ComputedPropertyContains for PropertyName with argument symbol.
These operations are used in multiple places throughout the specification.
With parameter scope.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody }
- Return ? InstantiateOrdinaryFunctionObject of FunctionDeclaration with argument scope.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody }
- Return ? InstantiateGeneratorFunctionObject of GeneratorDeclaration with argument scope.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody }
- Return ? InstantiateAsyncGeneratorFunctionObject of AsyncGeneratorDeclaration with argument scope.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
- Return ? InstantiateAsyncFunctionObject of AsyncFunctionDeclaration with argument scope.
With parameters value and environment.
Note
undefined is passed for environment to indicate that a PutValue operation should be used to assign the initialization value. This is the case for var
statements and formal parameter lists of some non-strict functions (See 10.2.10). In those cases a lexical binding is hoisted and preinitialized prior to evaluation of its initializer.
BindingIdentifier : Identifier
- Let name be StringValue of Identifier.
- Return ? InitializeBoundName(name, value, environment).
BindingIdentifier : yield
- Return ? InitializeBoundName("yield", value, environment).
BindingIdentifier : await
- Return ? InitializeBoundName("await", value, environment).
BindingPattern : ObjectBindingPattern
- Perform ? RequireObjectCoercible(value).
- Return the result of performing BindingInitialization for ObjectBindingPattern using value and environment as arguments.
BindingPattern : ArrayBindingPattern
- Let iteratorRecord be ? GetIterator(value).
- Let result be IteratorBindingInitialization of ArrayBindingPattern with arguments iteratorRecord and environment.
- If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
- Return result.
ObjectBindingPattern : { }
- Return NormalCompletion(empty).
ObjectBindingPattern : { BindingPropertyList } { BindingPropertyList , }
- Perform ? PropertyBindingInitialization for BindingPropertyList using value and environment as the arguments.
- Return NormalCompletion(empty).
ObjectBindingPattern : { BindingRestProperty }
- Let excludedNames be a new empty List.
- Return the result of performing RestBindingInitialization of BindingRestProperty with value, environment, and excludedNames as the arguments.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
- Let excludedNames be ? PropertyBindingInitialization of BindingPropertyList with arguments value and environment.
- Return the result of performing RestBindingInitialization of BindingRestProperty with arguments value, environment, and excludedNames.
The abstract operation InitializeBoundName takes arguments name, value, and environment. It performs the following steps when called:
- Assert: Type(name) is String.
- If environment is not undefined, then
- Perform environment.InitializeBinding(name, value).
- Return NormalCompletion(undefined).
- Else,
- Let lhs be ResolveBinding(name).
- Return ? PutValue(lhs, value).
With parameters iteratorRecord and environment.
Note
When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialization value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.
ArrayBindingPattern : [ ]
- Return NormalCompletion(empty).
ArrayBindingPattern : [ Elision ]
- Return the result of performing IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
- If Elision is present, then
- Perform ? IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
- Return the result of performing IteratorBindingInitialization for BindingRestElement with iteratorRecord and environment as arguments.
ArrayBindingPattern : [ BindingElementList , Elision ]
- Perform ? IteratorBindingInitialization for BindingElementList with iteratorRecord and environment as arguments.
- Return the result of performing IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
- Perform ? IteratorBindingInitialization for BindingElementList with iteratorRecord and environment as arguments.
- If Elision is present, then
- Perform ? IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
- Return the result of performing IteratorBindingInitialization for BindingRestElement with iteratorRecord and environment as arguments.
BindingElementList : BindingElementList , BindingElisionElement
- Perform ? IteratorBindingInitialization for BindingElementList with iteratorRecord and environment as arguments.
- Return the result of performing IteratorBindingInitialization for BindingElisionElement using iteratorRecord and environment as arguments.
BindingElisionElement : Elision BindingElement
- Perform ? IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
- Return the result of performing IteratorBindingInitialization of BindingElement with iteratorRecord and environment as the arguments.
SingleNameBinding : BindingIdentifier Initializeropt
- Let bindingId be StringValue of BindingIdentifier.
- Let lhs be ? ResolveBinding(bindingId, environment).
- If iteratorRecord.[[Done]] is false, then
- Let next be IteratorStep(iteratorRecord).
- If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(next).
- If next is false, set iteratorRecord.[[Done]] to true.
- Else,
- Let v be IteratorValue(next).
- If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(v).
- If iteratorRecord.[[Done]] is true, let v be undefined.
- If Initializer is present and v is undefined, then
- If IsAnonymousFunctionDefinition(Initializer) is true, then
- Set v to the result of performing NamedEvaluation for Initializer with argument bindingId.
- Else,
- Let defaultValue be the result of evaluating Initializer.
- Set v to ? GetValue(defaultValue).
- If IsAnonymousFunctionDefinition(Initializer) is true, then
- If environment is undefined, return ? PutValue(lhs, v).
- Return InitializeReferencedBinding(lhs, v).
BindingElement : BindingPattern Initializeropt
- If iteratorRecord.[[Done]] is false, then
- Let next be IteratorStep(iteratorRecord).
- If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(next).
- If next is false, set iteratorRecord.[[Done]] to true.
- Else,
- Let v be IteratorValue(next).
- If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(v).
- If iteratorRecord.[[Done]] is true, let v be undefined.
- If Initializer is present and v is undefined, then
- Let defaultValue be the result of evaluating Initializer.
- Set v to ? GetValue(defaultValue).
- Return the result of performing BindingInitialization of BindingPattern with v and environment as the arguments.
BindingRestElement : ... BindingIdentifier
- Let lhs be ? ResolveBinding(StringValue of BindingIdentifier, environment).
- Let A be ! ArrayCreate(0).
- Let n be 0.
- Repeat,
- If iteratorRecord.[[Done]] is false, then
- Let next be IteratorStep(iteratorRecord).
- If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(next).
- If next is false, set iteratorRecord.[[Done]] to true.
- If iteratorRecord.[[Done]] is true, then
- If environment is undefined, return ? PutValue(lhs, A).
- Return InitializeReferencedBinding(lhs, A).
- Let nextValue be IteratorValue(next).
- If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(nextValue).
- Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), nextValue).
- Set n to n + 1.
- If iteratorRecord.[[Done]] is false, then
BindingRestElement : ... BindingPattern
- Let A be ! ArrayCreate(0).
- Let n be 0.
- Repeat,
- If iteratorRecord.[[Done]] is false, then
- Let next be IteratorStep(iteratorRecord).
- If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(next).
- If next is false, set iteratorRecord.[[Done]] to true.
- If iteratorRecord.[[Done]] is true, then
- Return the result of performing BindingInitialization of BindingPattern with A and environment as the arguments.
- Let nextValue be IteratorValue(next).
- If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(nextValue).
- Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), nextValue).
- Set n to n + 1.
- If iteratorRecord.[[Done]] is false, then
FormalParameters : [empty]
- Return NormalCompletion(empty).
FormalParameters : FormalParameterList , FunctionRestParameter
- Perform ? IteratorBindingInitialization for FormalParameterList using iteratorRecord and environment as the arguments.
- Return the result of performing IteratorBindingInitialization for FunctionRestParameter using iteratorRecord and environment as the arguments.
FormalParameterList : FormalParameterList , FormalParameter
- Perform ? IteratorBindingInitialization for FormalParameterList using iteratorRecord and environment as the arguments.
- Return the result of performing IteratorBindingInitialization for FormalParameter using iteratorRecord and environment as the arguments.
ArrowParameters : BindingIdentifier
- Assert: iteratorRecord.[[Done]] is false.
- Let next be IteratorStep(iteratorRecord).
- If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(next).
- If next is false, set iteratorRecord.[[Done]] to true.
- Else,
- Let v be IteratorValue(next).
- If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(v).
- If iteratorRecord.[[Done]] is true, let v be undefined.
- Return the result of performing BindingInitialization for BindingIdentifier using v and environment as the arguments.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
- Let formals be CoveredFormalsList of CoverParenthesizedExpressionAndArrowParameterList.
- Return IteratorBindingInitialization of formals with arguments iteratorRecord and environment.
AsyncArrowBindingIdentifier : BindingIdentifier
- Assert: iteratorRecord.[[Done]] is false.
- Let next be IteratorStep(iteratorRecord).
- If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(next).
- If next is false, set iteratorRecord.[[Done]] to true.
- Else,
- Let v be IteratorValue(next).
- If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
- ReturnIfAbrupt(v).
- If iteratorRecord.[[Done]] is true, let v be undefined.
- Return the result of performing BindingInitialization for BindingIdentifier using v and environment as the arguments.
IdentifierReference : Identifier
- If this IdentifierReference is contained in strict mode code and StringValue of Identifier is "eval" or "arguments", return invalid.
- Return simple.
IdentifierReference : yield await CallExpression : CallExpression [ Expression ] CallExpression . IdentifierName MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty
- Return simple.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
- Let expr be CoveredParenthesizedExpression of CoverParenthesizedExpressionAndArrowParameterList.
- Return AssignmentTargetType of expr.
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CallExpression : CoverCallExpressionAndAsyncArrowHead SuperCall ImportCall CallExpression Arguments CallExpression TemplateLiteral NewExpression : new NewExpression MemberExpression : MemberExpression TemplateLiteral new MemberExpression Arguments NewTarget : new . target ImportMeta : import . meta LeftHandSideExpression : OptionalExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression AwaitExpression ExponentiationExpression : UpdateExpression ** ExponentiationExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression LogicalANDExpression : LogicalANDExpression && BitwiseORExpression LogicalORExpression : LogicalORExpression || LogicalANDExpression CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression Expression : Expression , AssignmentExpression
- Return invalid.
PropertyDefinition : IdentifierReference
- Return StringValue of IdentifierReference.
PropertyDefinition : ... AssignmentExpression
- Return empty.
PropertyDefinition : PropertyName : AssignmentExpression
- Return PropName of PropertyName.
LiteralPropertyName : IdentifierName
- Return StringValue of IdentifierName.
LiteralPropertyName : StringLiteral
- Return the SV of StringLiteral.
LiteralPropertyName : NumericLiteral
- Let nbr be the NumericValue of NumericLiteral.
- Return ! ToString(nbr).
ComputedPropertyName : [ AssignmentExpression ]
- Return empty.
MethodDefinition : PropertyName ( UniqueFormalParameters ) { FunctionBody } get PropertyName ( ) { FunctionBody } set PropertyName ( PropertySetParameterList ) { FunctionBody }
- Return PropName of PropertyName.
GeneratorMethod : * PropertyName ( UniqueFormalParameters ) { GeneratorBody }
- Return PropName of PropertyName.
AsyncGeneratorMethod : async * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody }
- Return PropName of PropertyName.
ClassElement : ;
- Return empty.
AsyncMethod : async PropertyName ( UniqueFormalParameters ) { AsyncFunctionBody }
- Return PropName of PropertyName.
Environment Record is a specification type used to define the association of Identifiers 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 a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement. 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 either null 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 a FunctionDeclaration contains two nested FunctionDeclarations 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.
Environment Records can be thought of as existing in a simple object-oriented hierarchy where Environment Record is an abstract class with three concrete subclasses: declarative Environment Record, object Environment Record, and global Environment Record. Function Environment Records and module Environment Records are subclasses of declarative Environment Record.
-
Environment Record (abstract)
-
A declarative Environment Record is used to define the effect of ECMAScript language syntactic elements such as FunctionDeclarations, VariableDeclarations, and Catch clauses that directly associate identifier bindings with ECMAScript language values.
-
A function Environment Record corresponds to the invocation of an ECMAScript function object, and contains bindings for the top-level declarations within that function. It may establish a new
this
binding. It also captures the state necessary to supportsuper
method invocations. -
A module Environment Record contains the bindings for the top-level declarations of a Module. It also contains the bindings that are explicitly imported by the Module. Its [[OuterEnv]] is a global Environment Record.
-
-
An object Environment Record is used to define the effect of ECMAScript elements such as WithStatement that associate identifier bindings with the properties of some object.
-
A global Environment Record is used for Script global declarations. It does not have an outer environment; its [[OuterEnv]] is null. It may be prepopulated with identifier bindings and it includes an associated global object whose properties provide some of the global environment's identifier bindings. As ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be modified.
-
The Environment Record abstract class includes the abstract specification methods defined in Table 17. These abstract methods have distinct concrete algorithms for each of the concrete subclasses.
Table 17: Abstract Methods of Environment Records
Method | Purpose |
---|---|
HasBinding(N) | Determine if an Environment Record has a binding for the String value N. Return true if it does and false if it does not. |
CreateMutableBinding(N, D) | Create a new but uninitialized mutable binding in an Environment Record. The String value N is the text of the bound name. If the Boolean argument D is true the binding may be subsequently deleted. |
CreateImmutableBinding(N, S) | Create a new but uninitialized immutable binding in an Environment Record. The String value N is the text of the bound name. If S is true 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 an Environment Record. The String value N is the text of the bound name. V is the value for the binding and is a value of any ECMAScript language type. |
SetMutableBinding(N, V, S) | Set the value of an already existing mutable binding in an Environment Record. The String value N is the text of the bound name. V is the value for the binding and may be a value of any ECMAScript language type. S is a Boolean flag. If S is true and the binding cannot be set throw a TypeError exception. |
GetBindingValue(N, S) | Returns the value of an already existing binding from an Environment Record. The String value N is the text of the bound name. S is used to identify references originating in strict mode code or that otherwise require strict mode reference semantics. If S is true and the binding does not exist throw a ReferenceError exception. If the binding exists but is uninitialized a ReferenceError is thrown, regardless of the value of S. |
DeleteBinding(N) | Delete a binding from an Environment Record. The String value N is the text of the bound name. If a binding for N exists, remove the binding and return true. If the binding exists but cannot be removed return false. If the binding does not exist return true. |
HasThisBinding() | Determine if an Environment Record establishes a this binding. Return true if it does and false if it does not. |
HasSuperBinding() | Determine if an Environment Record establishes a super method binding. Return true if it does and false if it does not. |
WithBaseObject() | If this Environment Record is associated with a with statement, return the with object. Otherwise, return undefined. |
Each declarative 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.
The behaviour of the concrete specification methods for declarative Environment Records is defined by the following algorithms.
The HasBinding concrete method of a declarative Environment Record envRec takes argument N (a String). It determines if the argument identifier is one of the identifiers bound by the record. It performs the following steps when called:
- If envRec has a binding for the name that is the value of N, return true.
- Return false.
The CreateMutableBinding concrete method of a declarative Environment Record envRec takes arguments N (a String) and D (a Boolean). It creates a new mutable binding for the name N that is uninitialized. A binding must not already exist in this Environment Record for N. If D has the value true, 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 for N.
- Create a mutable binding in envRec for N and record that it is uninitialized. If D is true, record that the newly created binding may be deleted by a subsequent DeleteBinding call.
- Return NormalCompletion(empty).
The CreateImmutableBinding concrete method of a declarative Environment Record envRec takes arguments N (a String) and S (a Boolean). It creates a new immutable binding for the name N that is uninitialized. A binding must not already exist in this Environment Record for N. If S has the value true, the new binding is marked as a strict binding. It performs the following steps when called:
- Assert: envRec does not already have a binding for N.
- Create an immutable binding in envRec for N and record that it is uninitialized. If S is true, record that the newly created binding is a strict binding.
- Return NormalCompletion(empty).
The InitializeBinding concrete method of a declarative Environment Record envRec takes arguments N (a String) and V (an ECMAScript language value). It is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialized binding for N must already exist. It performs the following steps when called:
- Assert: envRec must have an uninitialized binding for N.
- Set the bound value for N in envRec to V.
- Record that the binding for N in envRec has been initialized.
- Return NormalCompletion(empty).
The SetMutableBinding concrete method of a declarative Environment Record envRec takes arguments N (a String), V (an ECMAScript language value), and S (a Boolean). It attempts to change the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. A binding for N normally already exists, but in rare cases it may not. If the binding is an immutable binding, a TypeError is thrown if S is true. It performs the following steps when called:
- If envRec does not have a binding for N, then
- If S is true, throw a ReferenceError exception.
- Perform envRec.CreateMutableBinding(N, true).
- Perform envRec.InitializeBinding(N, V).
- Return NormalCompletion(empty).
- If the binding for N in envRec is a strict binding, set S to true.
- If the binding for N in envRec has not yet been initialized, throw a ReferenceError exception.
- Else if the binding for N in envRec is a mutable binding, change its bound value to V.
- Else,
- Assert: This is an attempt to change the value of an immutable binding.
- If S is true, throw a TypeError exception.
- Return NormalCompletion(empty).
Note
An example of ECMAScript code that results in a missing binding at step 1 is:
function f() { eval("var x; x = (delete x, 0);"); }
The GetBindingValue concrete method of a declarative Environment Record envRec takes arguments N (a String) and S (a Boolean). It returns the value of its bound identifier whose name is the value of the argument N. If the binding exists but is uninitialized a ReferenceError is thrown, regardless of the value of S. It performs the following steps when called:
- Assert: envRec has a binding for N.
- If the binding for N in envRec is an uninitialized binding, throw a ReferenceError exception.
- Return the value currently bound to N in envRec.
The DeleteBinding concrete method of a declarative Environment Record envRec takes argument N (a String). It can only delete bindings that have been explicitly designated as being subject to deletion. It performs the following steps when called:
- Assert: envRec has a binding for the name that is the value of N.
- If the binding for N in envRec cannot be deleted, return false.
- Remove the binding for N from envRec.
- Return true.
The HasThisBinding concrete method of a declarative Environment Record envRec takes no arguments. It performs the following steps when called:
- Return false.
Note
A regular declarative Environment Record (i.e., one that is neither a function Environment Record nor a module Environment Record) does not provide a this
binding.
The HasSuperBinding concrete method of a declarative Environment Record envRec takes no arguments. It performs the following steps when called:
- Return false.
Note
A regular declarative Environment Record (i.e., one that is neither a function Environment Record nor a module Environment Record) does not provide a super
binding.
The WithBaseObject concrete method of a declarative Environment Record envRec takes no arguments. It performs the following steps when called:
- Return undefined.
Each object Environment Record is associated with an object called its binding object. An object Environment Record binds the set of string identifier names that directly correspond to the property names of its binding object. Property keys that are not strings in the form of an IdentifierName 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 has the value false. Immutable bindings do not exist for object Environment Records.
Object Environment Records created for with
statements (14.11) can provide their binding object as an implicit this value for use in function calls. The capability is controlled by a withEnvironment Boolean value that is associated with each object Environment Record. By default, the value of withEnvironment is false for any object Environment Record.
The behaviour of the concrete specification methods for object Environment Records is defined by the following algorithms.
The HasBinding concrete method of an object Environment Record envRec takes argument N (a String). It determines if its associated binding object has a property whose name is the value of the argument N. It performs the following steps when called:
- Let bindings be the binding object for envRec.
- Let foundBinding be ? HasProperty(bindings, N).
- If foundBinding is false, return false.
- If the withEnvironment flag of envRec is false, return true.
- Let unscopables be ? Get(bindings, @@unscopables).
- If Type(unscopables) is Object, then
- Return true.
The CreateMutableBinding concrete method of an object Environment Record envRec takes arguments N (a String) and D (a Boolean). It creates in an Environment Record's associated binding object a property whose name is the String value and initializes it to the value undefined. If D has the value true, the new property's [[Configurable]] attribute is set to true; otherwise it is set to false. It performs the following steps when called:
- Let bindings be the binding object for envRec.
- Return ? DefinePropertyOrThrow(bindings, N, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }).
Note
Normally envRec will not have a binding for N but if it does, the semantics of DefinePropertyOrThrow may result in an existing binding being replaced or shadowed or cause an abrupt completion to be returned.
The CreateImmutableBinding concrete method of an object Environment Record is never used within this specification.
The InitializeBinding concrete method of an object Environment Record envRec takes arguments N (a String) and V (an ECMAScript language value). It is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. It performs the following steps when called:
- Return ? envRec.SetMutableBinding(N, V, false).
Note
In this specification, all uses of CreateMutableBinding for object 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 in object Environment Records.
The SetMutableBinding concrete method of an object Environment Record envRec takes arguments N (a String), V (an ECMAScript language value), and S (a Boolean). It attempts to set the value of the Environment Record's associated binding object's property whose name is the value of the argument N to the value of argument V. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by S. It performs the following steps when called:
- Let bindings be the binding object for envRec.
- Let stillExists be ? HasProperty(bindings, N).
- If stillExists is false and S is true, throw a ReferenceError exception.
- Return ? Set(bindings, N, V, S).
The GetBindingValue concrete method of an object Environment Record envRec takes arguments N (a String) and S (a Boolean). It returns the value of its associated binding object's property whose name is the String value of the argument identifier N. The property should already exist but if it does not the result depends upon S. It performs the following steps when called:
- Let bindings be the binding object for envRec.
- Let value be ? HasProperty(bindings, N).
- If value is false, then
- If S is false, return the value undefined; otherwise throw a ReferenceError exception.
- Return ? Get(bindings, N).
The DeleteBinding concrete method of an object Environment Record envRec takes argument N (a String). It can only delete bindings that correspond to properties of the environment object whose [[Configurable]] attribute have the value true. It performs the following steps when called:
- Let bindings be the binding object for envRec.
- Return ? bindings.[[Delete]](N).
The HasThisBinding concrete method of an object Environment Record envRec takes no arguments. It performs the following steps when called:
- Return false.
Note
Object Environment Records do not provide a this
binding.
The HasSuperBinding concrete method of an object Environment Record envRec takes no arguments. It performs the following steps when called:
- Return false.
Note
Object Environment Records do not provide a super
binding.
The WithBaseObject concrete method of an object Environment Record envRec takes no arguments. It performs the following steps when called:
- If the withEnvironment flag of envRec is true, return the binding object for envRec.
- Otherwise, return undefined.
A function Environment Record is a declarative Environment Record that is used to represent the top-level scope of a function and, if the function is not an ArrowFunction, provides a this
binding. If a function is not an ArrowFunction function and references super
, its function Environment Record also contains the state that is used to perform super
method invocations from within the function.
Function Environment Records have the additional state fields listed in Table 18.
Table 18: Additional Fields of Function Environment Records
Field Name | Value | Meaning |
---|---|---|
[[ThisValue]] | Any | This is the this value used for this invocation of the function. |
[[ThisBindingStatus]] | lexical | initialized |
[[FunctionObject]] | Object | The function object whose invocation caused this Environment Record to be created. |
[[NewTarget]] | Object | undefined |
Function Environment Records support all of the declarative Environment Record methods listed in Table 17 and share the same specifications for all of those methods except for HasThisBinding and HasSuperBinding. In addition, function Environment Records support the methods listed in Table 19:
Table 19: Additional Methods of Function Environment Records
Method | Purpose |
---|---|
BindThisValue(V) | Set the [[ThisValue]] and record that it has been initialized. |
GetThisBinding() | Return the value of this Environment Record's this binding. Throws a ReferenceError if the this binding has not been initialized. |
GetSuperBase() | Return the object that is the base for super property accesses bound in this Environment Record. The value undefined indicates that super property accesses will produce runtime errors. |
The behaviour of the additional concrete specification methods for function Environment Records is defined by the following algorithms:
The BindThisValue concrete method of a function Environment Record envRec takes argument V (an ECMAScript language value). It performs the following steps when called:
- Assert: envRec.[[ThisBindingStatus]] is not lexical.
- If envRec.[[ThisBindingStatus]] is initialized, throw a ReferenceError exception.
- Set envRec.[[ThisValue]] to V.
- Set envRec.[[ThisBindingStatus]] to initialized.
- Return V.
The HasThisBinding concrete method of a function Environment Record envRec takes no arguments. It performs the following steps when called:
- If envRec.[[ThisBindingStatus]] is lexical, return false; otherwise, return true.
The HasSuperBinding concrete method of a function Environment Record envRec takes no arguments. It performs the following steps when called:
- If envRec.[[ThisBindingStatus]] is lexical, return false.
- If envRec.[[FunctionObject]].[[HomeObject]] has the value undefined, return false; otherwise, return true.
The GetThisBinding concrete method of a function Environment Record envRec takes no arguments. It performs the following steps when called:
- Assert: envRec.[[ThisBindingStatus]] is not lexical.
- If envRec.[[ThisBindingStatus]] is uninitialized, throw a ReferenceError exception.
- Return envRec.[[ThisValue]].
The GetSuperBase concrete method of a function Environment Record envRec takes no arguments. It performs the following steps when called:
- Let home be envRec.[[FunctionObject]].[[HomeObject]].
- If home has the value undefined, return undefined.
- Assert: Type(home) is Object.
- Return ? home.[[GetPrototypeOf]]().
A global Environment Record is used to represent the outer most scope that is shared by all of the ECMAScript Script elements that are processed in a common realm. A global Environment Record provides the bindings for built-in globals (clause 19), properties of the global object, and for all top-level declarations (8.1.9, 8.1.11) that occur within a Script.
A global Environment Record is logically a single record but it is specified as a composite encapsulating an object Environment Record and a declarative Environment Record. The object Environment Record has as its base object the global object of the associated Realm Record. This global object is the value returned by the global Environment Record's GetThisBinding concrete method. The object Environment Record component of a global Environment Record contains the bindings for all built-in globals (clause 19) and all bindings introduced by a FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, or VariableStatement contained in global code. The bindings for all other ECMAScript declarations in global code are contained in the declarative Environment Record component of the global Environment Record.
Properties may be created directly on a global object. Hence, the object Environment Record component of a global Environment Record may contain both bindings created explicitly by FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, or VariableDeclaration declarations and bindings created implicitly as properties of the global object. In order to identify which bindings were explicitly created using declarations, a global Environment Record maintains a list of the names bound using its CreateGlobalVarBinding and CreateGlobalFunctionBinding concrete methods.
Global Environment Records have the additional fields listed in Table 20 and the additional methods listed in Table 21.
Table 20: Additional Fields of Global Environment Records
Field Name | Value | Meaning |
---|---|---|
[[ObjectRecord]] | Object Environment Record | Binding object is the global object. It contains global built-in bindings as well as FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, and VariableDeclaration bindings in global code for the associated realm. |
[[GlobalThisValue]] | Object | The value returned by this in global scope. Hosts may provide any ECMAScript Object value. |
[[DeclarativeRecord]] | Declarative Environment Record | Contains bindings for all declarations in global code for the associated realm code except for FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, and VariableDeclaration bindings. |
[[VarNames]] | List of String | The string names bound by FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, and VariableDeclaration declarations in global code for the associated realm. |
Table 21: Additional Methods of Global Environment Records
Method | Purpose |
---|---|
GetThisBinding() | Return the value of this Environment Record's this binding. |
HasVarDeclaration (N) | Determines if the argument identifier has a binding in this Environment Record that was created using a VariableDeclaration, FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, or AsyncGeneratorDeclaration. |
HasLexicalDeclaration (N) | Determines if the argument identifier has a binding in this Environment Record that was created using a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. |
HasRestrictedGlobalProperty (N) | Determines if the argument is the name of a global object property that may not be shadowed by a global lexical binding. |
CanDeclareGlobalVar (N) | Determines if a corresponding CreateGlobalVarBinding call would succeed if called for the same argument N. |
CanDeclareGlobalFunction (N) | Determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N. |
CreateGlobalVarBinding(N, D) | Used to create and initialize to undefined a global var binding in the [[ObjectRecord]] component of a global Environment Record. The binding will be a mutable binding. The corresponding global object property will have attribute values appropriate for a var . The String value N is the bound name. If D is true the binding may be deleted. Logically equivalent to CreateMutableBinding followed by a SetMutableBinding but it allows var declarations to receive special treatment. |
CreateGlobalFunctionBinding(N, V, D) | Create and initialize a global function binding in the [[ObjectRecord]] component of a global Environment Record. The binding will be a mutable binding. The corresponding global object property will have attribute values appropriate for a function . The String value N is the bound name. V is the initialization value. If the Boolean argument D is true the binding may be deleted. Logically equivalent to CreateMutableBinding followed by a SetMutableBinding but it allows function declarations to receive special treatment. |
The behaviour of the concrete specification methods for global Environment Records is defined by the following algorithms.
The HasBinding concrete method of a global Environment Record envRec takes argument N (a String). It determines if the argument identifier is one of the identifiers bound by the record. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- If DclRec.HasBinding(N) is true, return true.
- Let ObjRec be envRec.[[ObjectRecord]].
- Return ? ObjRec.HasBinding(N).
The CreateMutableBinding concrete method of a global Environment Record envRec takes arguments N (a String) and D (a Boolean). It creates a new mutable binding for the name N that is uninitialized. The binding is created in the associated DeclarativeRecord. A binding for N must not already exist in the DeclarativeRecord. If D has the value true, the new binding is marked as being subject to deletion. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- If DclRec.HasBinding(N) is true, throw a TypeError exception.
- Return DclRec.CreateMutableBinding(N, D).
The CreateImmutableBinding concrete method of a global Environment Record envRec takes arguments N (a String) and S (a Boolean). It creates a new immutable binding for the name N that is uninitialized. A binding must not already exist in this Environment Record for N. If S has the value true, the new binding is marked as a strict binding. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- If DclRec.HasBinding(N) is true, throw a TypeError exception.
- Return DclRec.CreateImmutableBinding(N, S).
The InitializeBinding concrete method of a global Environment Record envRec takes arguments N (a String) and V (an ECMAScript language value). It is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialized binding for N must already exist. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- If DclRec.HasBinding(N) is true, then
- Return DclRec.InitializeBinding(N, V).
- Assert: If the binding exists, it must be in the object Environment Record.
- Let ObjRec be envRec.[[ObjectRecord]].
- Return ? ObjRec.InitializeBinding(N, V).
The SetMutableBinding concrete method of a global Environment Record envRec takes arguments N (a String), V (an ECMAScript language value), and S (a Boolean). It attempts to change the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. If the binding is an immutable binding, a TypeError is thrown if S is true. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by S. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- If DclRec.HasBinding(N) is true, then
- Return DclRec.SetMutableBinding(N, V, S).
- Let ObjRec be envRec.[[ObjectRecord]].
- Return ? ObjRec.SetMutableBinding(N, V, S).
The GetBindingValue concrete method of a global Environment Record envRec takes arguments N (a String) and S (a Boolean). It returns the value of its bound identifier whose name is the value of the argument N. If the binding is an uninitialized binding throw a ReferenceError exception. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by S. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- If DclRec.HasBinding(N) is true, then
- Return DclRec.GetBindingValue(N, S).
- Let ObjRec be envRec.[[ObjectRecord]].
- Return ? ObjRec.GetBindingValue(N, S).
The DeleteBinding concrete method of a global Environment Record envRec takes argument N (a String). It can only delete bindings that have been explicitly designated as being subject to deletion. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- If DclRec.HasBinding(N) is true, then
- Return DclRec.DeleteBinding(N).
- Let ObjRec be envRec.[[ObjectRecord]].
- Let globalObject be the binding object for ObjRec.
- Let existingProp be ? HasOwnProperty(globalObject, N).
- If existingProp is true, then
- Let status be ? ObjRec.DeleteBinding(N).
- If status is true, then
- Let varNames be envRec.[[VarNames]].
- If N is an element of varNames, remove that element from the varNames.
- Return status.
- Return true.
The HasThisBinding concrete method of a global Environment Record envRec takes no arguments. It performs the following steps when called:
- Return true.
Note
Global Environment Records always provide a this
binding.
The HasSuperBinding concrete method of a global Environment Record envRec takes no arguments. It performs the following steps when called:
- Return false.
Note
Global Environment Records do not provide a super
binding.
The WithBaseObject concrete method of a global Environment Record envRec takes no arguments. It performs the following steps when called:
- Return undefined.
The GetThisBinding concrete method of a global Environment Record envRec takes no arguments. It performs the following steps when called:
- Return envRec.[[GlobalThisValue]].
The HasVarDeclaration concrete method of a global Environment Record envRec takes argument N (a String). It determines if the argument identifier has a binding in this record that was created using a VariableStatement or a FunctionDeclaration. It performs the following steps when called:
- Let varDeclaredNames be envRec.[[VarNames]].
- If varDeclaredNames contains N, return true.
- Return false.
The HasLexicalDeclaration concrete method of a global Environment Record envRec takes argument N (a String). It determines if the argument identifier has a binding in this record that was created using a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. It performs the following steps when called:
- Let DclRec be envRec.[[DeclarativeRecord]].
- Return DclRec.HasBinding(N).
The HasRestrictedGlobalProperty concrete method of a global Environment Record envRec takes argument N (a String). It determines if the argument identifier is the name of a property of the global object that must not be shadowed by a global lexical binding. It performs the following steps when called:
- Let ObjRec be envRec.[[ObjectRecord]].
- Let globalObject be the binding object for ObjRec.
- Let existingProp be ? globalObject.[[GetOwnProperty]](N).
- If existingProp is undefined, return false.
- If existingProp.[[Configurable]] is true, return false.
- Return true.
Note
Properties may exist upon a global 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 the global object. The global property "undefined" is an example of such a property.
The CanDeclareGlobalVar concrete method of a global Environment Record envRec takes argument N (a String). It determines if a corresponding CreateGlobalVarBinding call would succeed if called for the same argument N. Redundant var declarations and var declarations for pre-existing global object properties are allowed. It performs the following steps when called:
- Let ObjRec be envRec.[[ObjectRecord]].
- Let globalObject be the binding object for ObjRec.
- Let hasProperty be ? HasOwnProperty(globalObject, N).
- If hasProperty is true, return true.
- Return ? IsExtensible(globalObject).
The CanDeclareGlobalFunction concrete method of a global Environment Record envRec takes argument N (a String). It determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N. It performs the following steps when called:
- Let ObjRec be envRec.[[ObjectRecord]].
- Let globalObject be the binding object for ObjRec.
- Let existingProp be ? globalObject.[[GetOwnProperty]](N).
- If existingProp is undefined, return ? IsExtensible(globalObject).
- If existingProp.[[Configurable]] is true, return true.
- If IsDataDescriptor(existingProp) is true and existingProp has attribute values { [[Writable]]: true, [[Enumerable]]: true }, return true.
- Return false.
The CreateGlobalVarBinding concrete method of a global Environment Record envRec takes arguments N (a String) and D (a Boolean). It creates and initializes a mutable binding in the associated object Environment Record and records the bound name in the associated [[VarNames]] List. If a binding already exists, it is reused and assumed to be initialized. It performs the following steps when called:
- Let ObjRec be envRec.[[ObjectRecord]].
- Let globalObject be the binding object for ObjRec.
- Let hasProperty be ? HasOwnProperty(globalObject, N).
- Let extensible be ? IsExtensible(globalObject).
- If hasProperty is false and extensible is true, then
- Perform ? ObjRec.CreateMutableBinding(N, D).
- Perform ? ObjRec.InitializeBinding(N, undefined).
- Let varDeclaredNames be envRec.[[VarNames]].
- If varDeclaredNames does not contain N, then
- Append N to varDeclaredNames.
- Return NormalCompletion(empty).
The CreateGlobalFunctionBinding concrete method of a global Environment Record envRec takes arguments N (a String), V (an ECMAScript language value), and D (a Boolean). It creates and initializes a mutable binding in the associated object Environment Record and records the bound name in the associated [[VarNames]] List. If a binding already exists, it is replaced. It performs the following steps when called:
- Let ObjRec be envRec.[[ObjectRecord]].
- Let globalObject be the binding object for ObjRec.
- Let existingProp be ? globalObject.[[GetOwnProperty]](N).
- If existingProp is undefined or existingProp.[[Configurable]] is true, then
- Let desc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }.
- Else,
- Let desc be the PropertyDescriptor { [[Value]]: V }.
- Perform ? DefinePropertyOrThrow(globalObject, N, desc).
- Perform ? Set(globalObject, N, V, false).
- Let varDeclaredNames be envRec.[[VarNames]].
- If varDeclaredNames does not contain N, then
- Append N to varDeclaredNames.
- Return NormalCompletion(empty).
Note
Global function declarations are always represented as own properties of the global object. If possible, an existing own property is reconfigured to have a standard set of attribute values. Step 7 is equivalent to what calling the InitializeBinding concrete method would do and if globalObject is a Proxy will produce the same sequence of Proxy trap calls.
A module Environment Record is a declarative Environment Record that is used to represent the outer scope of an ECMAScript Module. 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 another Environment Record.
Module Environment Records support all of the declarative Environment Record methods listed in Table 17 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 in Table 22:
Table 22: Additional Methods of Module Environment Records
Method | Purpose |
---|---|
CreateImportBinding(N, M, N2) | Create an immutable indirect binding in a module Environment Record. The String value N is the text of the bound name. M is a Module Record, and N2 is a binding that exists in M's module Environment Record. |
GetThisBinding() | Return the value of this Environment Record's this binding. |
The behaviour of the additional concrete specification methods for module Environment Records are defined by the following algorithms:
The GetBindingValue concrete method of a module Environment Record envRec takes arguments N (a String) and S (a Boolean). It returns the value of its bound identifier whose name is the value of the argument N. However, if the binding is an indirect binding the value of the target binding is returned. If the binding exists but is uninitialized a ReferenceError is thrown. It performs the following steps when called:
- Assert: S is true.
- Assert: envRec has a binding for N.
- If the binding for N is an indirect binding, then
- Let M and N2 be the indirection values provided when this binding for N was created.
- Let targetEnv be M.[[Environment]].
- If targetEnv is undefined, throw a ReferenceError exception.
- Return ? targetEnv.GetBindingValue(N2, true).
- If the binding for N in envRec is an uninitialized binding, throw a ReferenceError exception.
- Return the value currently bound to N in envRec.
Note
S will always be true because a Module is always strict mode code.
The DeleteBinding concrete method of a module Environment Record is never used within this specification.
Note
Module Environment Records are only used within strict code and an early error rule prevents the delete operator, in strict code, from being applied to a Reference Record that would resolve to a module Environment Record binding. See 13.5.1.1.
The HasThisBinding concrete method of a module Environment Record envRec takes no arguments. It performs the following steps when called:
- Return true.
Note
Module Environment Records always provide a this
binding.
The GetThisBinding concrete method of a module Environment Record envRec takes no arguments. It performs the following steps when called:
- Return undefined.
The CreateImportBinding concrete method of a module Environment Record envRec takes arguments N (a String), M (a Module Record), and N2 (a String). It creates a new initialized immutable indirect binding for the name N. A binding must not already exist in this Environment Record for N. N2 is the name of a binding that exists in M's module 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 for N.
- Assert: M is a Module Record.
- Assert: When M.[[Environment]] is instantiated it will have a direct binding for N2.
- Create an immutable indirect binding in envRec for N that references M and N2 as its target binding and record that the binding is initialized.
- Return NormalCompletion(empty).
The following abstract operations are used in this specification to operate upon Environment Records:
The abstract operation GetIdentifierReference takes arguments env (an Environment Record or null), name (a String), and strict (a Boolean). It performs the following steps when called:
- If env is the value null, then
- Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
- Let exists be ? env.HasBinding(name).
- If exists is true, then
- Return the Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
- Else,
- Let outer be env.[[OuterEnv]].
- Return ? GetIdentifierReference(outer, name, strict).
The abstract operation NewDeclarativeEnvironment takes argument E (an Environment Record). It performs the following steps when called:
- Let env be a new declarative Environment Record containing no bindings.
- Set env.[[OuterEnv]] to E.
- Return env.
The abstract operation NewObjectEnvironment takes arguments O (an Object) and E (an Environment Record). It performs the following steps when called:
- Let env be a new object Environment Record containing O as the binding object.
- Set env.[[OuterEnv]] to E.
- Return env.
The abstract operation NewFunctionEnvironment takes arguments F and newTarget. It performs the following steps when called:
- Assert: F is an ECMAScript function.
- Assert: Type(newTarget) is Undefined or Object.
- Let env be a new function Environment Record containing no bindings.
- Set env.[[FunctionObject]] to F.
- If F.[[ThisMode]] is lexical, set env.[[ThisBindingStatus]] to lexical.
- Else, set env.[[ThisBindingStatus]] to uninitialized.
- Set env.[[NewTarget]] to newTarget.
- Set env.[[OuterEnv]] to F.[[Environment]].
- Return env.
The abstract operation NewGlobalEnvironment takes arguments G and thisValue. It performs the following steps when called:
- Let objRec be a new object Environment Record containing G as the binding object.
- Let dclRec be a new declarative Environment Record containing no bindings.
- Let env be a new global Environment Record.
- Set env.[[ObjectRecord]] to objRec.
- Set env.[[GlobalThisValue]] to thisValue.
- Set env.[[DeclarativeRecord]] to dclRec.
- Set env.[[VarNames]] to a new empty List.
- Set env.[[OuterEnv]] to null.
- Return env.
The abstract operation NewModuleEnvironment takes argument E (an Environment Record). It performs the following steps when called:
- Let env be a new module Environment Record containing no bindings.
- Set env.[[OuterEnv]] to E.
- Return env.
Before it is evaluated, all ECMAScript code must be associated with a realm. Conceptually, a realm 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.
A realm is represented in this specification as a Realm Record with the fields specified in Table 23:
Table 23: Realm Record Fields
Field Name | Value | Meaning |
---|---|---|
[[Intrinsics]] | Record whose field names are intrinsic keys and whose values are objects | The intrinsic values used by code associated with this realm |
[[GlobalObject]] | Object | The global object for this realm |
[[GlobalEnv]] | global Environment Record | The global environment for this realm |
[[TemplateMap]] | A List of Record { [[Site]]: Parse Node, [[Array]]: Object }. | |
Template objects are canonicalized separately for each realm using its Realm Record's [[TemplateMap]]. Each [[Site]] value is a Parse Node that is a TemplateLiteral. The associated [[Array]] value is the corresponding template object that is passed to a tag function. |
Note
Once a
becomes unreachable, the corresponding [[Array]] is also unreachable, and it would be unobservable if an implementation removed the pair from the [[TemplateMap]] list.
| | [[HostDefined]] | Any, default value is undefined. | Field reserved for use by hosts that need to associate additional information with a Realm Record. |
The abstract operation CreateRealm takes no arguments. It performs the following steps when called:
- Let realmRec be a new Realm Record.
- Perform CreateIntrinsics(realmRec).
- Set realmRec.[[GlobalObject]] to undefined.
- Set realmRec.[[GlobalEnv]] to undefined.
- Set realmRec.[[TemplateMap]] to a new empty List.
- Return realmRec.
The abstract operation CreateIntrinsics takes argument realmRec. It performs the following steps when called:
- Let intrinsics be a new Record.
- Set realmRec.[[Intrinsics]] to intrinsics.
- Set fields of intrinsics with the values listed in Table 8. 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 clauses 19 through 28. All object property values are newly created object values. All values that are built-in function objects are created by performing CreateBuiltinFunction(steps, length, name, slots, realmRec, prototype) where steps 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'slength
property, slots is a list of the names, if any, of the function's specified internal slots, and prototype 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. - Perform AddRestrictedFunctionProperties(intrinsics.[[%Function.prototype%]], realmRec).
- Return intrinsics.
The abstract operation SetRealmGlobalObject takes arguments realmRec, globalObj, and thisValue. It performs the following steps when called:
- If globalObj is undefined, then
- Let intrinsics be realmRec.[[Intrinsics]].
- Set globalObj to ! OrdinaryObjectCreate(intrinsics.[[%Object.prototype%]]).
- Assert: Type(globalObj) is Object.
- If thisValue is undefined, set thisValue to globalObj.
- Set realmRec.[[GlobalObject]] to globalObj.
- Let newGlobalEnv be NewGlobalEnvironment(globalObj, thisValue).
- Set realmRec.[[GlobalEnv]] to newGlobalEnv.
- Return realmRec.
The abstract operation SetDefaultGlobalBindings takes argument realmRec. It performs the following steps when called:
- Let global be realmRec.[[GlobalObject]].
- For each property of the Global Object specified in clause 19, do
- Let name be the String value of the property name.
- Let desc be the fully populated data Property Descriptor for the property, containing the specified attributes for the property. For properties listed in 19.2, 19.3, or 19.4 the value of the [[Value]] attribute is the corresponding intrinsic object from realmRec.
- Perform ? DefinePropertyOrThrow(global, name, desc).
- Return global.
An execution 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 per agent that is actually executing code. This is known as the agent's running execution context. All references to the running execution context in this specification denote the running execution context of the surrounding agent.
The execution context stack is used to track execution contexts. The running 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 currently running 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 the running 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 in Table 24.
Table 24: 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 this execution context. |
Function | If this execution context is evaluating the code of a function object, then the value of this component is that function object. If the context is evaluating the code of a Script or Module, the value is null. |
Realm | The Realm Record from which associated code accesses ECMAScript resources. |
ScriptOrModule | The Module Record or Script Record from which associated code originates. If there is no originating script or module, as is the case for the original execution context created in InitializeHostDefinedRealm, the value is null. |
Evaluation of code by the running execution context may be suspended at various points defined within this specification. Once the running execution context has been suspended a different execution context may become the running execution context and commence evaluating its code. At some later time a suspended execution context may again become the running execution context and continue evaluating its code at the point where it had previously been suspended. Transition of the running 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 the running execution context.
The value of the Realm component of the running execution context is also called the current Realm Record. The value of the Function component of the running execution context is also called the active function object.
Execution contexts for ECMAScript code have the additional state components listed in Table 25.
Table 25: Additional State Components for ECMAScript Code Execution Contexts
Component | Purpose |
---|---|
LexicalEnvironment | Identifies the Environment Record used to resolve identifier references made by code within this execution context. |
VariableEnvironment | Identifies the Environment Record that holds bindings created by VariableStatements within this execution context. |
The LexicalEnvironment and VariableEnvironment components of an execution context are always Environment Records.
Execution contexts representing the evaluation of generator objects have the additional state components listed in Table 26.
Table 26: Additional State Components for Generator Execution Contexts
Component | Purpose |
---|---|
Generator | The generator object that this execution context is evaluating. |
In most situations only the running execution context (the top of the execution 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 the running 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.
The abstract operation GetActiveScriptOrModule takes no arguments. It is used to determine the running script or module, based on the running execution context. It performs the following steps when called:
- If the execution context stack is empty, return null.
- Let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is not null.
- If no such execution context exists, return null. Otherwise, return ec's ScriptOrModule.
The abstract operation ResolveBinding takes argument name (a String) and optional argument env (an Environment Record). It is used to determine the binding of name. env can be used to explicitly provide the Environment Record that is to be searched for the binding. It performs the following steps when called:
- If env is not present or if env is undefined, then
- Set env to the running execution context's LexicalEnvironment.
- Assert: env is an Environment Record.
- If the code matching the syntactic production that is being evaluated is contained in strict mode code, let strict be true; else let strict be false.
- Return ? GetIdentifierReference(env, name, strict).
Note
The result of ResolveBinding is always a Reference Record whose [[ReferencedName]] field is name.
The abstract operation GetThisEnvironment takes no arguments. It finds the Environment Record that currently supplies the binding of the keyword this
. It performs the following steps when called:
- Let env be the running execution context's LexicalEnvironment.
- Repeat,
- Let exists be env.HasThisBinding().
- If exists is true, return env.
- Let outer be env.[[OuterEnv]].
- Assert: outer is not null.
- Set env to outer.
Note
The loop in step 2 will always terminate because the list of environments always ends with the global environment which has a this
binding.
The abstract operation ResolveThisBinding takes no arguments. It determines the binding of the keyword this
using the LexicalEnvironment of the running execution context. It performs the following steps when called:
- Let envRec be GetThisEnvironment().
- Return ? envRec.GetThisBinding().
The abstract operation GetNewTarget takes no arguments. It determines the NewTarget value using the LexicalEnvironment of the running execution context. It performs the following steps when called:
- Let envRec be GetThisEnvironment().
- Assert: envRec has a [[NewTarget]] field.
- Return envRec.[[NewTarget]].
The abstract operation GetGlobalObject takes no arguments. It returns the global object used by the currently running execution context. It performs the following steps when called:
- Let currentRealm be the current Realm Record.
- Return currentRealm.[[GlobalObject]].
A Job is an Abstract Closure with no parameters that initiates an ECMAScript computation when no other ECMAScript computation is currently in progress.
Jobs are scheduled for execution by ECMAScript host environments. This specification describes the host hook HostEnqueuePromiseJob to schedule one kind of job; hosts may define additional abstract operations which schedule jobs. Such operations accept a Job Abstract Closure as the parameter and schedule it to be performed at some future time. Their implementations must conform to the following requirements:
- At some future point in time, when there is no running execution context and the execution context stack is empty, the implementation must:
- Perform any host-defined preparation steps.
- Invoke the Job Abstract Closure.
- Perform any host-defined cleanup steps, after which the execution context stack must be empty.
- Only one Job may be actively undergoing evaluation at any point in time.
- Once evaluation of a Job starts, it must run to completion before evaluation of any other Job starts.
- The Abstract Closure must return a normal completion, implementing its own handling of errors.
Note 1
environments are not required to treat Jobs uniformly with respect to scheduling. For example, web browsers and Node.js treat Promise-handling Jobs as a higher priority than other work; future features may add Jobs that are not treated at such a high priority.
At any particular time, scriptOrModule (a Script Record, a Module Record, or null) is the active script or module if all of the following conditions are true:
- GetActiveScriptOrModule() is scriptOrModule.
- If scriptOrModule is a Script Record or Module Record, let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is scriptOrModule. The Realm component of ec is scriptOrModule.[[Realm]].
At any particular time, an execution is prepared to evaluate ECMAScript code if all of the following conditions are true:
- The execution context stack is not empty.
- The Realm component of the topmost execution context on the execution context stack is a Realm Record.
Note 2
Host environments may prepare an execution to evaluate code by pushing execution contexts onto the execution context stack. The specific steps are implementation-defined.
The specific choice of Realm is up to the host environment. This initial execution context and Realm is only in use before any callback function is invoked. When a callback function related to a Job, like a Promise handler, is invoked, the invocation pushes its own execution context and Realm.
Particular kinds of Jobs have additional conformance requirements.
A JobCallback Record is a Record value used to store a function object and a host-defined value. Function objects that are invoked via a Job enqueued by the host may have additional host-defined context. To propagate the state, Job Abstract Closures should not capture and call function objects directly. Instead, use HostMakeJobCallback and HostCallJobCallback.
Note
The WHATWG HTML specification (https://html.spec.whatwg.org/), for example, uses the host-defined value to propagate the incumbent settings object for Promise callbacks.
JobCallback Records have the fields listed in Table 27.
Table 27: JobCallback Record Fields
Field Name | Value | Meaning |
---|---|---|
[[Callback]] | A function object | The function to invoke when the Job is invoked. |
[[HostDefined]] | Any, default value is empty. | Field reserved for use by hosts. |
The host-defined abstract operation HostMakeJobCallback takes argument callback (a function object).
The implementation of HostMakeJobCallback must conform to the following requirements:
- It must always complete normally (i.e., not return an abrupt completion).
- It must always return a JobCallback Record whose [[Callback]] field is callback.
The default implementation of HostMakeJobCallback performs the following steps when called:
- Assert: IsCallable(callback) is true.
- Return the JobCallback Record { [[Callback]]: callback, [[HostDefined]]: empty }.
ECMAScript hosts 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 on thenAction
at the time of invoking Promise.prototype.then
, not at the time of scheduling the reaction Job.
The host-defined abstract operation HostCallJobCallback takes arguments jobCallback (a JobCallback Record), V (an ECMAScript language value), and argumentsList (a List of ECMAScript language values).
The implementation of HostCallJobCallback must conform to the following requirements:
- It must always perform and return the result of Call(jobCallback.[[Callback]], V, argumentsList).
Note
This requirement means that hosts cannot change the [[Call]] behaviour of function objects defined in this specification.
The default implementation of HostCallJobCallback performs the following steps when called:
- Assert: IsCallable(jobCallback.[[Callback]]) is true.
- Return ? Call(jobCallback.[[Callback]], V, argumentsList).
ECMAScript hosts that are not web browsers must use the default implementation of HostCallJobCallback.
The host-defined abstract operation HostEnqueuePromiseJob takes arguments job (a Job Abstract Closure) and realm (a Realm Record or null). It schedules job to be performed at some future time. The Abstract 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.
The implementation of HostEnqueuePromiseJob must conform to the requirements in 9.4 as well as the following:
- If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation.
- Let scriptOrModule be GetActiveScriptOrModule() at the time HostEnqueuePromiseJob is invoked. If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that scriptOrModule is the active script or module at the time of job's invocation.
- Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.
Note
The realm for Jobs returned by NewPromiseResolveThenableJob is usually the result of calling GetFunctionRealm on the then function object. The realm for Jobs returned by NewPromiseReactionJob is usually the result of calling GetFunctionRealm on the handler if the handler is not undefined. If the handler is undefined, realm is null. For both kinds of Jobs, when GetFunctionRealm completes abnormally (i.e. called on a revoked Proxy), realm is the current Realm at the time of the GetFunctionRealm call. When the realm is null, no user ECMAScript code will be evaluated and no new ECMAScript objects (e.g. Error objects) will be created. The WHATWG HTML specification (https://html.spec.whatwg.org/), for example, uses realm to check for the ability to run script and for the entry concept.
The abstract operation InitializeHostDefinedRealm takes no arguments. It performs the following steps when called:
- Let realm be CreateRealm().
- Let newContext be a new execution context.
- Set the Function of newContext to null.
- Set the Realm of newContext to realm.
- Set the ScriptOrModule of newContext to null.
- Push newContext onto the execution context stack; newContext is now the running execution context.
- If the host requires use of an exotic object to serve as realm's global object, let global be such an object created in a host-defined manner. Otherwise, let global be undefined, indicating that an ordinary object should be created as the global object.
- If the host requires that the
this
binding in realm's global scope return an object other than the global object, let thisValue be such an object created in a host-defined manner. Otherwise, let thisValue be undefined, indicating that realm's globalthis
binding should be the global object. - Perform SetRealmGlobalObject(realm, global, thisValue).
- Let globalObj be ? SetDefaultGlobalBindings(realm).
- Create any host-defined global object properties on globalObj.
- Return NormalCompletion(empty).
An agent comprises a set of ECMAScript execution contexts, an execution context stack, a running execution context, an Agent Record, and an executing thread. Except for the executing thread, the constituents of an agent belong exclusively to that agent.
An agent's executing thread executes a job on the agent's execution contexts independently of other agents, except that an executing thread may be used as the executing thread by multiple agents, provided none of the agents sharing the thread have an Agent Record whose [[CanBlock]] property is true.
Note 1
Some web browsers share a single executing thread across multiple unrelated tabs of a browser window, for example.
While an agent's executing thread executes jobs, the agent is the surrounding agent for the code in those jobs. The code uses the surrounding agent to access the specification level execution objects held within the agent: the running execution context, the execution context stack, and the Agent Record's fields.
Table 28: Agent Record Fields
Field Name | Value | Meaning |
---|---|---|
[[LittleEndian]] | Boolean | The default value computed for the isLittleEndian parameter when it is needed by the algorithms GetValueFromBuffer and SetValueInBuffer. The choice is implementation-defined and should be the alternative that is most efficient for the implementation. Once the value has been observed it cannot change. |
[[CanBlock]] | Boolean | Determines whether the agent can block or not. |
[[Signifier]] | Any globally-unique value | Uniquely identifies the agent within its agent cluster. |
[[IsLockFree1]] | Boolean | true if atomic operations on one-byte values are lock-free, false otherwise. |
[[IsLockFree2]] | Boolean | true if atomic operations on two-byte values are lock-free, false otherwise. |
[[IsLockFree8]] | Boolean | true if atomic operations on eight-byte values are lock-free, false otherwise. |
[[CandidateExecution]] | A candidate execution Record | See the memory model. |
[[KeptAlive]] | List of objects | Initially a new empty List, representing the list of objects to be kept alive until the end of the current Job |
Once the values of [[Signifier]], [[IsLockFree1]], and [[IsLockFree2]] have been observed by any agent in the agent 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]] property: 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 size n is lock-free does not imply anything about the (perceived) atomicity of non-atomic accesses of size n, specifically, non-atomic accesses may still be performed as a sequence of several separate memory accesses. See ReadSharedMemory and WriteSharedMemory for details.
Note 3
An agent is a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation.
The abstract operation AgentSignifier takes no arguments. It performs the following steps when called:
- Let AR be the Agent Record of the surrounding agent.
- Return AR.[[Signifier]].
The abstract operation AgentCanSuspend takes no arguments. It performs the following steps when called:
- Let AR be the Agent Record of the surrounding agent.
- Return AR.[[CanBlock]].
Note
In some environments it may not be reasonable for a given agent 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.
An agent cluster is a maximal set of agents that can communicate by operating on shared memory.
Note 1
Programs within different agents may share memory by unspecified means. At a minimum, the backing memory for SharedArrayBuffer objects can be shared among the agents in the cluster.
There may be agents that can communicate by message passing that cannot share memory; they are never in the same agent cluster.
Every agent belongs to exactly one agent cluster.
Note 2
The agents in a cluster need not all be alive at some particular point in time. If agent A creates another agent B, after which A terminates and B creates agent C, the three agents are in the same cluster if A could share some memory with B and B could share some memory with C.
All agents within a cluster must have the same value for the [[LittleEndian]] property in their respective Agent Records.
Note 3
If different agents within an agent cluster have different values of [[LittleEndian]] it becomes hard to use shared memory for multi-byte data.
All agents within a cluster must have the same values for the [[IsLockFree1]] property in their respective Agent Records; similarly for the [[IsLockFree2]] property.
All agents within a cluster must have different values for the [[Signifier]] property in their respective Agent Records.
An embedding may deactivate (stop forward progress) or activate (resume forward progress) an agent without the agent's knowledge or cooperation. If the embedding does so, it must not leave some agents in the cluster active while other agents in the cluster are deactivated indefinitely.
Note 4
The purpose of the preceding restriction is to avoid a situation where an agent deadlocks or starves because another agent 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 between agents that don't belong to the same suspend/wake collective within the embedding.
An embedding may terminate an agent without any of the agent's cluster's other agents' prior knowledge or cooperation. If an agent is terminated not by programmatic action of its own or of another agent in the cluster but by forces external to the cluster, then the embedding must choose one of two strategies: Either terminate all the agents in the cluster, or provide reliable APIs that allow the agents 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 the agent that was terminated.
Note 5
Examples of that type of termination are: operating systems or users terminating agents that are running in separate processes; the embedding itself terminating an agent that is running in-process with the other agents when per-agent resource accounting indicates that the agent is runaway.
Prior to any evaluation of any ECMAScript code by any agent in a cluster, the [[CandidateExecution]] field of the Agent Record for all agents in the cluster is set to the initial candidate execution. The initial candidate execution is an empty candidate execution whose [[EventsRecords]] field is a List containing, for each agent, an Agent Events Record whose [[AgentSignifier]] field is that agent's signifier, and whose [[EventList]] and [[AgentSynchronizesWith]] fields are empty Lists.
Note 6
All agents in an agent cluster share the same candidate execution in its Agent Record's [[CandidateExecution]] field. The candidate execution is a specification mechanism used by the memory model.
Note 7
An agent cluster is a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation.
For an agent to make forward progress is for it to perform an evaluation step according to this specification.
An agent becomes blocked when its running execution context waits synchronously and indefinitely for an external event. Only agents whose Agent Record's [[CanBlock]] property is true can become blocked in this sense. An unblocked agent is one that is not blocked.
Implementations must ensure that:
- every unblocked agent with a dedicated executing thread eventually makes forward progress
- in a set of agents that share an executing thread, one agent eventually makes forward progress
- an agent does not cause another agent to become blocked except via explicit APIs that provide blocking.
Note
This, along with the liveness guarantee in the memory model, ensures that all SeqCst writes eventually become observable to all agents.
This specification does not make any guarantees that any object will be garbage collected. Objects which are not live 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 of WeakRef and FinalizationRegistry objects is based on two operations which happen at particular points in time:
- When
WeakRef.prototype.deref
is called, the referent (if undefined is not returned) is kept alive so that subsequent, synchronous accesses also return the object. This list is reset when synchronous work is done using the ClearKeptObjects abstract operation. - When an object which is registered with a FinalizationRegistry becomes unreachable, a call of the FinalizationRegistry's cleanup callback may eventually be made, after synchronous ECMAScript execution completes. The FinalizationRegistry cleanup is performed with the CleanupFinalizationRegistry abstract operation.
Neither of these actions (ClearKeptObjects or CleanupFinalizationRegistry) may interrupt synchronous ECMAScript execution. Because hosts may assemble longer, synchronous ECMAScript execution runs, this specification defers the scheduling of ClearKeptObjects and CleanupFinalizationRegistry to the host environment.
Some ECMAScript implementations include garbage collector implementations which run in the background, including when ECMAScript is idle. Letting the host environment schedule CleanupFinalizationRegistry allows it to resume ECMAScript execution in order to run finalizer work, which may free up held values, reducing overall memory usage.
For some set of objects S, a hypothetical WeakRef-oblivious execution with respect to S is an execution whereby the abstract operation WeakRefDeref of a WeakRef whose referent is an element of S always returns undefined.
Note 1
-obliviousness, together with liveness, capture two notions. One, that a
itself does not keep an object alive. Two, that cycles in liveness does not imply that an object is live. To be concrete, if determining obj's liveness depends on determining the liveness of another
referent, obj2, obj2's liveness cannot assume obj's liveness, which would be circular reasoning.
Note 2
-obliviousness is defined on sets of objects instead of individual objects to account for cycles. If it were defined on individual objects, then an object in a cycle will be considered live even though its Object value is only observed via WeakRefs of other objects in the cycle.
Note 3
Colloquially, we say that an individual object is live if every set of objects containing it is live.
At any point during evaluation, a set of objects S is considered live if either of the following conditions is met:
- Any element in S is included in any agent's [[KeptAlive]] List.
- There exists a valid future hypothetical WeakRef-oblivious execution with respect to S that observes the Object value of any object in S.
Note 4
The intuition the second condition above intends to capture is that an object is live if its identity is observable via non-
means. An object's identity may be observed by observing a strict equality comparison between objects or observing the object being used as key in a Map.
Note 5
Presence of an object in a field, an internal slot, or a property does not imply that the object is live. For example if the object 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 a FinalizationRegistry 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 which WeakRefs 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.
At any time, if a set of objects S is not live, an ECMAScript implementation may perform the following steps atomically:
- For each element obj of S, do
- For each WeakRef ref such that ref.[[WeakRefTarget]] is obj, do
- Set ref.[[WeakRefTarget]] to empty.
- For each FinalizationRegistry fg such that fg.[[Cells]] contains a Record cell such that cell.[[WeakRefTarget]] is obj, do
- Set cell.[[WeakRefTarget]] to empty.
- Optionally, perform ! HostEnqueueFinalizationRegistryCleanupJob(fg).
- For each WeakMap map such that map.[[WeakMapData]] contains a Record r such that r.[[Key]] is obj, do
- Set r.[[Key]] to empty.
- Set r.[[Value]] to empty.
- For each WeakSet set such that set.[[WeakSetData]] contains obj, do
- Replace the element of set.[[WeakSetData]] whose value is obj with an element whose value is empty.
- For each WeakRef ref such that ref.[[WeakRefTarget]] is obj, do
Note 1
Together with the definition of liveness, this clause prescribes legal optimizations that an implementation may apply regarding WeakRefs.
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 empty WeakRefs 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 a WeakRef, optimizations such as rematerialization that observably empty the WeakRef are prohibited.
Because calling HostEnqueueFinalizationRegistryCleanupJob is optional, registered objects in a FinalizationRegistry do not necessarily hold that FinalizationRegistry live. Implementations may omit FinalizationRegistry callbacks for any reason, e.g., if the FinalizationRegistry itself becomes dead, or if the application is shutting down.
Note 2
Implementations are not obligated to empty WeakRefs for maximal sets of non-live objects.
If an implementation chooses a non-live set S in which to empty WeakRefs, it must empty WeakRefs for all objects in S simultaneously. In other words, an implementation must not empty a WeakRef pointing to an object obj without emptying out other WeakRefs that, if not emptied, could result in an execution that observes the Object value of obj.
The abstract operation HostEnqueueFinalizationRegistryCleanupJob takes argument finalizationRegistry (a FinalizationRegistry). HostEnqueueFinalizationRegistryCleanupJob is an implementation-defined abstract operation that is expected to call CleanupFinalizationRegistry(finalizationRegistry) at some point in the future, if possible. The host's responsibility is to make this call at a time which does not interrupt synchronous ECMAScript code execution.
The abstract operation ClearKeptObjects takes no arguments. ECMAScript implementations are expected to call ClearKeptObjects when a synchronous sequence of ECMAScript executions completes. It performs the following steps when called:
- Let agentRecord be the surrounding agent's Agent Record.
- Set agentRecord.[[KeptAlive]] to a new empty List.
The abstract operation AddToKeptObjects takes argument object (an Object). It performs the following steps when called:
- Let agentRecord be the surrounding agent's Agent Record.
- Append object to agentRecord.[[KeptAlive]].
Note
When the abstract operation AddToKeptObjects is called with a target object reference, it adds the target to a list that will point strongly at the target until
is called.
The abstract operation CleanupFinalizationRegistry takes argument finalizationRegistry (a FinalizationRegistry). It performs the following steps when called:
- Assert: finalizationRegistry has [[Cells]] and [[CleanupCallback]] internal slots.
- Let callback be finalizationRegistry.[[CleanupCallback]].
- While finalizationRegistry.[[Cells]] contains a Record cell such that cell.[[WeakRefTarget]] is empty, an implementation may perform the following steps:
- Choose any such cell.
- Remove cell from finalizationRegistry.[[Cells]].
- Perform ? Call(callback, undefined, « cell.[[HeldValue]] »).
- Return NormalCompletion(undefined).
All ordinary objects have an internal slot called [[Prototype]]. The value of this internal slot is either null or an object and is used for implementing inheritance. Data properties of the [[Prototype]] object are inherited (and visible as properties of the child object) for the purposes of get access, but not for set access. Accessor properties are inherited for both get access and set access.
Every ordinary object has a Boolean-valued [[Extensible]] internal slot which is used to fulfill the extensibility-related internal method invariants specified in 6.1.7.3. Namely, once the value of an object's [[Extensible]] internal slot has been set to false, it is no longer possible to add properties to the object, to modify the value of the object's [[Prototype]] internal slot, or to subsequently change the value of [[Extensible]] to true.
In the following algorithm descriptions, assume O is an ordinary object, P is a property key value, V is any ECMAScript language value, and Desc is a Property Descriptor record.
Each ordinary object internal method delegates to a similarly-named abstract operation. If such an abstract operation depends on another internal method, then the internal method is invoked on O rather than calling the similarly-named abstract operation directly. These semantics ensure that exotic objects have their overridden internal methods invoked when ordinary object internal methods are applied to them.
The [[GetPrototypeOf]] internal method of an ordinary object O takes no arguments. It performs the following steps when called:
- Return ! OrdinaryGetPrototypeOf(O).
The abstract operation OrdinaryGetPrototypeOf takes argument O (an Object). It performs the following steps when called:
- Return O.[[Prototype]].
The [[SetPrototypeOf]] internal method of an ordinary object O takes argument V (an Object or null). It performs the following steps when called:
- Return ! OrdinarySetPrototypeOf(O, V).
The abstract operation OrdinarySetPrototypeOf takes arguments O (an Object) and V (an ECMAScript language value). It performs the following steps when called:
- Assert: Either Type(V) is Object or Type(V) is Null.
- Let current be O.[[Prototype]].
- If SameValue(V, current) is true, return true.
- Let extensible be O.[[Extensible]].
- If extensible is false, return false.
- Let p be V.
- Let done be false.
- Repeat, while done is false,
- If p is null, set done to true.
- Else if SameValue(p, O) is true, return false.
- Else,
- If p.[[GetPrototypeOf]] is not the ordinary object internal method defined in 10.1.1, set done to true.
- Else, set p to p.[[Prototype]].
- Set O.[[Prototype]] to V.
- Return true.
Note
The loop in step 8 guarantees that there will be no circularities in any prototype chain that only includes objects that use the ordinary object definitions for [[GetPrototypeOf]] and [[SetPrototypeOf]].
The [[IsExtensible]] internal method of an ordinary object O takes no arguments. It performs the following steps when called:
- Return ! OrdinaryIsExtensible(O).
The abstract operation OrdinaryIsExtensible takes argument O (an Object). It performs the following steps when called:
- Return O.[[Extensible]].
The [[PreventExtensions]] internal method of an ordinary object O takes no arguments. It performs the following steps when called:
- Return ! OrdinaryPreventExtensions(O).
The abstract operation OrdinaryPreventExtensions takes argument O (an Object). It performs the following steps when called:
- Set O.[[Extensible]] to false.
- Return true.
The [[GetOwnProperty]] internal method of an ordinary object O takes argument P (a property key). It performs the following steps when called:
- Return ! OrdinaryGetOwnProperty(O, P).
The abstract operation OrdinaryGetOwnProperty takes arguments O (an Object) and P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If O does not have an own property with key P, return undefined.
- Let D be a newly created Property Descriptor with no fields.
- Let X be O's own property whose key is P.
- If X is a data property, then
- Set D.[[Value]] to the value of X's [[Value]] attribute.
- Set D.[[Writable]] to the value of X's [[Writable]] attribute.
- Else,
- Assert: X is an accessor property.
- Set D.[[Get]] to the value of X's [[Get]] attribute.
- Set D.[[Set]] to the value of X's [[Set]] attribute.
- Set D.[[Enumerable]] to the value of X's [[Enumerable]] attribute.
- Set D.[[Configurable]] to the value of X's [[Configurable]] attribute.
- Return D.
The [[DefineOwnProperty]] internal method of an ordinary object O takes arguments P (a property key) and Desc (a Property Descriptor). It performs the following steps when called:
- Return ? OrdinaryDefineOwnProperty(O, P, Desc).
The abstract operation OrdinaryDefineOwnProperty takes arguments O (an Object), P (a property key), and Desc (a Property Descriptor). It performs the following steps when called:
- Let current be ? O.[[GetOwnProperty]](P).
- Let extensible be ? IsExtensible(O).
- Return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current).
The abstract operation IsCompatiblePropertyDescriptor takes arguments Extensible (a Boolean), Desc (a Property Descriptor), and Current (a Property Descriptor). It performs the following steps when called:
- Return ValidateAndApplyPropertyDescriptor(undefined, undefined, Extensible, Desc, Current).
The abstract operation ValidateAndApplyPropertyDescriptor takes arguments O (an Object or undefined), P (a property key), extensible (a Boolean), Desc (a Property Descriptor), and current (a Property Descriptor). It performs the following steps when called:
Note
If undefined is passed as O, only validation is performed and no object updates are performed.
- Assert: If O is not undefined, then IsPropertyKey(P) is true.
- If current is undefined, then
- If extensible is false, return false.
- Assert: extensible is true.
- If IsGenericDescriptor(Desc) is true or IsDataDescriptor(Desc) is true, then
- If O is not undefined, create an own data property named P of object O whose [[Value]], [[Writable]], [[Enumerable]], and [[Configurable]] attribute values are described by Desc. If the value of an attribute field of Desc is absent, the attribute of the newly created property is set to its default value.
- Else,
- Assert: ! IsAccessorDescriptor(Desc) is true.
- If O is not undefined, create an own accessor property named P of object O whose [[Get]], [[Set]], [[Enumerable]], and [[Configurable]] attribute values are described by Desc. If the value of an attribute field of Desc is absent, the attribute of the newly created property is set to its default value.
- Return true.
- If every field in Desc is absent, return true.
- If current.[[Configurable]] is false, then
- If Desc.[[Configurable]] is present and its value is true, return false.
- If Desc.[[Enumerable]] is present and ! SameValue(Desc.[[Enumerable]], current.[[Enumerable]]) is false, return false.
- If ! IsGenericDescriptor(Desc) is true, then
- NOTE: No further validation is required.
- Else if ! SameValue(! IsDataDescriptor(current), ! IsDataDescriptor(Desc)) is false, then
- If current.[[Configurable]] is false, return false.
- If IsDataDescriptor(current) is true, then
- If O is not undefined, convert the property named P of object O from a data property to an accessor property. Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and set the rest of the property's attributes to their default values.
- Else,
- If O is not undefined, convert the property named P of object O from an accessor property to a data property. Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and set the rest of the property's attributes to their default values.
- Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true, then
- If current.[[Configurable]] is false and current.[[Writable]] is false, then
- If Desc.[[Writable]] is present and Desc.[[Writable]] is true, return false.
- If Desc.[[Value]] is present and SameValue(Desc.[[Value]], current.[[Value]]) is false, return false.
- Return true.
- If current.[[Configurable]] is false and current.[[Writable]] is false, then
- Else,
- Assert: ! IsAccessorDescriptor(current) and ! IsAccessorDescriptor(Desc) are both true.
- If current.[[Configurable]] is false, then
- If O is not undefined, then
- For each field of Desc that is present, set the corresponding attribute of the property named P of object O to the value of the field.
- Return true.
The [[HasProperty]] internal method of an ordinary object O takes argument P (a property key). It performs the following steps when called:
- Return ? OrdinaryHasProperty(O, P).
The abstract operation OrdinaryHasProperty takes arguments O (an Object) and P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let hasOwn be ? O.[[GetOwnProperty]](P).
- If hasOwn is not undefined, return true.
- Let parent be ? O.[[GetPrototypeOf]]().
- If parent is not null, then
- Return ? parent.[[HasProperty]](P).
- Return false.
The [[Get]] internal method of an ordinary object O takes arguments P (a property key) and Receiver (an ECMAScript language value). It performs the following steps when called:
- Return ? OrdinaryGet(O, P, Receiver).
The abstract operation OrdinaryGet takes arguments O (an Object), P (a property key), and Receiver (an ECMAScript language value). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let desc be ? O.[[GetOwnProperty]](P).
- If desc is undefined, then
- Let parent be ? O.[[GetPrototypeOf]]().
- If parent is null, return undefined.
- Return ? parent.[[Get]](P, Receiver).
- If IsDataDescriptor(desc) is true, return desc.[[Value]].
- Assert: IsAccessorDescriptor(desc) is true.
- Let getter be desc.[[Get]].
- If getter is undefined, return undefined.
- Return ? Call(getter, Receiver).
The [[Set]] internal method of an ordinary object O takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value). It performs the following steps when called:
- Return ? OrdinarySet(O, P, V, Receiver).
The abstract operation OrdinarySet takes arguments O (an Object), P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let ownDesc be ? O.[[GetOwnProperty]](P).
- Return OrdinarySetWithOwnDescriptor(O, P, V, Receiver, ownDesc).
The abstract operation OrdinarySetWithOwnDescriptor takes arguments O (an Object), P (a property key), V (an ECMAScript language value), Receiver (an ECMAScript language value), and ownDesc (a Property Descriptor or undefined). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If ownDesc is undefined, then
- Let parent be ? O.[[GetPrototypeOf]]().
- If parent is not null, then
- Return ? parent.[[Set]](P, V, Receiver).
- Else,
- Set ownDesc to the PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
- If IsDataDescriptor(ownDesc) is true, then
- If ownDesc.[[Writable]] is false, return false.
- If Type(Receiver) is not Object, return false.
- Let existingDescriptor be ? Receiver.[[GetOwnProperty]](P).
- If existingDescriptor is not undefined, then
- If IsAccessorDescriptor(existingDescriptor) is true, return false.
- If existingDescriptor.[[Writable]] is false, return false.
- Let valueDesc be the PropertyDescriptor { [[Value]]: V }.
- Return ? Receiver.[[DefineOwnProperty]](P, valueDesc).
- Else,
- Assert: Receiver does not currently have a property P.
- Return ? CreateDataProperty(Receiver, P, V).
- Assert: IsAccessorDescriptor(ownDesc) is true.
- Let setter be ownDesc.[[Set]].
- If setter is undefined, return false.
- Perform ? Call(setter, Receiver, « V »).
- Return true.
The [[Delete]] internal method of an ordinary object O takes argument P (a property key). It performs the following steps when called:
- Return ? OrdinaryDelete(O, P).
The abstract operation OrdinaryDelete takes arguments O (an Object) and P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let desc be ? O.[[GetOwnProperty]](P).
- If desc is undefined, return true.
- If desc.[[Configurable]] is true, then
- Remove the own property with name P from O.
- Return true.
- Return false.
The [[OwnPropertyKeys]] internal method of an ordinary object O takes no arguments. It performs the following steps when called:
- Return ! OrdinaryOwnPropertyKeys(O).
The abstract operation OrdinaryOwnPropertyKeys takes argument O (an Object). It performs the following steps when called:
- Let keys be a new empty List.
- For each own property key P of O such that P is an array index, in ascending numeric index order, do
- Add P as the last element of keys.
- For each own property key P of O such that Type(P) is String and P is not an array index, in ascending chronological order of property creation, do
- Add P as the last element of keys.
- For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property creation, do
- Add P as the last element of keys.
- Return keys.
The abstract operation OrdinaryObjectCreate takes argument proto (an Object or null) and optional argument additionalInternalSlotsList (a List of names of internal slots). It is used to specify the runtime creation of new ordinary objects. additionalInternalSlotsList contains the names of additional internal slots that must be defined as part of the object, beyond [[Prototype]] and [[Extensible]]. If additionalInternalSlotsList is not provided, a new empty List is used. It performs the following steps when called:
- Let internalSlotsList be « [[Prototype]], [[Extensible]] ».
- If additionalInternalSlotsList is present, append each of its elements to internalSlotsList.
- Let O be ! MakeBasicObject(internalSlotsList).
- Set O.[[Prototype]] to proto.
- Return O.
Note
Although OrdinaryObjectCreate does little more than call MakeBasicObject, its use communicates the intention to create an ordinary object, and not an exotic one. Thus, within this specification, it is not called by any algorithm that subsequently modifies the internal methods of the object in ways that would make the result non-ordinary. Operations that create exotic objects invoke MakeBasicObject directly.
10.1.13 OrdinaryCreateFromConstructor ( constructor, intrinsicDefaultProto [ , internalSlotsList ] )
The abstract operation OrdinaryCreateFromConstructor takes arguments constructor and intrinsicDefaultProto and optional argument internalSlotsList (a List of names of internal slots). It creates an ordinary object whose [[Prototype]] value is retrieved from a constructor's "prototype" property, if it exists. Otherwise the intrinsic named by intrinsicDefaultProto is used for [[Prototype]]. internalSlotsList contains the names of additional internal slots that must be defined as part of the object. If internalSlotsList is not provided, a new empty List is used. It performs the following steps when called:
- Assert: intrinsicDefaultProto is a String value that is this specification's name of an intrinsic object. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.
- Let proto be ? GetPrototypeFromConstructor(constructor, intrinsicDefaultProto).
- Return ! OrdinaryObjectCreate(proto, internalSlotsList).
The abstract operation GetPrototypeFromConstructor takes arguments constructor and intrinsicDefaultProto. It determines the [[Prototype]] value that should be used to create an object corresponding to a specific constructor. The value is retrieved from the constructor's "prototype" property, if it exists. Otherwise the intrinsic named by intrinsicDefaultProto is used for [[Prototype]]. It performs the following steps when called:
- Assert: intrinsicDefaultProto is a String value that is this specification's name of an intrinsic object. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.
- Assert: IsCallable(constructor) is true.
- Let proto be ? Get(constructor, "prototype").
- If Type(proto) is not Object, then
- Let realm be ? GetFunctionRealm(constructor).
- Set proto to realm's intrinsic object named intrinsicDefaultProto.
- Return proto.
Note
If constructor does not supply a [[Prototype]] value, the default value that is used is obtained from the realm of the constructor function rather than from the running execution context.
The abstract operation RequireInternalSlot takes arguments O and internalSlot. It throws an exception unless O is an Object and has the given internal slot. It performs the following steps when called:
- If Type(O) is not Object, throw a TypeError exception.
- If O does not have an internalSlot internal slot, throw a TypeError exception.
ECMAScript function objects encapsulate parameterized ECMAScript code closed over a lexical environment and support the dynamic evaluation of that code. An ECMAScript function object is an ordinary object and has the same internal slots and the same internal methods as other ordinary objects. The code of an ECMAScript function object may be either strict mode code (11.2.2) or non-strict code. An ECMAScript function object whose code is strict mode code is called a strict function. One whose code is not strict mode code is called a non-strict function.
In addition to [[Extensible]] and [[Prototype]], ECMAScript function objects also have the internal slots listed in Table 29.
Table 29: Internal Slots of ECMAScript Function Objects
Internal Slot | Type | Description |
---|---|---|
[[Environment]] | Environment Record | The Environment Record that the function was closed over. Used as the outer environment when evaluating the code of the function. |
[[FormalParameters]] | Parse Node | The root parse node of the source text that defines the function's formal parameter list. |
[[ECMAScriptCode]] | Parse Node | The root parse node of the source text that defines the function's body. |
[[ConstructorKind]] | base | derived |
[[Realm]] | Realm Record | The realm in which the function was created and which provides any intrinsic objects that are accessed when evaluating the function. |
[[ScriptOrModule]] | Script Record or Module Record | The script or module in which the function was created. |
[[ThisMode]] | lexical | strict |
[[Strict]] | Boolean | true if this is a strict function, false if this is a non-strict function. |
[[HomeObject]] | Object | If the function uses super , this is the object whose [[GetPrototypeOf]] provides the object where super property lookups begin. |
[[SourceText]] | sequence of Unicode code points | The source text that defines the function. |
[[IsClassConstructor]] | Boolean | Indicates whether the function is a class constructor. (If true, invoking the function's [[Call]] will immediately throw a TypeError exception.) |
All ECMAScript function objects have the [[Call]] internal method defined here. ECMAScript functions that are also constructors in addition have the [[Construct]] internal method.
The [[Call]] internal method of an ECMAScript function object F takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values). It performs the following steps when called:
- Assert: F is an ECMAScript function object.
- Let callerContext be the running execution context.
- Let calleeContext be PrepareForOrdinaryCall(F, undefined).
- Assert: calleeContext is now the running execution context.
- If F.[[IsClassConstructor]] is true, then
- Let error be a newly created TypeError object.
- NOTE: error is created in calleeContext with F's associated Realm Record.
- Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
- Return ThrowCompletion(error).
- Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
- Let result be OrdinaryCallEvaluateBody(F, argumentsList).
- Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
- If result.[[Type]] is return, return NormalCompletion(result.[[Value]]).
- ReturnIfAbrupt(result).
- Return NormalCompletion(undefined).
Note
When calleeContext is removed from the execution context stack in step 8 it must not be destroyed if it is suspended and retained for later resumption by an accessible generator object.
The abstract operation PrepareForOrdinaryCall takes arguments F (a function object) and newTarget (an ECMAScript language value). It performs the following steps when called:
- Assert: Type(newTarget) is Undefined or Object.
- Let callerContext be the running execution context.
- Let calleeContext be a new ECMAScript code execution context.
- Set the Function of calleeContext to F.
- Let calleeRealm be F.[[Realm]].
- Set the Realm of calleeContext to calleeRealm.
- Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
- Let localEnv be NewFunctionEnvironment(F, newTarget).
- Set the LexicalEnvironment of calleeContext to localEnv.
- Set the VariableEnvironment of calleeContext to localEnv.
- If callerContext is not already suspended, suspend callerContext.
- Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
- NOTE: Any exception objects produced after this point are associated with calleeRealm.
- Return calleeContext.
The abstract operation OrdinaryCallBindThis takes arguments F (a function object), calleeContext (an execution context), and thisArgument (an ECMAScript language value). It performs the following steps when called:
- Let thisMode be F.[[ThisMode]].
- If thisMode is lexical, return NormalCompletion(undefined).
- Let calleeRealm be F.[[Realm]].
- Let localEnv be the LexicalEnvironment of calleeContext.
- If thisMode is strict, let thisValue be thisArgument.
- Else,
- If thisArgument is undefined or null, then
- Let globalEnv be calleeRealm.[[GlobalEnv]].
- Assert: globalEnv is a global Environment Record.
- Let thisValue be globalEnv.[[GlobalThisValue]].
- Else,
- If thisArgument is undefined or null, then
- Assert: localEnv is a function Environment Record.
- Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized.
- Return localEnv.BindThisValue(thisValue).
With parameters functionObject and argumentsList (a List).
FunctionBody : FunctionStatementList
- Return ? EvaluateFunctionBody of FunctionBody with arguments functionObject and argumentsList.
- Return ? EvaluateConciseBody of ConciseBody with arguments functionObject and argumentsList.
- Return ? EvaluateGeneratorBody of GeneratorBody with arguments functionObject and argumentsList.
AsyncGeneratorBody : FunctionBody
- Return ? EvaluateAsyncGeneratorBody of AsyncGeneratorBody with arguments functionObject and argumentsList.
AsyncFunctionBody : FunctionBody
- Return ? EvaluateAsyncFunctionBody of AsyncFunctionBody with arguments functionObject and argumentsList.
AsyncConciseBody : ExpressionBody
- Return ? EvaluateAsyncConciseBody of AsyncConciseBody with arguments functionObject and argumentsList.
The abstract operation OrdinaryCallEvaluateBody takes arguments F (a function object) and argumentsList (a List). It performs the following steps when called:
- Return the result of EvaluateBody of the parsed code that is F.[[ECMAScriptCode]] passing F and argumentsList as the arguments.
The [[Construct]] internal method of an ECMAScript function object F takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor). It performs the following steps when called:
- Assert: F is an ECMAScript function object.
- Assert: Type(newTarget) is Object.
- Let callerContext be the running execution context.
- Let kind be F.[[ConstructorKind]].
- If kind is base, then
- Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
- Let calleeContext be PrepareForOrdinaryCall(F, newTarget).
- Assert: calleeContext is now the running execution context.
- If kind is base, perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
- Let constructorEnv be the LexicalEnvironment of calleeContext.
- Let result be OrdinaryCallEvaluateBody(F, argumentsList).
- Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
- If result.[[Type]] is return, then 1. If Type(result.[[Value]]) is Object, return NormalCompletion(result.[[Value]]). 2. If kind is base, return NormalCompletion(thisArgument). 3. If result.[[Value]] is not undefined, throw a TypeError exception.
- Else, ReturnIfAbrupt(result).
- Return ? constructorEnv.GetThisBinding().
10.2.3 OrdinaryFunctionCreate ( functionPrototype, sourceText, ParameterList, Body, thisMode, Scope )
The abstract operation OrdinaryFunctionCreate takes arguments functionPrototype (an Object), sourceText (a sequence of Unicode code points), ParameterList (a Parse Node), Body (a Parse Node), thisMode (either lexical-this or non-lexical-this), and Scope (an Environment Record). sourceText is the source text of the syntactic definition of the function to be created. It performs the following steps when called:
- Assert: Type(functionPrototype) is Object.
- Let internalSlotsList be the internal slots listed in Table 29.
- Let F be ! OrdinaryObjectCreate(functionPrototype, internalSlotsList).
- Set F.[[Call]] to the definition specified in 10.2.1.
- Set F.[[SourceText]] to sourceText.
- Set F.[[FormalParameters]] to ParameterList.
- Set F.[[ECMAScriptCode]] to Body.
- If the source text matching Body is strict mode code, let Strict be true; else let Strict be false.
- Set F.[[Strict]] to Strict.
- If thisMode is lexical-this, set F.[[ThisMode]] to lexical.
- Else if Strict is true, set F.[[ThisMode]] to strict.
- Else, set F.[[ThisMode]] to global.
- Set F.[[IsClassConstructor]] to false.
- Set F.[[Environment]] to Scope.
- Set F.[[ScriptOrModule]] to GetActiveScriptOrModule().
- Set F.[[Realm]] to the current Realm Record.
- Set F.[[HomeObject]] to undefined.
- Let len be the ExpectedArgumentCount of ParameterList.
- Perform ! SetFunctionLength(F, len).
- Return F.
The abstract operation AddRestrictedFunctionProperties takes arguments F (a function object) and realm (a Realm Record). It performs the following steps when called:
- Assert: realm.[[Intrinsics]].[[%ThrowTypeError%]] exists and has been initialized.
- Let thrower be realm.[[Intrinsics]].[[%ThrowTypeError%]].
- Perform ! DefinePropertyOrThrow(F, "caller", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true }).
- Return ! DefinePropertyOrThrow(F, "arguments", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true }).
The %ThrowTypeError% intrinsic is an anonymous built-in function object that is defined once for each realm. When %ThrowTypeError% is called it performs the following steps:
- Throw a TypeError exception.
The value of the [[Extensible]] internal slot of a %ThrowTypeError% function is false.
The "length" property of a %ThrowTypeError% function has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
The "name" property of a %ThrowTypeError% function has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
The abstract operation MakeConstructor takes argument F (a function object) and optional arguments writablePrototype (a Boolean) and prototype (an Object). It converts F into a constructor. It performs the following steps when called:
- Assert: F is an ECMAScript function object or a built-in function object.
- If F is an ECMAScript function object, then
- Assert: IsConstructor(F) is false.
- Assert: F is an extensible object that does not have a "prototype" own property.
- Set F.[[Construct]] to the definition specified in 10.2.2.
- Set F.[[ConstructorKind]] to base.
- If writablePrototype is not present, set writablePrototype to true.
- If prototype is not present, then
- Set prototype to ! OrdinaryObjectCreate(%Object.prototype%).
- Perform ! DefinePropertyOrThrow(prototype, "constructor", PropertyDescriptor { [[Value]]: F, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: true }).
- Perform ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: false }).
- Return NormalCompletion(undefined).
The abstract operation MakeClassConstructor takes argument F. It performs the following steps when called:
- Assert: F is an ECMAScript function object.
- Assert: F.[[IsClassConstructor]] is false.
- Set F.[[IsClassConstructor]] to true.
- Return NormalCompletion(undefined).
The abstract operation MakeMethod takes arguments F and homeObject. It configures F as a method. It performs the following steps when called:
- Assert: F is an ECMAScript function object.
- Assert: Type(homeObject) is Object.
- Set F.[[HomeObject]] to homeObject.
- Return NormalCompletion(undefined).
The abstract operation SetFunctionName takes arguments F (a function object) and name (a property key) and optional argument prefix (a String). It adds a "name" property to F. It performs the following steps when called:
- Assert: F is an extensible object that does not have a "name" own property.
- Assert: Type(name) is either Symbol or String.
- Assert: If prefix is present, then Type(prefix) is String.
- If Type(name) is Symbol, then
- Let description be name's [[Description]] value.
- If description is undefined, set name to the empty String.
- Else, set name to the string-concatenation of "[", description, and "]".
- If F has an [[InitialName]] internal slot, then
- Set F.[[InitialName]] to name.
- If prefix is present, then
- Set name to the string-concatenation of prefix, the code unit 0x0020 (SPACE), and name.
- If F has an [[InitialName]] internal slot, then
- Optionally, set F.[[InitialName]] to name.
- Return ! DefinePropertyOrThrow(F, "name", PropertyDescriptor { [[Value]]: name, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }).
The abstract operation SetFunctionLength takes arguments F (a function object) and length (a non-negative integer or +∞). It adds a "length" property to F. It performs the following steps when called:
- Assert: F is an extensible object that does not have a "length" own property.
- Return ! DefinePropertyOrThrow(F, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }).
Note 1
When an execution context is established for evaluating an ECMAScript function a new function Environment Record is created and bindings for each formal parameter are instantiated in that Environment Record. Each declaration in the function body is also instantiated. If the function's formal parameters do not include any default value initializers then the body declarations are instantiated in the same Environment Record as the parameters. If default value parameter initializers exist, a second Environment Record is created for the body declarations. Formal parameters and functions are initialized as part of FunctionDeclarationInstantiation. All other bindings are initialized during evaluation of the function body.
The abstract operation FunctionDeclarationInstantiation takes arguments func (a function object) and argumentsList. func is the function object for which the execution context is being established. It performs the following steps when called:
- Let calleeContext be the running execution context.
- Let code be func.[[ECMAScriptCode]].
- Let strict be func.[[Strict]].
- Let formals be func.[[FormalParameters]].
- Let parameterNames be the BoundNames of formals.
- If parameterNames has any duplicate entries, let hasDuplicates be true. Otherwise, let hasDuplicates be false.
- Let simpleParameterList be IsSimpleParameterList of formals.
- Let hasParameterExpressions be ContainsExpression of formals.
- Let varNames be the VarDeclaredNames of code.
- Let varDeclarations be the VarScopedDeclarations of code.
- Let lexicalNames be the LexicallyDeclaredNames of code.
- Let functionNames be a new empty List.
- Let functionsToInitialize be a new empty List.
- For each element d of varDeclarations, in reverse List order, do
1. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
- Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
- Let fn be the sole element of the BoundNames of d.
- If fn is not an element of functionNames, then
- Insert fn as the first element of functionNames.
- NOTE: If there are multiple function declarations for the same name, the last declaration is used.
- Insert d as the first element of functionsToInitialize.
- Let argumentsObjectNeeded be true.
- If func.[[ThisMode]] is lexical, then 1. NOTE: Arrow functions never have an arguments objects. 2. Set argumentsObjectNeeded to false.
- Else if "arguments" is an element of parameterNames, then 1. Set argumentsObjectNeeded to false.
- Else if hasParameterExpressions is false, then
1. If "arguments" is an element of functionNames or if "arguments" is an element of lexicalNames, then
- Set argumentsObjectNeeded to false.
- If strict is true or if hasParameterExpressions is false, then 1. NOTE: Only a single Environment Record is needed for the parameters and top-level vars. 2. Let env be the LexicalEnvironment of calleeContext.
- Else, 1. NOTE: A separate Environment Record is needed to ensure that bindings created by direct eval calls in the formal parameter list are outside the environment where parameters are declared. 2. Let calleeEnv be the LexicalEnvironment of calleeContext. 3. Let env be NewDeclarativeEnvironment(calleeEnv). 4. Assert: The VariableEnvironment of calleeContext is calleeEnv. 5. Set the LexicalEnvironment of calleeContext to env.
- For each String paramName of parameterNames, do
1. Let alreadyDeclared be env.HasBinding(paramName).
2. NOTE: Early errors ensure that duplicate parameter names can only occur in non-strict functions that do not have parameter default values or rest parameters.
3. If alreadyDeclared is false, then
- Perform ! env.CreateMutableBinding(paramName, false).
- If hasDuplicates is true, then
- Perform ! env.InitializeBinding(paramName, undefined).
- If argumentsObjectNeeded is true, then
1. If strict is true or if simpleParameterList is false, then
- Let ao be CreateUnmappedArgumentsObject(argumentsList). 2. Else,
- NOTE: A mapped argument object is only provided for non-strict functions that don't have a rest parameter, any parameter default value initializers, or any destructured parameters.
- Let ao be CreateMappedArgumentsObject(func, formals, argumentsList, env). 3. If strict is true, then
- Perform ! env.CreateImmutableBinding("arguments", false). 4. Else,
- Perform ! env.CreateMutableBinding("arguments", false). 5. Call env.InitializeBinding("arguments", ao). 6. Let parameterBindings be a List whose elements are the elements of parameterNames, followed by "arguments".
- Else, 1. Let parameterBindings be parameterNames.
- Let iteratorRecord be CreateListIteratorRecord(argumentsList).
- If hasDuplicates is true, then 1. Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
- Else, 1. Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
- If hasParameterExpressions is false, then
1. NOTE: Only a single Environment Record is needed for the parameters and top-level vars.
2. Let instantiatedVarNames be a copy of the List parameterBindings.
3. For each element n of varNames, do
- If n is not an element of instantiatedVarNames, then
- Append n to instantiatedVarNames.
- Perform ! env.CreateMutableBinding(n, false).
- Call env.InitializeBinding(n, undefined). 4. Let varEnv be env.
- If n is not an element of instantiatedVarNames, then
- Else,
1. NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body.
2. Let varEnv be NewDeclarativeEnvironment(env).
3. Set the VariableEnvironment of calleeContext to varEnv.
4. Let instantiatedVarNames be a new empty List.
5. For each element n of varNames, do
- If n is not an element of instantiatedVarNames, then
- Append n to instantiatedVarNames.
- Perform ! varEnv.CreateMutableBinding(n, false).
- If n is not an element of parameterBindings or if n is an element of functionNames, let initialValue be undefined.
- Else,
- Let initialValue be ! env.GetBindingValue(n, false).
- Call varEnv.InitializeBinding(n, initialValue).
- NOTE: A var with the same name as a formal parameter initially has the same value as the corresponding initialized parameter.
- If n is not an element of instantiatedVarNames, then
- NOTE: Annex B.3.3.1 adds additional steps at this point.
- If strict is false, then 1. Let lexEnv be NewDeclarativeEnvironment(varEnv). 2. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places all declarations into a new Environment Record.
- Else, let lexEnv be varEnv.
- Set the LexicalEnvironment of calleeContext to lexEnv.
- Let lexDeclarations be the LexicallyScopedDeclarations of code.
- For each element d of lexDeclarations, do
1. NOTE: A lexically declared name cannot be the same as a function/generator declaration, formal parameter, or a var name. Lexically declared names are only instantiated here but not initialized.
2. For each element dn of the BoundNames of d, do
- If IsConstantDeclaration of d is true, then
- Perform ! lexEnv.CreateImmutableBinding(dn, true).
- Else,
- Perform ! lexEnv.CreateMutableBinding(dn, false).
- If IsConstantDeclaration of d is true, then
- For each Parse Node f of functionsToInitialize, do 1. Let fn be the sole element of the BoundNames of f. 2. Let fo be InstantiateFunctionObject of f with argument lexEnv. 3. Perform ! varEnv.SetMutableBinding(fn, fo, false).
- Return NormalCompletion(empty).
Note 2
B.3.3 provides an extension to the above algorithm that is necessary for backwards compatibility with web browser implementations of ECMAScript that predate ECMAScript 2015.
Note 3
Parameter Initializers may contain direct eval expressions. Any top level declarations of such evals are only visible to the eval code (11.2). The creation of the environment for such declarations is described in 8.5.3.
The built-in function objects defined in this specification may be implemented as either ECMAScript function objects (10.2) whose behaviour is provided using ECMAScript code or as implementation provided function exotic objects whose behaviour is provided in some other manner. In either case, the effect of calling such functions must conform to their specifications. An implementation may also provide additional built-in function objects that are not defined in this specification.
If a built-in function object is implemented as an exotic object it must have the ordinary object behaviour specified in 10.1. All such function exotic objects also have [[Prototype]], [[Extensible]], and [[Realm]] internal slots.
Unless otherwise specified every built-in function object has the %Function.prototype% object as the initial value of its [[Prototype]] internal slot.
The behaviour specified for each built-in function via algorithm steps or other means is the specification of the function body behaviour for both [[Call]] and [[Construct]] invocations of the function. However, [[Construct]] invocation is not supported by all built-in functions. For each built-in function, when invoked with [[Call]], the [[Call]] thisArgument provides the this value, the [[Call]] argumentsList provides the named parameters, and the NewTarget value is undefined. When invoked with [[Construct]], the this value is uninitialized, the [[Construct]] argumentsList provides the named parameters, and the [[Construct]] newTarget parameter provides the NewTarget value. If the built-in function is implemented as an ECMAScript function object then this specified behaviour must be implemented by the ECMAScript code that is the body of the function. Built-in functions that are ECMAScript function objects must be strict functions. If a built-in constructor has any [[Call]] behaviour other than throwing a TypeError exception, an ECMAScript implementation of the function must be done in a manner that does not cause the function's [[IsClassConstructor]] internal slot to have the value true.
Built-in function objects that are not identified as constructors do not implement the [[Construct]] internal method unless otherwise specified in the description of a particular function. When a built-in constructor is called as part of a new
expression the argumentsList parameter of the invoked [[Construct]] internal method provides the values for the built-in constructor's named parameters.
Built-in functions that are not constructors do not have a "prototype" property unless otherwise specified in the description of a particular function.
Built-in functions have an [[InitialName]] internal slot.
If a built-in function object is not implemented as an ECMAScript function it must provide [[Call]] and [[Construct]] internal methods that conform to the following definitions:
The [[Call]] internal method of a built-in function object F takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values). It performs the following steps when called:
- Let callerContext be the running execution context.
- If callerContext is not already suspended, suspend callerContext.
- Let calleeContext be a new execution context.
- Set the Function of calleeContext to F.
- Let calleeRealm be F.[[Realm]].
- Set the Realm of calleeContext to calleeRealm.
- Set the ScriptOrModule of calleeContext to null.
- Perform any necessary implementation-defined initialization of calleeContext.
- Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
- Let result be the Completion Record that is the result of evaluating F in a manner that conforms to the specification of F. thisArgument is the this value, argumentsList provides the named parameters, and the NewTarget value is undefined.
- Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
- Return result.
Note
When calleeContext is removed from the execution context stack it must not be destroyed if it has been suspended and retained by an accessible generator object for later resumption.
The [[Construct]] internal method of a built-in function object F takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor). The steps performed are the same as [[Call]] (see 10.3.1) except that step 10 is replaced by:
- Let result be the Completion Record that is the result of evaluating F in a manner that conforms to the specification of F. The this value is uninitialized, argumentsList provides the named parameters, and newTarget provides the NewTarget value.
10.3.3 CreateBuiltinFunction ( steps, length, name, internalSlotsList [ , realm [ , prototype [ , prefix ] ] ] )
The abstract operation CreateBuiltinFunction takes arguments steps, length, name, and internalSlotsList (a List of names of internal slots) and optional arguments realm, prototype, and prefix. internalSlotsList contains the names of additional internal slots that must be defined as part of the object. This operation creates a built-in function object. It performs the following steps when called:
- Assert: steps is either a set of algorithm steps or other definition of a function's behaviour provided in this specification.
- If realm is not present or realm is empty, set realm to the current Realm Record.
- Assert: realm is a Realm Record.
- If prototype is not present, set prototype to realm.[[Intrinsics]].[[%Function.prototype%]].
- Let func be a new built-in function object that when called performs the action described by steps. The new function object has internal slots whose names are the elements of internalSlotsList, and an [[InitialName]] internal slot.
- Set func.[[Realm]] to realm.
- Set func.[[Prototype]] to prototype.
- Set func.[[Extensible]] to true.
- Set func.[[InitialName]] to null.
- Perform ! SetFunctionLength(func, length).
- If prefix is not present, then 1. Perform ! SetFunctionName(func, name).
- Else, 1. Perform ! SetFunctionName(func, name, prefix).
- Return func.
Each built-in function defined in this specification is created by calling the CreateBuiltinFunction abstract operation.
This specification defines several kinds of built-in exotic objects. These objects generally behave similar to ordinary objects except for a few specific situations. The following exotic objects use the ordinary object internal methods except where it is explicitly specified otherwise below:
A bound function exotic object is an exotic object that wraps another function object. A bound function exotic object is callable (it has a [[Call]] internal method and may have a [[Construct]] internal method). Calling a bound function exotic object generally results in a call of its wrapped function.
An object is a bound function exotic object if its [[Call]] and (if applicable) [[Construct]] internal methods use the following implementations, and its other essential internal methods use the definitions found in 10.1. These methods are installed in BoundFunctionCreate.
Bound function exotic objects do not have the internal slots of ECMAScript function objects listed in Table 29. Instead they have the internal slots listed in Table 30, in addition to [[Prototype]] and [[Extensible]].
Table 30: Internal Slots of Bound Function Exotic Objects
Internal Slot | Type | Description |
---|---|---|
[[BoundTargetFunction]] | Callable Object | The wrapped function object. |
[[BoundThis]] | Any | The value that is always passed as the this value when calling the wrapped function. |
[[BoundArguments]] | List of Any | A list of values whose elements are used as the first arguments to any call to the wrapped function. |
The [[Call]] internal method of a bound function exotic object F takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values). It performs the following steps when called:
- Let target be F.[[BoundTargetFunction]].
- Let boundThis be F.[[BoundThis]].
- Let boundArgs be F.[[BoundArguments]].
- Let args be a List whose elements are the elements of boundArgs, followed by the elements of argumentsList.
- Return ? Call(target, boundThis, args).
The [[Construct]] internal method of a bound function exotic object F takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor). It performs the following steps when called:
- Let target be F.[[BoundTargetFunction]].
- Assert: IsConstructor(target) is true.
- Let boundArgs be F.[[BoundArguments]].
- Let args be a List whose elements are the elements of boundArgs, followed by the elements of argumentsList.
- If SameValue(F, newTarget) is true, set newTarget to target.
- Return ? Construct(target, args, newTarget).
The abstract operation BoundFunctionCreate takes arguments targetFunction, boundThis, and boundArgs. It is used to specify the creation of new bound function exotic objects. It performs the following steps when called:
- Assert: Type(targetFunction) is Object.
- Let proto be ? targetFunction.[[GetPrototypeOf]]().
- Let internalSlotsList be the internal slots listed in Table 30, plus [[Prototype]] and [[Extensible]].
- Let obj be ! MakeBasicObject(internalSlotsList).
- Set obj.[[Prototype]] to proto.
- Set obj.[[Call]] as described in 10.4.1.1.
- If IsConstructor(targetFunction) is true, then
- Set obj.[[Construct]] as described in 10.4.1.2.
- Set obj.[[BoundTargetFunction]] to targetFunction.
- Set obj.[[BoundThis]] to boundThis.
- Set obj.[[BoundArguments]] to boundArgs.
- Return obj.
An Array object is an exotic object that gives special treatment to array index property keys (see 6.1.7). A property whose property name is an array index is also called an element. Every Array object has a non-configurable "length" property whose value is always a non-negative integral Number whose mathematical value is less than 232. The value of the "length" property is numerically greater than the name of every own property whose name is an array index; whenever an own property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever an own property is added whose name is an array index, the value of the "length" property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the value of the "length" property is changed, every own property whose name is an array index whose value is not smaller than the new length is deleted. This constraint applies only to own properties of an Array object and is unaffected by "length" or array index properties that may be inherited from its prototypes.
Note
A String property name P is an array index if and only if ToString(ToUint32(P)) equals P and ToUint32(P) is not the same value as 𝔽(232 - 1).
An object is an Array exotic object (or simply, an Array object) if its [[DefineOwnProperty]] internal method uses the following implementation, and its other essential internal methods use the definitions found in 10.1. These methods are installed in ArrayCreate.
The [[DefineOwnProperty]] internal method of an Array exotic object A takes arguments P (a property key) and Desc (a Property Descriptor). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If P is "length", then
- Return ? ArraySetLength(A, Desc).
- Else if P is an array index, then
- Let oldLenDesc be OrdinaryGetOwnProperty(A, "length").
- Assert: ! IsDataDescriptor(oldLenDesc) is true.
- Assert: oldLenDesc.[[Configurable]] is false.
- Let oldLen be oldLenDesc.[[Value]].
- Assert: oldLen is a non-negative integral Number.
- Let index be ! ToUint32(P).
- If index ≥ oldLen and oldLenDesc.[[Writable]] is false, return false.
- Let succeeded be ! OrdinaryDefineOwnProperty(A, P, Desc).
- If succeeded is false, return false.
- If index ≥ oldLen, then 1. Set oldLenDesc.[[Value]] to index + 1𝔽. 2. Let succeeded be OrdinaryDefineOwnProperty(A, "length", oldLenDesc). 3. Assert: succeeded is true.
- Return true.
- Return OrdinaryDefineOwnProperty(A, P, Desc).
The abstract operation ArrayCreate takes argument length (a non-negative integer) and optional argument proto. It is used to specify the creation of new Array exotic objects. It performs the following steps when called:
- If length > 232 - 1, throw a RangeError exception.
- If proto is not present, set proto to %Array.prototype%.
- Let A be ! MakeBasicObject(« [[Prototype]], [[Extensible]] »).
- Set A.[[Prototype]] to proto.
- Set A.[[DefineOwnProperty]] as specified in 10.4.2.1.
- Perform ! OrdinaryDefineOwnProperty(A, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
- Return A.
The abstract operation ArraySpeciesCreate takes arguments originalArray and length (a non-negative integer). It is used to specify the creation of a new Array object using a constructor function that is derived from originalArray. It performs the following steps when called:
- Let isArray be ? IsArray(originalArray).
- If isArray is false, return ? ArrayCreate(length).
- Let C be ? Get(originalArray, "constructor").
- If IsConstructor(C) is true, then
- Let thisRealm be the current Realm Record.
- Let realmC be ? GetFunctionRealm(C).
- If thisRealm and realmC are not the same Realm Record, then
- If Type(C) is Object, then
- If C is undefined, return ? ArrayCreate(length).
- If IsConstructor(C) is false, throw a TypeError exception.
- Return ? Construct(C, « 𝔽(length) »).
Note
If originalArray was created using the standard built-in Array constructor for a realm that is not the realm of the running execution context, then a new Array is created using the realm of the running execution context. This maintains compatibility with Web browsers that have historically had that behaviour for the Array.prototype
methods that now are defined using ArraySpeciesCreate.
The abstract operation ArraySetLength takes arguments A (an Array object) and Desc (a Property Descriptor). It performs the following steps when called:
- If Desc.[[Value]] is absent, then
- Return OrdinaryDefineOwnProperty(A, "length", Desc).
- Let newLenDesc be a copy of Desc.
- Let newLen be ? ToUint32(Desc.[[Value]]).
- Let numberLen be ? ToNumber(Desc.[[Value]]).
- If newLen is not the same value as numberLen, throw a RangeError exception.
- Set newLenDesc.[[Value]] to newLen.
- Let oldLenDesc be OrdinaryGetOwnProperty(A, "length").
- Assert: ! IsDataDescriptor(oldLenDesc) is true.
- Assert: oldLenDesc.[[Configurable]] is false.
- Let oldLen be oldLenDesc.[[Value]].
- If newLen ≥ oldLen, then 1. Return OrdinaryDefineOwnProperty(A, "length", newLenDesc).
- If oldLenDesc.[[Writable]] is false, return false.
- If newLenDesc.[[Writable]] is absent or has the value true, let newWritable be true.
- Else, 1. NOTE: Setting the [[Writable]] attribute to false is deferred in case any elements cannot be deleted. 2. Let newWritable be false. 3. Set newLenDesc.[[Writable]] to true.
- Let succeeded be ! OrdinaryDefineOwnProperty(A, "length", newLenDesc).
- If succeeded is false, return false.
- For each own property key P of A that is an array index, whose numeric value is greater than or equal to newLen, in descending numeric index order, do
1. Let deleteSucceeded be ! A.[[Delete]](P).
2. If deleteSucceeded is false, then
- Set newLenDesc.[[Value]] to ! ToUint32(P) + 1𝔽.
- If newWritable is false, set newLenDesc.[[Writable]] to false.
- Perform ! OrdinaryDefineOwnProperty(A, "length", newLenDesc).
- Return false.
- If newWritable is false, then 1. Let succeeded be ! OrdinaryDefineOwnProperty(A, "length", PropertyDescriptor { [[Writable]]: false }). 2. Assert: succeeded is true.
- Return true.
Note
In steps 3 and 4, if Desc.[[Value]] is an object then its valueOf
method is called twice. This is legacy behaviour that was specified with this effect starting with the 2nd Edition of this specification.
A String object is an exotic object that encapsulates a String value and exposes virtual integer-indexed data properties corresponding to the individual code unit elements of the String value. String exotic objects always have a data property named "length" whose value is the number of code unit elements in the encapsulated String value. Both the code unit data properties and the "length" property are non-writable and non-configurable.
An object is a String exotic object (or simply, a String object) if its [[GetOwnProperty]], [[DefineOwnProperty]], and [[OwnPropertyKeys]] internal methods use the following implementations, and its other essential internal methods use the definitions found in 10.1. These methods are installed in StringCreate.
String exotic objects have the same internal slots as ordinary objects. They also have a [[StringData]] internal slot.
The [[GetOwnProperty]] internal method of a String exotic object S takes argument P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let desc be OrdinaryGetOwnProperty(S, P).
- If desc is not undefined, return desc.
- Return ! StringGetOwnProperty(S, P).
The [[DefineOwnProperty]] internal method of a String exotic object S takes arguments P (a property key) and Desc (a Property Descriptor). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let stringDesc be ! StringGetOwnProperty(S, P).
- If stringDesc is not undefined, then
- Let extensible be S.[[Extensible]].
- Return ! IsCompatiblePropertyDescriptor(extensible, Desc, stringDesc).
- Return ! OrdinaryDefineOwnProperty(S, P, Desc).
The [[OwnPropertyKeys]] internal method of a String exotic object O takes no arguments. It performs the following steps when called:
- Let keys be a new empty List.
- Let str be O.[[StringData]].
- Assert: Type(str) is String.
- Let len be the length of str.
- For each integer i starting with 0 such that i < len, in ascending order, do
- For each own property key P of O such that P is an array index and ! ToIntegerOrInfinity(P) ≥ len, in ascending numeric index order, do
- Add P as the last element of keys.
- For each own property key P of O such that Type(P) is String and P is not an array index, in ascending chronological order of property creation, do
- Add P as the last element of keys.
- For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property creation, do
- Add P as the last element of keys.
- Return keys.
The abstract operation StringCreate takes arguments value (a String) and prototype. It is used to specify the creation of new String exotic objects. It performs the following steps when called:
- Let S be ! MakeBasicObject(« [[Prototype]], [[Extensible]], [[StringData]] »).
- Set S.[[Prototype]] to prototype.
- Set S.[[StringData]] to value.
- Set S.[[GetOwnProperty]] as specified in 10.4.3.1.
- Set S.[[DefineOwnProperty]] as specified in 10.4.3.2.
- Set S.[[OwnPropertyKeys]] as specified in 10.4.3.3.
- Let length be the number of code unit elements in value.
- Perform ! DefinePropertyOrThrow(S, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).
- Return S.
The abstract operation StringGetOwnProperty takes arguments S and P. It performs the following steps when called:
- Assert: S is an Object that has a [[StringData]] internal slot.
- Assert: IsPropertyKey(P) is true.
- If Type(P) is not String, return undefined.
- Let index be ! CanonicalNumericIndexString(P).
- If index is undefined, return undefined.
- If IsIntegralNumber(index) is false, return undefined.
- If index is -0𝔽, return undefined.
- Let str be S.[[StringData]].
- Assert: Type(str) is String.
- Let len be the length of str.
- If ℝ(index) < 0 or len ≤ ℝ(index), return undefined.
- Let resultStr be the String value of length 1, containing one code unit from str, specifically the code unit at index ℝ(index).
- Return the PropertyDescriptor { [[Value]]: resultStr, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }.
Most ECMAScript functions make an arguments object available to their code. Depending upon the characteristics of the function definition, its arguments object is either an ordinary object or an arguments exotic object. An arguments exotic object is an exotic object whose array index properties map to the formal parameters bindings of an invocation of its associated ECMAScript function.
An object is an arguments exotic object if its internal methods use the following implementations, with the ones not specified here using those found in 10.1. These methods are installed in CreateMappedArgumentsObject.
Note 1
While CreateUnmappedArgumentsObject is grouped into this clause, it creates an ordinary object, not an arguments exotic object.
Arguments exotic objects have the same internal slots as ordinary objects. They also have a [[ParameterMap]] internal slot. Ordinary arguments objects also have a [[ParameterMap]] internal slot whose value is always undefined. For ordinary argument objects the [[ParameterMap]] internal slot is only used by Object.prototype.toString
(20.1.3.6) to identify them as such.
Note 2
The integer-indexed data properties of an arguments exotic object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function's execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. If the arguments object is an ordinary object, the values of its properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.
Note 3
The ParameterMap object and its property values are used as a device for specifying the arguments object correspondence to argument bindings. The ParameterMap object and the objects that are the values of its properties are not directly observable from ECMAScript code. An ECMAScript implementation does not need to actually create or use such objects to implement the specified semantics.
Note 4
Ordinary arguments objects define a non-configurable accessor property named "callee" which throws a TypeError exception on access. The "callee" property has a more specific meaning for arguments exotic objects, which are created only for some class of non-strict functions. The definition of this property in the ordinary variant exists to ensure that it is not defined in any other manner by conforming ECMAScript implementations.
Note 5
ECMAScript implementations of arguments exotic objects have historically contained an accessor property named "caller". Prior to ECMAScript 2017, this specification included the definition of a throwing "caller" property on ordinary arguments objects. Since implementations do not contain this extension any longer, ECMAScript 2017 dropped the requirement for a throwing "caller" accessor.
The [[GetOwnProperty]] internal method of an arguments exotic object args takes argument P (a property key). It performs the following steps when called:
- Let desc be OrdinaryGetOwnProperty(args, P).
- If desc is undefined, return desc.
- Let map be args.[[ParameterMap]].
- Let isMapped be ! HasOwnProperty(map, P).
- If isMapped is true, then
- Set desc.[[Value]] to Get(map, P).
- Return desc.
The [[DefineOwnProperty]] internal method of an arguments exotic object args takes arguments P (a property key) and Desc (a Property Descriptor). It performs the following steps when called:
- Let map be args.[[ParameterMap]].
- Let isMapped be HasOwnProperty(map, P).
- Let newArgDesc be Desc.
- If isMapped is true and IsDataDescriptor(Desc) is true, then
- If Desc.[[Value]] is not present and Desc.[[Writable]] is present and its value is false, then
- Set newArgDesc to a copy of Desc.
- Set newArgDesc.[[Value]] to Get(map, P).
- If Desc.[[Value]] is not present and Desc.[[Writable]] is present and its value is false, then
- Let allowed be ? OrdinaryDefineOwnProperty(args, P, newArgDesc).
- If allowed is false, return false.
- If isMapped is true, then
- If IsAccessorDescriptor(Desc) is true, then
- Call map.[[Delete]](P).
- Else,
- If IsAccessorDescriptor(Desc) is true, then
- Return true.
The [[Get]] internal method of an arguments exotic object args takes arguments P (a property key) and Receiver (an ECMAScript language value). It performs the following steps when called:
- Let map be args.[[ParameterMap]].
- Let isMapped be ! HasOwnProperty(map, P).
- If isMapped is false, then
- Return ? OrdinaryGet(args, P, Receiver).
- Else,
The [[Set]] internal method of an arguments exotic object args takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value). It performs the following steps when called:
- If SameValue(args, Receiver) is false, then
- Let isMapped be false.
- Else,
- Let map be args.[[ParameterMap]].
- Let isMapped be ! HasOwnProperty(map, P).
- If isMapped is true, then
- Return ? OrdinarySet(args, P, V, Receiver).
The [[Delete]] internal method of an arguments exotic object args takes argument P (a property key). It performs the following steps when called:
- Let map be args.[[ParameterMap]].
- Let isMapped be ! HasOwnProperty(map, P).
- Let result be ? OrdinaryDelete(args, P).
- If result is true and isMapped is true, then
- Call map.[[Delete]](P).
- Return result.
The abstract operation CreateUnmappedArgumentsObject takes argument argumentsList. It performs the following steps when called:
- Let len be the number of elements in argumentsList.
- Let obj be ! OrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »).
- Set obj.[[ParameterMap]] to undefined.
- Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
- Let index be 0.
- Repeat, while index < len,
- Let val be argumentsList[index].
- Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val).
- Set index to index + 1.
- Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
- Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false }).
- Return obj.
The abstract operation CreateMappedArgumentsObject takes arguments func (an Object), formals (a Parse Node), argumentsList (a List), and env (an Environment Record). It performs the following steps when called:
- Assert: formals does not contain a rest parameter, any binding patterns, or any initializers. It may contain duplicate identifiers.
- Let len be the number of elements in argumentsList.
- Let obj be ! MakeBasicObject(« [[Prototype]], [[Extensible]], [[ParameterMap]] »).
- Set obj.[[GetOwnProperty]] as specified in 10.4.4.1.
- Set obj.[[DefineOwnProperty]] as specified in 10.4.4.2.
- Set obj.[[Get]] as specified in 10.4.4.3.
- Set obj.[[Set]] as specified in 10.4.4.4.
- Set obj.[[Delete]] as specified in 10.4.4.5.
- Set obj.[[Prototype]] to %Object.prototype%.
- Let map be ! OrdinaryObjectCreate(null).
- Set obj.[[ParameterMap]] to map.
- Let parameterNames be the BoundNames of formals.
- Let numberOfParameters be the number of elements in parameterNames.
- Let index be 0.
- Repeat, while index < len, 1. Let val be argumentsList[index]. 2. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val). 3. Set index to index + 1.
- Perform ! DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
- Let mappedNames be a new empty List.
- Let index be numberOfParameters - 1.
- Repeat, while index ≥ 0,
1. Let name be parameterNames[index].
2. If name is not an element of mappedNames, then
- Add name as an element of the list mappedNames.
- If index < len, then
- Let g be MakeArgGetter(name, env).
- Let p be MakeArgSetter(name, env).
- Perform map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: p, [[Get]]: g, [[Enumerable]]: false, [[Configurable]]: true }). 3. Set index to index - 1.
- Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
- Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
- Return obj.
The abstract operation MakeArgGetter takes arguments name (a String) and env (an Environment Record). It creates a built-in function object that when executed returns the value bound for name in env. It performs the following steps when called:
- Let steps be the steps of an ArgGetter function as specified below.
- Let length be the number of non-optional parameters of an ArgGetter function as specified below.
- Let getter be ! CreateBuiltinFunction(steps, length, "", « [[Name]], [[Env]] »).
- Set getter.[[Name]] to name.
- Set getter.[[Env]] to env.
- Return getter.
An ArgGetter function is an anonymous built-in function with [[Name]] and [[Env]] internal slots. When an ArgGetter function that expects no arguments is called it performs the following steps:
- Let f be the active function object.
- Let name be f.[[Name]].
- Let env be f.[[Env]].
- Return env.GetBindingValue(name, false).
Note
ArgGetter functions are never directly accessible to ECMAScript code.
The abstract operation MakeArgSetter takes arguments name (a String) and env (an Environment Record). It creates a built-in function object that when executed sets the value bound for name in env. It performs the following steps when called:
- Let steps be the steps of an ArgSetter function as specified below.
- Let length be the number of non-optional parameters of an ArgSetter function as specified below.
- Let setter be ! CreateBuiltinFunction(steps, length, "", « [[Name]], [[Env]] »).
- Set setter.[[Name]] to name.
- Set setter.[[Env]] to env.
- Return setter.
An ArgSetter function is an anonymous built-in function with [[Name]] and [[Env]] internal slots. When an ArgSetter function is called with argument value it performs the following steps:
- Let f be the active function object.
- Let name be f.[[Name]].
- Let env be f.[[Env]].
- Return env.SetMutableBinding(name, value, false).
Note
ArgSetter functions are never directly accessible to ECMAScript code.
An Integer-Indexed exotic object is an exotic object that performs special handling of integer index property keys.
Integer-Indexed exotic objects have the same internal slots as ordinary objects and additionally [[ViewedArrayBuffer]], [[ArrayLength]], [[ByteOffset]], [[ContentType]], and [[TypedArrayName]] internal slots.
An object is an Integer-Indexed exotic object if its [[GetOwnProperty]], [[HasProperty]], [[DefineOwnProperty]], [[Get]], [[Set]], [[Delete]], and [[OwnPropertyKeys]] internal methods use the definitions in this section, and its other essential internal methods use the definitions found in 10.1. These methods are installed by IntegerIndexedObjectCreate.
The [[GetOwnProperty]] internal method of an Integer-Indexed exotic object O takes argument P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Assert: O is an Integer-Indexed exotic object.
- If Type(P) is String, then
- Let numericIndex be ! CanonicalNumericIndexString(P).
- If numericIndex is not undefined, then
- Let value be ! IntegerIndexedElementGet(O, numericIndex).
- If value is undefined, return undefined.
- Return the PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
- Return OrdinaryGetOwnProperty(O, P).
The [[HasProperty]] internal method of an Integer-Indexed exotic object O takes argument P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Assert: O is an Integer-Indexed exotic object.
- If Type(P) is String, then
- Let numericIndex be ! CanonicalNumericIndexString(P).
- If numericIndex is not undefined, return ! IsValidIntegerIndex(O, numericIndex).
- Return ? OrdinaryHasProperty(O, P).
The [[DefineOwnProperty]] internal method of an Integer-Indexed exotic object O takes arguments P (a property key) and Desc (a Property Descriptor). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Assert: O is an Integer-Indexed exotic object.
- If Type(P) is String, then
- Let numericIndex be ! CanonicalNumericIndexString(P).
- If numericIndex is not undefined, then
- If ! IsValidIntegerIndex(O, numericIndex) is false, return false.
- If Desc has a [[Configurable]] field and if Desc.[[Configurable]] is false, return false.
- If Desc has an [[Enumerable]] field and if Desc.[[Enumerable]] is false, return false.
- If ! IsAccessorDescriptor(Desc) is true, return false.
- If Desc has a [[Writable]] field and if Desc.[[Writable]] is false, return false.
- If Desc has a [[Value]] field, perform ? IntegerIndexedElementSet(O, numericIndex, Desc.[[Value]]).
- Return true.
- Return ! OrdinaryDefineOwnProperty(O, P, Desc).
The [[Get]] internal method of an Integer-Indexed exotic object O takes arguments P (a property key) and Receiver (an ECMAScript language value). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If Type(P) is String, then
- Let numericIndex be ! CanonicalNumericIndexString(P).
- If numericIndex is not undefined, then
- Return ! IntegerIndexedElementGet(O, numericIndex).
- Return ? OrdinaryGet(O, P, Receiver).
The [[Set]] internal method of an Integer-Indexed exotic object O takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If Type(P) is String, then
- Let numericIndex be ! CanonicalNumericIndexString(P).
- If numericIndex is not undefined, then
- Perform ? IntegerIndexedElementSet(O, numericIndex, V).
- Return true.
- Return ? OrdinarySet(O, P, V, Receiver).
The [[Delete]] internal method of an Integer-Indexed exotic object O takes arguments P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Assert: O is an Integer-Indexed exotic object.
- If Type(P) is String, then
- Let numericIndex be ! CanonicalNumericIndexString(P).
- If numericIndex is not undefined, then
- If ! IsValidIntegerIndex(O, numericIndex) is false, return true; else return false.
- Return ? OrdinaryDelete(O, P).
The [[OwnPropertyKeys]] internal method of an Integer-Indexed exotic object O takes no arguments. It performs the following steps when called:
- Let keys be a new empty List.
- Assert: O is an Integer-Indexed exotic object.
- If IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is false, then
- For each own property key P of O such that Type(P) is String and P is not an integer index, in ascending chronological order of property creation, do
- Add P as the last element of keys.
- For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property creation, do
- Add P as the last element of keys.
- Return keys.
The abstract operation IntegerIndexedObjectCreate takes argument prototype. It is used to specify the creation of new Integer-Indexed exotic objects. It performs the following steps when called:
- Let internalSlotsList be « [[Prototype]], [[Extensible]], [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] ».
- Let A be ! MakeBasicObject(internalSlotsList).
- Set A.[[GetOwnProperty]] as specified in 10.4.5.1.
- Set A.[[HasProperty]] as specified in 10.4.5.2.
- Set A.[[DefineOwnProperty]] as specified in 10.4.5.3.
- Set A.[[Get]] as specified in 10.4.5.4.
- Set A.[[Set]] as specified in 10.4.5.5.
- Set A.[[Delete]] as specified in 10.4.5.6.
- Set A.[[OwnPropertyKeys]] as specified in 10.4.5.7.
- Set A.[[Prototype]] to prototype.
- Return A.
The abstract operation IsValidIntegerIndex takes arguments O and index (a Number). It performs the following steps when called:
- Assert: O is an Integer-Indexed exotic object.
- If IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is true, return false.
- If ! IsIntegralNumber(index) is false, return false.
- If index is -0𝔽, return false.
- If ℝ(index) < 0 or ℝ(index) ≥ O.[[ArrayLength]], return false.
- Return true.
The abstract operation IntegerIndexedElementGet takes arguments O and index (a Number). It performs the following steps when called:
- Assert: O is an Integer-Indexed exotic object.
- If ! IsValidIntegerIndex(O, index) is false, return undefined.
- Let offset be O.[[ByteOffset]].
- Let arrayTypeName be the String value of O.[[TypedArrayName]].
- Let elementSize be the Element Size value specified in Table 60 for arrayTypeName.
- Let indexedPosition be (ℝ(index) × elementSize) + offset.
- Let elementType be the Element Type value in Table 60 for arrayTypeName.
- Return GetValueFromBuffer(O.[[ViewedArrayBuffer]], indexedPosition, elementType, true, Unordered).
The abstract operation IntegerIndexedElementSet takes arguments O, index (a Number), and value. It performs the following steps when called:
- Assert: O is an Integer-Indexed exotic object.
- If O.[[ContentType]] is BigInt, let numValue be ? ToBigInt(value).
- Otherwise, let numValue be ? ToNumber(value).
- If ! IsValidIntegerIndex(O, index) is true, then
- Let offset be O.[[ByteOffset]].
- Let arrayTypeName be the String value of O.[[TypedArrayName]].
- Let elementSize be the Element Size value specified in Table 60 for arrayTypeName.
- Let indexedPosition be (ℝ(index) × elementSize) + offset.
- Let elementType be the Element Type value in Table 60 for arrayTypeName.
- Perform SetValueInBuffer(O.[[ViewedArrayBuffer]], indexedPosition, elementType, numValue, true, Unordered).
- Return NormalCompletion(undefined).
Note
This operation always appears to succeed, but it has no effect when attempting to write past the end of a TypedArray or to a TypedArray which is backed by a detached ArrayBuffer.
A module namespace exotic object is an exotic object that exposes the bindings exported from an ECMAScript Module (See 16.2.3). There is a one-to-one correspondence between the String-keyed own properties of a module namespace exotic object and the binding names exported by the Module. The exported bindings include any bindings that are indirectly exported using export *
export items. Each String-valued own property key is the StringValue of the corresponding exported binding name. These are the only String-keyed properties of a module namespace exotic object. Each such property has the attributes { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }. Module namespace exotic objects are not extensible.
An object is a module namespace exotic object if its [[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]], [[GetOwnProperty]], [[DefineOwnProperty]], [[HasProperty]], [[Get]], [[Set]], [[Delete]], and [[OwnPropertyKeys]] internal methods use the definitions in this section, and its other essential internal methods use the definitions found in 10.1. These methods are installed by ModuleNamespaceCreate.
Module namespace exotic objects have the internal slots defined in Table 31.
Table 31: Internal Slots of Module Namespace Exotic Objects
Internal Slot | Type | Description |
---|---|---|
[[Module]] | Module Record | The Module Record whose exports this namespace exposes. |
[[Exports]] | List of String | A List whose elements are the String values of the exported names exposed as own properties of this object. The list is ordered as if an Array of those String values had been sorted using %Array.prototype.sort% using undefined as comparefn. |
[[Prototype]] | Null | This slot always contains the value null (see 10.4.6.1). |
Module namespace exotic objects provide alternative definitions for all of the internal methods except [[GetPrototypeOf]], which behaves as defined in 10.1.1.
The [[SetPrototypeOf]] internal method of a module namespace exotic object O takes argument V (an Object or null). It performs the following steps when called:
- Return ? SetImmutablePrototype(O, V).
The [[IsExtensible]] internal method of a module namespace exotic object takes no arguments. It performs the following steps when called:
- Return false.
The [[PreventExtensions]] internal method of a module namespace exotic object takes no arguments. It performs the following steps when called:
- Return true.
The [[GetOwnProperty]] internal method of a module namespace exotic object O takes argument P (a property key). It performs the following steps when called:
- If Type(P) is Symbol, return OrdinaryGetOwnProperty(O, P).
- Let exports be O.[[Exports]].
- If P is not an element of exports, return undefined.
- Let value be ? O.[[Get]](P, O).
- Return PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }.
The [[DefineOwnProperty]] internal method of a module namespace exotic object O takes arguments P (a property key) and Desc (a Property Descriptor). It performs the following steps when called:
- If Type(P) is Symbol, return OrdinaryDefineOwnProperty(O, P, Desc).
- Let current be ? O.[[GetOwnProperty]](P).
- If current is undefined, return false.
- If Desc.[[Configurable]] is present and has value true, return false.
- If Desc.[[Enumerable]] is present and has value false, return false.
- If ! IsAccessorDescriptor(Desc) is true, return false.
- If Desc.[[Writable]] is present and has value false, return false.
- If Desc.[[Value]] is present, return SameValue(Desc.[[Value]], current.[[Value]]).
- Return true.
The [[HasProperty]] internal method of a module namespace exotic object O takes argument P (a property key). It performs the following steps when called:
- If Type(P) is Symbol, return OrdinaryHasProperty(O, P).
- Let exports be O.[[Exports]].
- If P is an element of exports, return true.
- Return false.
The [[Get]] internal method of a module namespace exotic object O takes arguments P (a property key) and Receiver (an ECMAScript language value). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If Type(P) is Symbol, then
- Return ? OrdinaryGet(O, P, Receiver).
- Let exports be O.[[Exports]].
- If P is not an element of exports, return undefined.
- Let m be O.[[Module]].
- Let binding be ! m.ResolveExport(P).
- Assert: binding is a ResolvedBinding Record.
- Let targetModule be binding.[[Module]].
- Assert: targetModule is not undefined.
- If binding.[[BindingName]] is "*namespace*", then 1. Return ? GetModuleNamespace(targetModule).
- Let targetEnv be targetModule.[[Environment]].
- If targetEnv is undefined, throw a ReferenceError exception.
- Return ? targetEnv.GetBindingValue(binding.[[BindingName]], true).
Note
ResolveExport is side-effect free. Each time this operation is called with a specific exportName, resolveSet pair as arguments it must return the same result. An implementation might choose to pre-compute or cache the ResolveExport results for the [[Exports]] of each module namespace exotic object.
The [[Set]] internal method of a module namespace exotic object takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value). It performs the following steps when called:
- Return false.
The [[Delete]] internal method of a module namespace exotic object O takes argument P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- If Type(P) is Symbol, then
- Return ? OrdinaryDelete(O, P).
- Let exports be O.[[Exports]].
- If P is an element of exports, return false.
- Return true.
The [[OwnPropertyKeys]] internal method of a module namespace exotic object O takes no arguments. It performs the following steps when called:
- Let exports be a copy of O.[[Exports]].
- Let symbolKeys be ! OrdinaryOwnPropertyKeys(O).
- Append all the entries of symbolKeys to the end of exports.
- Return exports.
The abstract operation ModuleNamespaceCreate takes arguments module and exports. It is used to specify the creation of new module namespace exotic objects. It performs the following steps when called:
- Assert: module is a Module Record.
- Assert: module.[[Namespace]] is undefined.
- Assert: exports is a List of String values.
- Let internalSlotsList be the internal slots listed in Table 31.
- Let M be ! MakeBasicObject(internalSlotsList).
- Set M's essential internal methods to the definitions specified in 10.4.6.
- Set M.[[Prototype]] to null.
- Set M.[[Module]] to module.
- Let sortedExports be a List whose elements are the elements of exports ordered as if an Array of the same values had been sorted using %Array.prototype.sort% using undefined as comparefn.
- Set M.[[Exports]] to sortedExports.
- Create own properties of M corresponding to the definitions in 28.3.
- Set module.[[Namespace]] to M.
- Return M.
An immutable prototype exotic object is an exotic object that has a [[Prototype]] internal slot that will not change once it is initialized.
An object is an immutable prototype exotic object if its [[SetPrototypeOf]] internal method uses the following implementation. (Its other essential internal methods may use any implementation, depending on the specific immutable prototype exotic object in question.)
Note
Unlike other exotic objects, there is not a dedicated creation abstract operation provided for immutable prototype exotic objects. This is because they are only used by %Object.prototype% and by host environments, and in host environments, the relevant objects are potentially exotic in other ways and thus need their own dedicated creation operation.
The [[SetPrototypeOf]] internal method of an immutable prototype exotic object O takes argument V (an Object or null). It performs the following steps when called:
- Return ? SetImmutablePrototype(O, V).
The abstract operation SetImmutablePrototype takes arguments O and V. It performs the following steps when called:
- Assert: Either Type(V) is Object or Type(V) is Null.
- Let current be ? O.[[GetPrototypeOf]]().
- If SameValue(V, current) is true, return true.
- Return false.
A proxy object is an exotic object whose essential internal methods are partially implemented using ECMAScript code. Every proxy object has an internal slot called [[ProxyHandler]]. The value of [[ProxyHandler]] is an object, called the proxy's handler object, or null. Methods (see Table 32) of a handler object may be used to augment the implementation for one or more of the proxy object's internal methods. Every proxy object also has an internal slot called [[ProxyTarget]] whose value is either an object or the null value. This object is called the proxy's target object.
An object is a Proxy exotic object if its essential internal methods (including [[Call]] and [[Construct]], if applicable) use the definitions in this section. These internal methods are installed in ProxyCreate.
Table 32: Proxy Handler Methods
Internal Method | Handler Method |
---|---|
[[GetPrototypeOf]] | getPrototypeOf |
[[SetPrototypeOf]] | setPrototypeOf |
[[IsExtensible]] | isExtensible |
[[PreventExtensions]] | preventExtensions |
[[GetOwnProperty]] | getOwnPropertyDescriptor |
[[DefineOwnProperty]] | defineProperty |
[[HasProperty]] | has |
[[Get]] | get |
[[Set]] | set |
[[Delete]] | deleteProperty |
[[OwnPropertyKeys]] | ownKeys |
[[Call]] | apply |
[[Construct]] | construct |
When a handler method is called to provide the implementation of a proxy object internal method, the handler method is passed the proxy's target object as a parameter. A proxy's handler object does not necessarily have a method corresponding to every essential internal method. Invoking an internal method on the proxy results in the invocation of the corresponding internal method on the proxy's target object if the handler object does not have a method corresponding to the internal trap.
The [[ProxyHandler]] and [[ProxyTarget]] internal slots of a proxy object are always initialized when the object is created and typically may not be modified. Some proxy objects are created in a manner that permits them to be subsequently revoked. When a proxy is revoked, its [[ProxyHandler]] and [[ProxyTarget]] internal slots are set to null causing subsequent invocations of internal methods on that proxy object to throw a TypeError exception.
Because proxy objects permit the implementation of internal methods to be provided by arbitrary ECMAScript code, it is possible to define a proxy object whose handler methods violates the invariants defined in 6.1.7.3. Some of the internal method invariants defined in 6.1.7.3 are essential integrity invariants. These invariants are explicitly enforced by the proxy object internal methods specified in this section. An ECMAScript implementation must be robust in the presence of all possible invariant violations.
In the following algorithm descriptions, assume O is an ECMAScript proxy object, P is a property key value, V is any ECMAScript language value and Desc is a Property Descriptor record.
The [[GetPrototypeOf]] internal method of a Proxy exotic object O takes no arguments. It performs the following steps when called:
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "getPrototypeOf").
- If trap is undefined, then
- Return ? target.[[GetPrototypeOf]]().
- Let handlerProto be ? Call(trap, handler, « target »).
- If Type(handlerProto) is neither Object nor Null, throw a TypeError exception.
- Let extensibleTarget be ? IsExtensible(target).
- If extensibleTarget is true, return handlerProto.
- Let targetProto be ? target.[[GetPrototypeOf]]().
- If SameValue(handlerProto, targetProto) is false, throw a TypeError exception.
- Return handlerProto.
Note
[[GetPrototypeOf]] for proxy objects enforces the following invariants:
- The result of [[GetPrototypeOf]] must be either an Object or null.
- If the target object is not extensible, [[GetPrototypeOf]] applied to the proxy object must return the same value as [[GetPrototypeOf]] applied to the proxy object's target object.
The [[SetPrototypeOf]] internal method of a Proxy exotic object O takes argument V (an Object or null). It performs the following steps when called:
- Assert: Either Type(V) is Object or Type(V) is Null.
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "setPrototypeOf").
- If trap is undefined, then
- Return ? target.[[SetPrototypeOf]](V).
- Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, V »)).
- If booleanTrapResult is false, return false.
- Let extensibleTarget be ? IsExtensible(target).
- If extensibleTarget is true, return true.
- Let targetProto be ? target.[[GetPrototypeOf]]().
- If SameValue(V, targetProto) is false, throw a TypeError exception.
- Return true.
Note
[[SetPrototypeOf]] for proxy objects enforces the following invariants:
- The result of [[SetPrototypeOf]] is a Boolean value.
- If the target object is not extensible, the argument value must be the same as the result of [[GetPrototypeOf]] applied to target object.
The [[IsExtensible]] internal method of a Proxy exotic object O takes no arguments. It performs the following steps when called:
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "isExtensible").
- If trap is undefined, then
- Return ? IsExtensible(target).
- Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target »)).
- Let targetResult be ? IsExtensible(target).
- If SameValue(booleanTrapResult, targetResult) is false, throw a TypeError exception.
- Return booleanTrapResult.
Note
[[IsExtensible]] for proxy objects enforces the following invariants:
- The result of [[IsExtensible]] is a Boolean value.
- [[IsExtensible]] applied to the proxy object must return the same value as [[IsExtensible]] applied to the proxy object's target object with the same argument.
The [[PreventExtensions]] internal method of a Proxy exotic object O takes no arguments. It performs the following steps when called:
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "preventExtensions").
- If trap is undefined, then
- Return ? target.[[PreventExtensions]]().
- Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target »)).
- If booleanTrapResult is true, then
- Let extensibleTarget be ? IsExtensible(target).
- If extensibleTarget is true, throw a TypeError exception.
- Return booleanTrapResult.
Note
[[PreventExtensions]] for proxy objects enforces the following invariants:
- The result of [[PreventExtensions]] is a Boolean value.
- [[PreventExtensions]] applied to the proxy object only returns true if [[IsExtensible]] applied to the proxy object's target object is false.
The [[GetOwnProperty]] internal method of a Proxy exotic object O takes argument P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "getOwnPropertyDescriptor").
- If trap is undefined, then
- Return ? target.[[GetOwnProperty]](P).
- Let trapResultObj be ? Call(trap, handler, « target, P »).
- If Type(trapResultObj) is neither Object nor Undefined, throw a TypeError exception.
- Let targetDesc be ? target.[[GetOwnProperty]](P).
- If trapResultObj is undefined, then 1. If targetDesc is undefined, return undefined. 2. If targetDesc.[[Configurable]] is false, throw a TypeError exception. 3. Let extensibleTarget be ? IsExtensible(target). 4. If extensibleTarget is false, throw a TypeError exception. 5. Return undefined.
- Let extensibleTarget be ? IsExtensible(target).
- Let resultDesc be ? ToPropertyDescriptor(trapResultObj).
- Call CompletePropertyDescriptor(resultDesc).
- Let valid be IsCompatiblePropertyDescriptor(extensibleTarget, resultDesc, targetDesc).
- If valid is false, throw a TypeError exception.
- If resultDesc.[[Configurable]] is false, then
1. If targetDesc is undefined or targetDesc.[[Configurable]] is true, then
- Throw a TypeError exception. 2. If resultDesc has a [[Writable]] field and resultDesc.[[Writable]] is false, then
- If targetDesc.[[Writable]] is true, throw a TypeError exception.
- Return resultDesc.
Note
[[GetOwnProperty]] for proxy objects enforces the following invariants:
- The result of [[GetOwnProperty]] must be either an Object or undefined.
- A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
- A property cannot be reported as non-existent, if the target object is not extensible, unless it does not exist as an own property of the target object.
- A property cannot be reported as existent, if the target object is not extensible, unless it exists as an own property of the target object.
- A property cannot be reported as non-configurable, unless it exists as a non-configurable own property of the target object.
- A property cannot be reported as both non-configurable and non-writable, unless it exists as a non-configurable, non-writable own property of the target object.
The [[DefineOwnProperty]] internal method of a Proxy exotic object O takes arguments P (a property key) and Desc (a Property Descriptor). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "defineProperty").
- If trap is undefined, then
- Return ? target.[[DefineOwnProperty]](P, Desc).
- Let descObj be FromPropertyDescriptor(Desc).
- Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P, descObj »)).
- If booleanTrapResult is false, return false.
- Let targetDesc be ? target.[[GetOwnProperty]](P).
- Let extensibleTarget be ? IsExtensible(target).
- If Desc has a [[Configurable]] field and if Desc.[[Configurable]] is false, then 1. Let settingConfigFalse be true.
- Else, let settingConfigFalse be false.
- If targetDesc is undefined, then 1. If extensibleTarget is false, throw a TypeError exception. 2. If settingConfigFalse is true, throw a TypeError exception.
- Else,
1. If IsCompatiblePropertyDescriptor(extensibleTarget, Desc, targetDesc) is false, throw a TypeError exception.
2. If settingConfigFalse is true and targetDesc.[[Configurable]] is true, throw a TypeError exception.
3. If IsDataDescriptor(targetDesc) is true, targetDesc.[[Configurable]] is false, and targetDesc.[[Writable]] is true, then
- If Desc has a [[Writable]] field and Desc.[[Writable]] is false, throw a TypeError exception.
- Return true.
Note
[[DefineOwnProperty]] for proxy objects enforces the following invariants:
- The result of [[DefineOwnProperty]] is a Boolean value.
- A property cannot be added, if the target object is not extensible.
- A property cannot be non-configurable, unless there exists a corresponding non-configurable own property of the target object.
- A non-configurable property cannot be non-writable, unless there exists a corresponding non-configurable, non-writable own property of the target object.
- If a property has a corresponding target object property then applying the Property Descriptor of the property to the target object using [[DefineOwnProperty]] will not throw an exception.
The [[HasProperty]] internal method of a Proxy exotic object O takes argument P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "has").
- If trap is undefined, then
- Return ? target.[[HasProperty]](P).
- Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P »)).
- If booleanTrapResult is false, then
- Let targetDesc be ? target.[[GetOwnProperty]](P).
- If targetDesc is not undefined, then
- If targetDesc.[[Configurable]] is false, throw a TypeError exception.
- Let extensibleTarget be ? IsExtensible(target).
- If extensibleTarget is false, throw a TypeError exception.
- Return booleanTrapResult.
Note
[[HasProperty]] for proxy objects enforces the following invariants:
- The result of [[HasProperty]] is a Boolean value.
- A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
- A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
The [[Get]] internal method of a Proxy exotic object O takes arguments P (a property key) and Receiver (an ECMAScript language value). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "get").
- If trap is undefined, then
- Return ? target.[[Get]](P, Receiver).
- Let trapResult be ? Call(trap, handler, « target, P, Receiver »).
- Let targetDesc be ? target.[[GetOwnProperty]](P).
- If targetDesc is not undefined and targetDesc.[[Configurable]] is false, then
1. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]] is false, then
- If SameValue(trapResult, targetDesc.[[Value]]) is false, throw a TypeError exception. 2. If IsAccessorDescriptor(targetDesc) is true and targetDesc.[[Get]] is undefined, then
- If trapResult is not undefined, throw a TypeError exception.
- Return trapResult.
Note
[[Get]] for proxy objects enforces the following invariants:
- The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property.
- The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[Get]] attribute.
The [[Set]] internal method of a Proxy exotic object O takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "set").
- If trap is undefined, then
- Return ? target.[[Set]](P, V, Receiver).
- Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P, V, Receiver »)).
- If booleanTrapResult is false, return false.
- Let targetDesc be ? target.[[GetOwnProperty]](P).
- If targetDesc is not undefined and targetDesc.[[Configurable]] is false, then
1. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]] is false, then
- If SameValue(V, targetDesc.[[Value]]) is false, throw a TypeError exception. 2. If IsAccessorDescriptor(targetDesc) is true, then
- If targetDesc.[[Set]] is undefined, throw a TypeError exception.
- Return true.
Note
[[Set]] for proxy objects enforces the following invariants:
- The result of [[Set]] is a Boolean value.
- Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable own data property.
- Cannot set the value of a property if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[Set]] attribute.
The [[Delete]] internal method of a Proxy exotic object O takes argument P (a property key). It performs the following steps when called:
- Assert: IsPropertyKey(P) is true.
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "deleteProperty").
- If trap is undefined, then
- Return ? target.[[Delete]](P).
- Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P »)).
- If booleanTrapResult is false, return false.
- Let targetDesc be ? target.[[GetOwnProperty]](P).
- If targetDesc is undefined, return true.
- If targetDesc.[[Configurable]] is false, throw a TypeError exception.
- Let extensibleTarget be ? IsExtensible(target).
- If extensibleTarget is false, throw a TypeError exception.
- Return true.
Note
[[Delete]] for proxy objects enforces the following invariants:
- The result of [[Delete]] is a Boolean value.
- A property cannot be reported as deleted, if it exists as a non-configurable own property of the target object.
- A property cannot be reported as deleted, if it exists as an own property of the target object and the target object is non-extensible.
The [[OwnPropertyKeys]] internal method of a Proxy exotic object O takes no arguments. It performs the following steps when called:
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "ownKeys").
- If trap is undefined, then
- Return ? target.[[OwnPropertyKeys]]().
- Let trapResultArray be ? Call(trap, handler, « target »).
- Let trapResult be ? CreateListFromArrayLike(trapResultArray, « String, Symbol »).
- If trapResult contains any duplicate entries, throw a TypeError exception.
- Let extensibleTarget be ? IsExtensible(target).
- Let targetKeys be ? target.[[OwnPropertyKeys]]().
- Assert: targetKeys is a List whose elements are only String and Symbol values.
- Assert: targetKeys contains no duplicate entries.
- Let targetConfigurableKeys be a new empty List.
- Let targetNonconfigurableKeys be a new empty List.
- For each element key of targetKeys, do
1. Let desc be ? target.[[GetOwnProperty]](key).
2. If desc is not undefined and desc.[[Configurable]] is false, then
- Append key as an element of targetNonconfigurableKeys. 3. Else,
- Append key as an element of targetConfigurableKeys.
- If extensibleTarget is true and targetNonconfigurableKeys is empty, then 1. Return trapResult.
- Let uncheckedResultKeys be a List whose elements are the elements of trapResult.
- For each element key of targetNonconfigurableKeys, do 1. If key is not an element of uncheckedResultKeys, throw a TypeError exception. 2. Remove key from uncheckedResultKeys.
- If extensibleTarget is true, return trapResult.
- For each element key of targetConfigurableKeys, do 1. If key is not an element of uncheckedResultKeys, throw a TypeError exception. 2. Remove key from uncheckedResultKeys.
- If uncheckedResultKeys is not empty, throw a TypeError exception.
- Return trapResult.
Note
[[OwnPropertyKeys]] for proxy objects enforces the following invariants:
- The result of [[OwnPropertyKeys]] is a List.
- The returned List contains no duplicate entries.
- The Type of each result List element is either String or Symbol.
- The result List must contain the keys of all non-configurable own properties of the target object.
- If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.
The [[Call]] internal method of a Proxy exotic object O takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values). It performs the following steps when called:
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Let trap be ? GetMethod(handler, "apply").
- If trap is undefined, then
- Return ? Call(target, thisArgument, argumentsList).
- Let argArray be ! CreateArrayFromList(argumentsList).
- Return ? Call(trap, handler, « target, thisArgument, argArray »).
Note
A Proxy exotic object only has a [[Call]] internal method if the initial value of its [[ProxyTarget]] internal slot is an object that has a [[Call]] internal method.
The [[Construct]] internal method of a Proxy exotic object O takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor). It performs the following steps when called:
- Let handler be O.[[ProxyHandler]].
- If handler is null, throw a TypeError exception.
- Assert: Type(handler) is Object.
- Let target be O.[[ProxyTarget]].
- Assert: IsConstructor(target) is true.
- Let trap be ? GetMethod(handler, "construct").
- If trap is undefined, then
- Return ? Construct(target, argumentsList, newTarget).
- Let argArray be ! CreateArrayFromList(argumentsList).
- Let newObj be ? Call(trap, handler, « target, argArray, newTarget »).
- If Type(newObj) is not Object, throw a TypeError exception.
- Return newObj.
Note 1
A Proxy exotic object only has a [[Construct]] internal method if the initial value of its [[ProxyTarget]] internal slot is an object that has a [[Construct]] internal method.
Note 2
[[Construct]] for proxy objects enforces the following invariants:
- The result of [[Construct]] must be an Object.
The abstract operation ProxyCreate takes arguments target and handler. It is used to specify the creation of new Proxy exotic objects. It performs the following steps when called:
- If Type(target) is not Object, throw a TypeError exception.
- If Type(handler) is not Object, throw a TypeError exception.
- Let P be ! MakeBasicObject(« [[ProxyHandler]], [[ProxyTarget]] »).
- Set P's essential internal methods, except for [[Call]] and [[Construct]], to the definitions specified in 10.5.
- If IsCallable(target) is true, then
- Set P.[[Call]] as specified in 10.5.12.
- If IsConstructor(target) is true, then
- Set P.[[Construct]] as specified in 10.5.13.
- Set P.[[ProxyTarget]] to target.
- Set P.[[ProxyHandler]] to handler.
- Return P.
SourceCharacter :: any Unicode code point
ECMAScript code is expressed using Unicode. ECMAScript source text is a sequence of code points. All Unicode code point values from U+0000 to U+10FFFF, including surrogate code points, may occur in source text where permitted by the ECMAScript grammars. The actual encodings used to store and interchange ECMAScript source text is not relevant to this specification. Regardless of the external source text encoding, a conforming ECMAScript implementation processes the source text as if it was an equivalent sequence of SourceCharacter values, each SourceCharacter being a Unicode code point. Conforming ECMAScript implementations are not required to perform any normalization of source text, or behave as though they were performing normalization of source text.
The components of a combining character sequence are treated as individual Unicode code points even though a user might think of the whole sequence as a single character.
Note
In string literals, regular expression literals, template literals and identifiers, any Unicode code point may also be expressed using Unicode escape sequences that explicitly express a code point's numeric value. Within a comment, such an escape sequence is effectively ignored as part of the comment.
ECMAScript differs from the Java programming language in the behaviour of Unicode escape sequences. In a Java program, if the Unicode escape sequence \u000A
, for example, occurs within a single-line comment, it is interpreted as a line terminator (Unicode code point U+000A is LINE FEED (LF)) and therefore the next code point is not part of the comment. Similarly, if the Unicode escape sequence \u000A
occurs within a string literal in a Java program, it is likewise interpreted as a line terminator, which is not allowed within a string literal—one must write \n
instead of \u000A
to cause a LINE FEED (LF) to be part of the String value of a string literal. In an ECMAScript program, a Unicode escape sequence occurring within a comment is never interpreted and therefore cannot contribute to termination of the comment. Similarly, a Unicode escape sequence occurring within a string literal in an ECMAScript program always contributes to the literal and is never interpreted as a line terminator or as a code point that might terminate the string literal.
The abstract operation UTF16EncodeCodePoint takes argument cp (a Unicode code point). It performs the following steps when called:
- Assert: 0 ≤ cp ≤ 0x10FFFF.
- If cp ≤ 0xFFFF, return the String value consisting of the code unit whose value is cp.
- Let cu1 be the code unit whose value is floor((cp - 0x10000) / 0x400) + 0xD800.
- Let cu2 be the code unit whose value is ((cp - 0x10000) modulo 0x400) + 0xDC00.
- Return the string-concatenation of cu1 and cu2.
The abstract operation CodePointsToString takes argument text (a sequ