Draft ECMA-262 / August 26, 2025

ECMAScript® 2026 Language Specification

About this Specification

The document at https://tc39.es/ecma262/ is the most accurate and up-to-date ECMAScript specification. It contains the content of the most recent yearly snapshot plus any finished proposals (those that have reached Stage 4 in the proposal process and thus are implemented in several implementations and will be in the next practical revision) since that snapshot was taken.

This document is available as a single page and as multiple pages.

Contributing to this Specification

This specification is developed on GitHub with the help of the ECMAScript community. There are a number of ways to contribute to the development of this specification:

Refer to the colophon for more information on how this document is created.

Introduction

This Ecma Standard defines the ECMAScript 2026 Language. It is the seventeenth 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 supplementary 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 async iterator 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, introduced 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 (undefined or null): 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.

ECMAScript 2021, the 12th edition, introduced 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.

ECMAScript 2022, the 13th edition, introduced top-level await, allowing the keyword to be used at the top level of modules; new class elements: public and private instance fields, public and private static fields, private instance methods and accessors, and private static methods and accessors; static blocks inside classes, to perform per-class evaluation initialization; the #x in obj syntax, to test for presence of private fields on objects; regular expression match indices via the /d flag, which provides start and end indices for matched substrings; the cause property on Error objects, which can be used to record a causation chain in errors; the at method for Strings, Arrays, and TypedArrays, which allows relative indexing; and Object.hasOwn, a convenient alternative to Object.prototype.hasOwnProperty.

ECMAScript 2023, the 14th edition, introduced the toSorted, toReversed, with, findLast, and findLastIndex methods on Array.prototype and TypedArray.prototype, as well as the toSpliced method on Array.prototype; added support for #! comments at the beginning of files to better facilitate executable ECMAScript files; and allowed the use of most Symbols as keys in weak collections.

ECMAScript 2024, the 15th edition, added facilities for resizing and transferring ArrayBuffers and SharedArrayBuffers; added a new RegExp /v flag for creating RegExps with more advanced features for working with sets of strings; and introduced the Promise.withResolvers convenience method for constructing Promises, the Object.groupBy and Map.groupBy methods for aggregating data, the Atomics.waitAsync method for asynchronously waiting for a change to shared memory, and the String.prototype.isWellFormed and String.prototype.toWellFormed methods for checking and ensuring that strings contain only well-formed Unicode.

ECMAScript 2025, the 16th edition, added a new Iterator global with associated static and prototype methods for working with iterators; added methods to Set.prototype for performing common operations on Sets; added support for importing JSON modules as well as syntax for declaring attributes of imported modules; added the RegExp.escape method for escaping a string to be safely used in a regular expression; added syntax for enabling and disabling modifier flags inline within regular expressions; added the Promise.try method for calling functions which may or may not return a Promise and ensuring the result is always a Promise; and added a new Float16Array TypedArray kind as well as the related DataView.prototype.getFloat16, DataView.prototype.setFloat16, and Math.f16round methods.

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

Shu-yu Guo
ECMA-262, Project Editor, 12th through 16th Editions

Michael Ficarra
ECMA-262, Project Editor, 12th through 16th Editions

Kevin Gibbons
ECMA-262, Project Editor, 12th through 16th Editions

1 Scope

This Standard defines the ECMAScript 2026 general-purpose programming language.

2 Conformance

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.7.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, unless otherwise indicated. Web browsers are generally required to implement all normative optional subclauses. (See Annex B.) 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.

2.1 Example Normative Optional Clause Heading

Example clause contents.

A conforming implementation of ECMAScript must implement Legacy subclauses, unless they are also marked as Normative Optional. All of the language features and behaviours specified within Legacy subclauses have one or more undesirable characteristics. However, their continued usage in existing applications prevents their removal from this specification. These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code.

2.2 Example Legacy Clause Heading

Example clause contents.

2.3 Example Legacy Normative Optional Clause Heading

Example clause contents.

3 Normative References

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.

IEEE 754-2019, IEEE Standard for Floating-Point Arithmetic.

The Unicode Standard.
https://unicode.org/versions/latest

ISO/IEC 10646, Information Technology — Universal Multiple-Octet Coded Character Set (UCS) plus Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, Amendment 4:2008, and additional amendments and corrigenda, or successor.

ECMA-402, ECMAScript Internationalization API Specification, specifically the annual edition corresponding to this edition of this specification.
https://www.ecma-international.org/publications-and-standards/standards/ecma-402/

ECMA-404, The JSON Data Interchange Format.
https://www.ecma-international.org/publications-and-standards/standards/ecma-404/

4 Overview

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.

4.1 Web Scripting

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.

4.2 Hosts and Implementations

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 hook must conform to at least the following requirements:

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.

4.3 ECMAScript Overview

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.

4.3.1 Objects

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
An image of lots of boxes and arrows.

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.

4.3.2 The Strict Variant of ECMAScript

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.

4.4 Terms and Definitions

For the purposes of this document, the following terms and definitions apply.

4.4.1 implementation-approximated

an implementation-approximated facility is defined in whole or in part by an external source but has a recommended, ideal behaviour in this specification

4.4.2 implementation-defined

an implementation-defined facility is defined in whole or in part by an external source to this specification

4.4.3 host-defined

same as implementation-defined

Note

Editorially, see clause 4.2.

4.4.4 type

set of data values as defined in clause 6

4.4.5 primitive value

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.

4.4.6 object

member of the type Object

Note

An object is a collection of properties and has a single prototype object. The prototype may be null.

4.4.7 constructor

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.

4.4.8 prototype

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.

4.4.9 ordinary object

object that has the default behaviour for the essential internal methods that must be supported by all objects

4.4.10 exotic object

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.

4.4.11 standard object

object whose semantics are defined by this specification

4.4.12 built-in object

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.

4.4.13 undefined value

primitive value used when a variable has not been assigned a value

4.4.14 Undefined type

type whose sole value is the undefined value

4.4.15 null value

primitive value that represents the intentional absence of any object value

4.4.16 Null type

type whose sole value is the null value

4.4.17 Boolean value

member of the Boolean type

Note

There are only two Boolean values, true and false.

4.4.18 Boolean type

type consisting of the primitive values true and false

4.4.19 Boolean object

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.

4.4.20 String 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.

4.4.21 String type

set of all possible String values

4.4.22 String object

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).

4.4.23 Number value

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.

4.4.24 Number type

set of all possible Number values including NaN (“not a number”), +∞𝔽 (positive infinity), and -∞𝔽 (negative infinity)

4.4.25 Number object

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).

4.4.26 Infinity

Number value that is the positive infinite Number value

4.4.27 NaN

Number value that is an IEEE 754-2019 NaN (“not a number”) value

4.4.28 BigInt value

primitive value corresponding to an arbitrary-precision integer value

4.4.29 BigInt type

set of all possible BigInt values

4.4.30 BigInt object

member of the Object type that is an instance of the standard built-in BigInt constructor

4.4.31 Symbol value

primitive value that represents a unique, non-String Object property key

4.4.32 Symbol type

set of all possible Symbol values

4.4.33 Symbol object

member of the Object type that is an instance of the standard built-in Symbol constructor

4.4.34 function

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.

4.4.35 built-in function

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.

4.4.36 built-in constructor

built-in function that is a constructor

Note

Examples of built-in constructors include Object and Function. A host or implementation may provide additional built-in constructors that are not described in this specification.

4.4.37 property

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.

4.4.38 method

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.

4.4.39 built-in method

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.

4.4.40 attribute

internal value that defines some characteristic of a property

4.4.41 own property

property that is directly contained by its object

4.4.42 inherited property

property of an object that is not an own property but is a property (either own or inherited) of the object's prototype

4.5 Organization of This Specification

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.

5 Notational Conventions

5.1 Syntactic and Lexical Grammars

5.1.1 Context-Free Grammars

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.

5.1.2 The Lexical and RegExp Grammars

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, InputElementRegExp, InputElementRegExpOrTemplateTail, or InputElementHashbangOrRegExp, 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.10). 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.

5.1.3 The Numeric String Grammar

A numeric string grammar appears in 7.1.4.1. It has as its terminal symbols SourceCharacter, and is used for translating Strings into numeric values starting from the goal symbol StringNumericLiteral (which is similar to but distinct from the lexical grammar for numeric literals).

Productions of the numeric string grammar are distinguished by having three colons “:::” as punctuation, and are never used for parsing source text.

5.1.4 The Syntactic Grammar

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 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 state that, in certain contexts, "P must cover an N", where P is a Parse Node (an instance of the generalized production) and N is a nonterminal from the supplemental grammar. This means:

  1. 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.
  2. If the sequence of tokens can be parsed as a single instance of N, with no tokens left over, then:
    1. We refer to that instance of N (a Parse Node, unique for a given P) as "the N that is covered by P".
    2. All Early Error rules for N and its derived productions also apply to the N that is covered by P.
  3. Otherwise (if the parse fails), it is an early Syntax Error.

5.1.5 Grammar Notation

5.1.5.1 Terminal Symbols

In the ECMAScript grammars, some terminal symbols are shown in fixed-width font. These are to appear in a source text 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 block, 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.

In grammars whose terminal symbols are individual Unicode code points (i.e., the lexical, RegExp, and numeric string grammars), a contiguous run of multiple fixed-width code points appearing in a production is a simple shorthand for the same sequence of code points, written as standalone terminal symbols.

For example, the production:

HexIntegerLiteral :: 0x HexDigits

is a shorthand for:

HexIntegerLiteral :: 0 x HexDigits

In contrast, in the syntactic grammar, a contiguous run of fixed-width code points is a single terminal symbol.

Terminal symbols come in two other forms:

  • In the lexical and RegExp grammars, Unicode code points without a conventional printed representation are instead shown in the form "<ABBREV>" where "ABBREV" is a mnemonic for the code point or set of code points. These forms are defined in Unicode Format-Control Characters, White Space, and Line Terminators.
  • In the syntactic grammar, certain terminal symbols (e.g. IdentifierName and RegularExpressionLiteral) are shown in italics, as they refer to the nonterminals of the same name in the lexical grammar.

5.1.5.2 Nonterminal Symbols and Productions

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.

5.1.5.3 Optional Symbols

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.

5.1.5.4 Grammatical Parameters

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 combinatoric 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

5.1.5.5 one of

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

5.1.5.6 [empty]

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.

5.1.5.7 Lookahead Restrictions

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 non-empty 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.

5.1.5.8 [no LineTerminator here]

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.

5.1.5.9 but not

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.

5.1.5.10 Descriptive Phrases

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

5.2 Algorithm Conventions

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 lowercase alphabetic characters and the second level of substeps labelled with lowercase roman numerals. If more than three levels are required these rules repeat with the fourth level using numeric labels. For example:

  1. Top-level step
    1. Substep.
    2. Substep.
      1. Subsubstep.
        1. Subsubsubstep
          1. Subsubsubsubstep
            1. Subsubsubsubsubstep

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”.

5.2.1 Abstract Operations

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).

5.2.2 Syntax-Directed Operations

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 or Parse Node derived from it 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:

  1. Let status be SyntaxDirectedOperation of SomeNonTerminal.
  2. Let someParseNode be the parse of some source text.
  3. Perform SyntaxDirectedOperation of someParseNode.
  4. Perform SyntaxDirectedOperation of someParseNode with argument "value".

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 Evaluation of 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 }
  1. Return Evaluation of StatementList.

5.2.3 Runtime Semantics

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.

5.2.3.1 Completion ( completionRecord )

The abstract operation Completion takes argument completionRecord (a Completion Record) and returns a Completion Record. It is used to emphasize that a Completion Record is being returned. It performs the following steps when called:

  1. Assert: completionRecord is a Completion Record.
  2. Return completionRecord.

5.2.3.2 Throw an Exception

Algorithms steps that say to throw an exception, such as

  1. Throw a TypeError exception.

mean the same things as:

  1. Return ThrowCompletion(a newly created TypeError object).

5.2.3.3 ReturnIfAbrupt

Algorithms steps that say or are otherwise equivalent to:

  1. ReturnIfAbrupt(argument).

mean the same thing as:

  1. Assert: argument is a Completion Record.
  2. If argument is an abrupt completion, return Completion(argument).
  3. Else, set argument to argument.[[Value]].

Algorithms steps that say or are otherwise equivalent to:

  1. ReturnIfAbrupt(AbstractOperation()).

mean the same thing as:

  1. Let hygienicTemp be AbstractOperation().
  2. Assert: hygienicTemp is a Completion Record.
  3. If hygienicTemp is an abrupt completion, return Completion(hygienicTemp).
  4. Else, 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:

  1. Let result be AbstractOperation(ReturnIfAbrupt(argument)).

mean the same thing as:

  1. Assert: argument is a Completion Record.
  2. If argument is an abrupt completion, return Completion(argument).
  3. Else, set argument to argument.[[Value]].
  4. Let result be AbstractOperation(argument).

5.2.3.4 ReturnIfAbrupt Shorthands

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:

  1. ? OperationName().

is equivalent to the following step:

  1. ReturnIfAbrupt(OperationName()).

Similarly, for method application style, the step:

  1. someValue.OperationName().

is equivalent to:

  1. 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:

  1. Let val be ! OperationName().

is equivalent to the following steps:

  1. Let val be OperationName().
  2. Assert: val is a normal completion.
  3. 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:

  1. Perform ! SyntaxDirectedOperation of NonTerminal.

5.2.3.5 Implicit Normal Completion

In algorithms within abstract operations which are declared to return a Completion Record, and within all built-in functions, the returned value is first passed to NormalCompletion, and the result is used instead. This rule does not apply within the Completion algorithm or when the value being returned is clearly marked as a Completion Record in that step; these cases are:

It is an editorial error if a Completion Record is returned from such an abstract operation through any other means. For example, within these abstract operations,

  1. Return true.

means the same things as any of

  1. Return NormalCompletion(true).

or

  1. Let completion be NormalCompletion(true).
  2. Return Completion(completion).

or

  1. Return Completion Record { [[Type]]: normal, [[Value]]: true, [[Target]]: empty }.

Note that, through the ReturnIfAbrupt expansion, the following example is allowed, as within the expanded steps, the result of applying Completion is returned directly in the abrupt case and the implicit NormalCompletion application occurs after unwrapping in the normal case.

  1. Return ? completion.

The following example would be an editorial error because a Completion Record is being returned without being annotated in that step.

  1. Let completion be NormalCompletion(true).
  2. Return completion.

5.2.4 Static Semantics

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.

5.2.5 Mathematical Operations

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 binary64 (double-precision floating point) values.
  • BigInts: ECMAScript language 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. 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.

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 …".

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 finite Number value whose mathematical value is in the set of integers.

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 extended mathematical values, the operators refer to the usual mathematical operations over the extended real numbers; indeterminate forms are not defined and their use in this specification should be considered an editorial error. 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. 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.

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 lowerupper) 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.

Note

floor(x) = x - (x modulo 1).

The mathematical function truncate(x) removes the fractional part of x by rounding towards zero, producing -floor(-x) if x < 0 and otherwise producing floor(x).

Mathematical functions min, max, abs, floor, and truncate 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.

An interval from lower bound a to upper bound b is a possibly-infinite, possibly-empty set of numeric values of the same numeric type. Each bound will be described as either inclusive or exclusive, but not both. There are four kinds of intervals, as follows:

  • An interval from a (inclusive) to b (inclusive), also called an inclusive interval from a to b, includes all values x of the same numeric type such that axb, and no others.
  • An interval from a (inclusive) to b (exclusive) includes all values x of the same numeric type such that ax < b, and no others.
  • An interval from a (exclusive) to b (inclusive) includes all values x of the same numeric type such that a < xb, and no others.
  • An interval from a (exclusive) to b (exclusive) includes all values x of the same numeric type such that a < x < b, and no others.

For example, the interval from 1 (inclusive) to 2 (exclusive) consists of all mathematical values between 1 and 2, including 1 and not including 2. For the purpose of defining intervals, -0𝔽 < +0𝔽, so, for example, an inclusive interval with a lower bound of +0𝔽 includes +0𝔽 but not -0𝔽. NaN is never included in an interval.

5.2.6 Value Notation

In this specification, ECMAScript language values are displayed in bold. Examples include null, true, or "hello". These are distinguished from ECMAScript source text such as Function.prototype.apply or let n = 42;.

5.2.7 Identity

In this specification, both specification values and ECMAScript language values are compared for equality. When comparing for equality, values fall into one of two categories. Values without identity are equal to other values without identity if all of their innate characteristics are the same — characteristics such as the magnitude of an integer or the length of a sequence. Values without identity may be manifest without prior reference by fully describing their characteristics. In contrast, each value with identity is unique and therefore only equal to itself. Values with identity are like values without identity but with an additional unguessable, unchangeable, universally-unique characteristic called identity. References to existing values with identity cannot be manifest simply by describing them, as the identity itself is indescribable; instead, references to these values must be explicitly passed from one place to another. Some values with identity are mutable and therefore can have their characteristics (except their identity) changed in-place, causing all holders of the value to observe the new characteristics. A value without identity is never equal to a value with identity.

From the perspective of this specification, the word “is” is used to compare two values for equality, as in “If bool is true, then ...”, and the word “contains” is used to search for a value inside lists using equality comparisons, as in "If list contains a Record r such that r.[[Foo]] is true, then ...". The specification identity of values determines the result of these comparisons and is axiomatic in this specification.

From the perspective of the ECMAScript language, language values are compared for equality using the SameValue abstract operation and the abstract operations it transitively calls. The algorithms of these comparison abstract operations determine language identity of ECMAScript language values.

For specification values, examples of values without specification identity include, but are not limited to: mathematical values and extended mathematical values; ECMAScript source text, surrogate pairs, Directive Prologues, etc; UTF-16 code units; Unicode code points; enums; abstract operations, including syntax-directed operations, host hooks, etc; and ordered pairs. Examples of specification values with specification identity include, but are not limited to: any kind of Records, including Property Descriptors, PrivateElements, etc; Parse Nodes; Lists; Sets and Relations; Abstract Closures; Data Blocks; Private Names; execution contexts and execution context stacks; agent signifiers; and WaiterList Records.

Specification identity agrees with language identity for all ECMAScript language values except Symbol values produced by Symbol.for. The ECMAScript language values without specification identity and without language identity are undefined, null, Booleans, Strings, Numbers, and BigInts. The ECMAScript language values with specification identity and language identity are Symbols not produced by Symbol.for and Objects. Symbol values produced by Symbol.for have specification identity, but not language identity.

6 ECMAScript Data Types and Values

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 classified into ECMAScript language types and specification types.

6.1 ECMAScript Language Types

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.

6.1.1 The Undefined Type

The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

6.1.2 The Null Type

The Null type has exactly one value, called null.

6.1.3 The Boolean Type

The Boolean type represents a logical entity having two values, called true and false.

6.1.4 The String Type

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 interval from 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 interval from 0xDC00 to 0xDFFF (defined as a trailing surrogate, or more formally as a low-surrogate code unit) using the following rules:

The function String.prototype.normalize (see 22.1.3.15) can be used to explicitly normalize a String value. String.prototype.localeCompare (see 22.1.3.12) internally normalizes String values, but no other operations implicitly normalize the strings upon which they operate. Operation results are not language- and/or locale-sensitive unless stated otherwise.

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 phrase "the ASCII word characters" denotes the following String value, which consists solely of every letter and number in the Unicode Basic Latin block along with U+005F (LOW LINE):
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".
For historical reasons, it has significance to various algorithms.

6.1.4.1 StringIndexOf ( string, searchValue, fromIndex )

The abstract operation StringIndexOf takes arguments string (a String), searchValue (a String), and fromIndex (a non-negative integer) and returns a non-negative integer or not-found. It performs the following steps when called:

  1. Let len be the length of string.
  2. If searchValue is the empty String and fromIndexlen, return fromIndex.
  3. Let searchLen be the length of searchValue.
  4. For each integer i such that fromIndexilen - searchLen, in ascending order, do
    1. Let candidate be the substring of string from i to i + searchLen.
    2. If candidate is searchValue, return i.
  5. Return not-found.
Note 1

If searchValue is the empty String and fromIndex ≤ 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 not-found if fromIndex + the length of searchValue > the length of string.

6.1.4.2 StringLastIndexOf ( string, searchValue, fromIndex )

The abstract operation StringLastIndexOf takes arguments string (a String), searchValue (a String), and fromIndex (a non-negative integer) and returns a non-negative integer or not-found. It performs the following steps when called:

  1. Let len be the length of string.
  2. Let searchLen be the length of searchValue.
  3. Assert: fromIndex + searchLenlen.
  4. For each integer i such that 0 ≤ ifromIndex, in descending order, do
    1. Let candidate be the substring of string from i to i + searchLen.
    2. If candidate is searchValue, return i.
  5. Return not-found.
Note

If searchValue is the empty String, this algorithm returns fromIndex. The empty String is effectively found at every position within a string, including after the last code unit.

6.1.5 The Symbol Type

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 Symbol is unique and immutable.

Each Symbol has an immutable [[Description]] internal slot whose value is either a String or undefined.

6.1.5.1 Well-Known Symbols

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.3).

Within this specification a well-known symbol is referred to using the standard intrinsic notation where the intrinsic is one of the values listed in Table 1.

Note
Previous editions of this specification used a notation of the form @@name, where the current edition would use %Symbol.name%. In particular, the following names were used: @@asyncIterator, @@hasInstance, @@isConcatSpreadable, @@iterator, @@match, @@matchAll, @@replace, @@search, @@species, @@split, @@toPrimitive, @@toStringTag, and @@unscopables.
Table 1: Well-known Symbols
Specification Name [[Description]] Value and Purpose
%Symbol.asyncIterator% "Symbol.asyncIterator" A method that returns the default async iterator for an object. Called by the semantics of the for-await-of statement.
%Symbol.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.
%Symbol.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.
%Symbol.iterator% "Symbol.iterator" A method that returns the default iterator for an object. Called by the semantics of the for-of statement.
%Symbol.match% "Symbol.match" A regular expression method that matches the regular expression against a string. Called by the String.prototype.match method.
%Symbol.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.
%Symbol.replace% "Symbol.replace" A regular expression method that replaces matched substrings of a string. Called by the String.prototype.replace method.
%Symbol.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.
%Symbol.species% "Symbol.species" A function valued property that is the constructor function that is used to create derived objects.
%Symbol.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.
%Symbol.toPrimitive% "Symbol.toPrimitive" A method that converts an object to a corresponding primitive value. Called by the ToPrimitive abstract operation.
%Symbol.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.
%Symbol.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.

6.1.6 Numeric Types

ECMAScript has two built-in numeric types: Number and BigInt. The following abstract operations are defined over these numeric types. 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
Operation Example source Invoked by the Evaluation semantics of ... Result
Number::unaryMinus -x Unary - Operator Number
BigInt::unaryMinus BigInt
Number::bitwiseNOT ~x Bitwise NOT Operator ( ~ ) Number
BigInt::bitwiseNOT BigInt
Number::exponentiate x ** y Exponentiation Operator and Math.pow ( base, exponent ) Number
BigInt::exponentiate either a normal completion containing a BigInt or a throw completion
Number::multiply x * y Multiplicative Operators Number
BigInt::multiply BigInt
Number::divide x / y Multiplicative Operators Number
BigInt::divide either a normal completion containing a BigInt or a throw completion
Number::remainder x % y Multiplicative Operators Number
BigInt::remainder either a normal completion containing a BigInt or a throw completion
Number::add x ++
++ x
x + y
Postfix Increment Operator, Prefix Increment Operator, and The Addition Operator ( + ) Number
BigInt::add BigInt
Number::subtract x --
-- x
x - y
Postfix Decrement Operator, Prefix Decrement Operator, and The Subtraction Operator ( - ) Number
BigInt::subtract BigInt
Number::leftShift x << y The Left Shift Operator ( << ) Number
BigInt::leftShift BigInt
Number::signedRightShift x >> y The Signed Right Shift Operator ( >> ) Number
BigInt::signedRightShift BigInt
Number::unsignedRightShift x >>> y The Unsigned Right Shift Operator ( >>> ) Number
BigInt::unsignedRightShift a throw completion
Number::lessThan x < y
x > y
x <= y
x >= y
Relational Operators, via IsLessThan ( x, y, LeftFirst ) Boolean or undefined (for unordered inputs)
BigInt::lessThan Boolean
Number::equal x == y
x != y
x === y
x !== y
Equality Operators, via IsStrictlyEqual ( x, y ) Boolean
BigInt::equal
Number::sameValue Object.is(x, y) Object internal methods, via SameValue ( x, y ), to test exact value equality Boolean
Number::sameValueZero [x].includes(y) via SameValueZero ( x, y ), to test value equality, ignoring the difference between +0𝔽 and -0𝔽, as in Array, Map, and Set methods Boolean
Number::bitwiseAND x & y Binary Bitwise Operators Number
BigInt::bitwiseAND BigInt
Number::bitwiseXOR x ^ y Number
BigInt::bitwiseXOR BigInt
Number::bitwiseOR x | y Number
BigInt::bitwiseOR BigInt
Number::toString String(x) Many expressions and built-in functions, via ToString ( argument ) String
BigInt::toString

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.

6.1.6.1 The Number Type

The Number type has exactly 18,437,736,874,454,810,627 (that is, 264 - 253 + 3) values, representing the double-precision floating point IEEE 754-2019 binary64 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 NaN 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 NaN 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 in the interval from 252 (inclusive) to 253 (exclusive), and e is an integer in the inclusive interval from -1074 to 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 in the interval from 0 (exclusive) to 252 (exclusive), 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 the inclusive interval from -231 to 231 - 1 or the inclusive interval from 0 to 216 - 1. 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.

6.1.6.1.1 Number::unaryMinus ( x )

The abstract operation Number::unaryMinus takes argument x (a Number) and returns a Number. It performs the following steps when called:

  1. If x is NaN, return NaN.
  2. Return the negation of x; that is, compute a Number with the same magnitude but opposite sign.

6.1.6.1.2 Number::bitwiseNOT ( x )

The abstract operation Number::bitwiseNOT takes argument x (a Number) and returns an integral Number. It performs the following steps when called:

  1. Let oldValue be ! ToInt32(x).
  2. Return the bitwise complement of oldValue. The mathematical value of the result is exactly representable as a 32-bit two's complement bit string.

6.1.6.1.3 Number::exponentiate ( base, exponent )

The abstract operation Number::exponentiate takes arguments base (a Number) and exponent (a Number) and returns 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:

  1. If exponent is NaN, return NaN.
  2. If exponent is either +0𝔽 or -0𝔽, return 1𝔽.
  3. If base is NaN, return NaN.
  4. If base is +∞𝔽, then
    1. If exponent > +0𝔽, return +∞𝔽; otherwise return +0𝔽.
  5. If base is -∞𝔽, then
    1. If exponent > +0𝔽, then
      1. If exponent is an odd integral Number, return -∞𝔽; otherwise return +∞𝔽.
    2. Else,
      1. If exponent is an odd integral Number, return -0𝔽; otherwise return +0𝔽.
  6. If base is +0𝔽, then
    1. If exponent > +0𝔽, return +0𝔽; otherwise return +∞𝔽.
  7. If base is -0𝔽, then
    1. If exponent > +0𝔽, then
      1. If exponent is an odd integral Number, return -0𝔽; otherwise return +0𝔽.
    2. Else,
      1. If exponent is an odd integral Number, return -∞𝔽; otherwise return +∞𝔽.
  8. Assert: base is finite and is neither +0𝔽 nor -0𝔽.
  9. If exponent is +∞𝔽, then
    1. If abs((base)) > 1, return +∞𝔽.
    2. If abs((base)) = 1, return NaN.
    3. If abs((base)) < 1, return +0𝔽.
  10. If exponent is -∞𝔽, then
    1. If abs((base)) > 1, return +0𝔽.
    2. If abs((base)) = 1, return NaN.
    3. If abs((base)) < 1, return +∞𝔽.
  11. Assert: exponent is finite and is neither +0𝔽 nor -0𝔽.
  12. If base < -0𝔽 and exponent is not an integral Number, return NaN.
  13. Return an implementation-approximated Number 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 revisions of IEEE 754 specified 1𝔽. The historical ECMAScript behaviour is preserved for compatibility reasons.

6.1.6.1.4 Number::multiply ( x, y )

The abstract operation Number::multiply takes arguments x (a Number) and y (a Number) and returns 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:

  1. If x is NaN or y is NaN, return NaN.
  2. If x is either +∞𝔽 or -∞𝔽, then
    1. If y is either +0𝔽 or -0𝔽, return NaN.
    2. If y > +0𝔽, return x.
    3. Return -x.
  3. If y is either +∞𝔽 or -∞𝔽, then
    1. If x is either +0𝔽 or -0𝔽, return NaN.
    2. If x > +0𝔽, return y.
    3. Return -y.
  4. If x is -0𝔽, then
    1. If y is -0𝔽 or y < -0𝔽, return +0𝔽.
    2. Else, return -0𝔽.
  5. If y is -0𝔽, then
    1. If x < -0𝔽, return +0𝔽.
    2. Else, return -0𝔽.
  6. Return 𝔽((x) × (y)).
Note

Finite-precision multiplication is commutative, but not always associative.

6.1.6.1.5 Number::divide ( x, y )

The abstract operation Number::divide takes arguments x (a Number) and y (a Number) and returns 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:

  1. If x is NaN or y is NaN, return NaN.
  2. If x is either +∞𝔽 or -∞𝔽, then
    1. If y is either +∞𝔽 or -∞𝔽, return NaN.
    2. If y is +0𝔽 or y > +0𝔽, return x.
    3. Return -x.
  3. If y is +∞𝔽, then
    1. If x is +0𝔽 or x > +0𝔽, return +0𝔽; otherwise return -0𝔽.
  4. If y is -∞𝔽, then
    1. If x is +0𝔽 or x > +0𝔽, return -0𝔽; otherwise return +0𝔽.
  5. If x is either +0𝔽 or -0𝔽, then
    1. If y is either +0𝔽 or -0𝔽, return NaN.
    2. If y > +0𝔽, return x.
    3. Return -x.
  6. If y is +0𝔽, then
    1. If x > +0𝔽, return +∞𝔽; otherwise return -∞𝔽.
  7. If y is -0𝔽, then
    1. If x > +0𝔽, return -∞𝔽; otherwise return +∞𝔽.
  8. Return 𝔽((x) / (y)).

6.1.6.1.6 Number::remainder ( n, d )

The abstract operation Number::remainder takes arguments n (a Number) and d (a Number) and returns 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:

  1. If n is NaN or d is NaN, return NaN.
  2. If n is either +∞𝔽 or -∞𝔽, return NaN.
  3. If d is either +∞𝔽 or -∞𝔽, return n.
  4. If d is either +0𝔽 or -0𝔽, return NaN.
  5. If n is either +0𝔽 or -0𝔽, return n.
  6. Assert: n and d are finite and non-zero.
  7. Let quotient be (n) / (d).
  8. Let q be truncate(quotient).
  9. Let r be (n) - ((d) × q).
  10. If r = 0 and n < -0𝔽, return -0𝔽.
  11. 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 IEEE 754-2019. The IEEE 754-2019 “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.

6.1.6.1.7 Number::add ( x, y )

The abstract operation Number::add takes arguments x (a Number) and y (a Number) and returns 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:

  1. If x is NaN or y is NaN, return NaN.
  2. If x is +∞𝔽 and y is -∞𝔽, return NaN.
  3. If x is -∞𝔽 and y is +∞𝔽, return NaN.
  4. If x is either +∞𝔽 or -∞𝔽, return x.
  5. If y is either +∞𝔽 or -∞𝔽, return y.
  6. Assert: x and y are both finite.
  7. If x is -0𝔽 and y is -0𝔽, return -0𝔽.
  8. Return 𝔽((x) + (y)).
Note

Finite-precision addition is commutative, but not always associative.

6.1.6.1.8 Number::subtract ( x, y )

The abstract operation Number::subtract takes arguments x (a Number) and y (a Number) and returns 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:

  1. Return Number::add(x, Number::unaryMinus(y)).
Note

It is always the case that x - y produces the same result as x + (-y).

6.1.6.1.9 Number::leftShift ( x, y )

The abstract operation Number::leftShift takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. Let lNum be ! ToInt32(x).
  2. Let rNum be ! ToUint32(y).
  3. Let shiftCount be (rNum) modulo 32.
  4. 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.

6.1.6.1.10 Number::signedRightShift ( x, y )

The abstract operation Number::signedRightShift takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. Let lNum be ! ToInt32(x).
  2. Let rNum be ! ToUint32(y).
  3. Let shiftCount be (rNum) modulo 32.
  4. 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.

6.1.6.1.11 Number::unsignedRightShift ( x, y )

The abstract operation Number::unsignedRightShift takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. Let lNum be ! ToUint32(x).
  2. Let rNum be ! ToUint32(y).
  3. Let shiftCount be (rNum) modulo 32.
  4. 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.

6.1.6.1.12 Number::lessThan ( x, y )

The abstract operation Number::lessThan takes arguments x (a Number) and y (a Number) and returns a Boolean or undefined. It performs the following steps when called:

  1. If x is NaN, return undefined.
  2. If y is NaN, return undefined.
  3. If x is y, return false.
  4. If x is +0𝔽 and y is -0𝔽, return false.
  5. If x is -0𝔽 and y is +0𝔽, return false.
  6. If x is +∞𝔽, return false.
  7. If y is +∞𝔽, return true.
  8. If y is -∞𝔽, return false.
  9. If x is -∞𝔽, return true.
  10. Assert: x and y are finite.
  11. If (x) < (y), return true; otherwise return false.

6.1.6.1.13 Number::equal ( x, y )

The abstract operation Number::equal takes arguments x (a Number) and y (a Number) and returns a Boolean. It performs the following steps when called:

  1. If x is NaN, return false.
  2. If y is NaN, return false.
  3. If x is y, return true.
  4. If x is +0𝔽 and y is -0𝔽, return true.
  5. If x is -0𝔽 and y is +0𝔽, return true.
  6. Return false.

6.1.6.1.14 Number::sameValue ( x, y )

The abstract operation Number::sameValue takes arguments x (a Number) and y (a Number) and returns a Boolean. It performs the following steps when called:

  1. If x is NaN and y is NaN, return true.
  2. If x is +0𝔽 and y is -0𝔽, return false.
  3. If x is -0𝔽 and y is +0𝔽, return false.
  4. If x is y, return true.
  5. Return false.

6.1.6.1.15 Number::sameValueZero ( x, y )

The abstract operation Number::sameValueZero takes arguments x (a Number) and y (a Number) and returns a Boolean. It performs the following steps when called:

  1. If x is NaN and y is NaN, return true.
  2. If x is +0𝔽 and y is -0𝔽, return true.
  3. If x is -0𝔽 and y is +0𝔽, return true.
  4. If x is y, return true.
  5. Return false.

6.1.6.1.16 NumberBitwiseOp ( op, x, y )

The abstract operation NumberBitwiseOp takes arguments op (&, ^, or |), x (a Number), and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. Let lNum be ! ToInt32(x).
  2. Let rNum be ! ToInt32(y).
  3. Let lBits be the 32-bit two's complement bit string representing (lNum).
  4. Let rBits be the 32-bit two's complement bit string representing (rNum).
  5. If op is &, then
    1. Let result be the result of applying the bitwise AND operation to lBits and rBits.
  6. Else if op is ^, then
    1. Let result be the result of applying the bitwise exclusive OR (XOR) operation to lBits and rBits.
  7. Else,
    1. Assert: op is |.
    2. Let result be the result of applying the bitwise inclusive OR operation to lBits and rBits.
  8. Return the Number value for the integer represented by the 32-bit two's complement bit string result.

6.1.6.1.17 Number::bitwiseAND ( x, y )

The abstract operation Number::bitwiseAND takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. Return NumberBitwiseOp(&, x, y).

6.1.6.1.18 Number::bitwiseXOR ( x, y )

The abstract operation Number::bitwiseXOR takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. Return NumberBitwiseOp(^, x, y).

6.1.6.1.19 Number::bitwiseOR ( x, y )

The abstract operation Number::bitwiseOR takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. Return NumberBitwiseOp(|, x, y).

6.1.6.1.20 Number::toString ( x, radix )

The abstract operation Number::toString takes arguments x (a Number) and radix (an integer in the inclusive interval from 2 to 36) and returns a String. It represents x as a String using a positional numeral system with radix radix. The digits used in the representation of a number using radix r are taken from the first r code units of "0123456789abcdefghijklmnopqrstuvwxyz" in order. The representation of numbers with magnitude greater than or equal to 1𝔽 never includes leading zeroes. It performs the following steps when called:

  1. If x is NaN, return "NaN".
  2. If x is either +0𝔽 or -0𝔽, return "0".
  3. If x < -0𝔽, return the string-concatenation of "-" and Number::toString(-x, radix).
  4. If x is +∞𝔽, return "Infinity".
  5. Let n, k, and s be integers such that k ≥ 1, radixk - 1s < radixk, 𝔽(s × radixn - k) is x, and k is as small as possible. Note that k is the number of digits in the representation of s using radix radix, that s is not divisible by radix, and that the least significant digit of s is not necessarily uniquely determined by these criteria.
  6. If radix ≠ 10 or n is in the inclusive interval from -5 to 21, then
    1. If nk, then
      1. Return the string-concatenation of:
        • the code units of the k digits of the representation of s using radix radix
        • n - k occurrences of the code unit 0x0030 (DIGIT ZERO)
    2. Else if n > 0, then
      1. Return the string-concatenation of:
        • the code units of the most significant n digits of the representation of s using radix radix
        • the code unit 0x002E (FULL STOP)
        • the code units of the remaining k - n digits of the representation of s using radix radix
    3. Else,
      1. Assert: n ≤ 0.
      2. 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 representation of s using radix radix
  7. NOTE: In this case, the input will be represented using scientific E notation, such as 1.2e+3.
  8. Assert: radix is 10.
  9. If n < 0, then
    1. Let exponentSign be the code unit 0x002D (HYPHEN-MINUS).
  10. Else,
    1. Let exponentSign be the code unit 0x002B (PLUS SIGN).
  11. If k = 1, then
    1. Return the string-concatenation of:
      • the code unit of the single digit of s
      • the code unit 0x0065 (LATIN SMALL LETTER E)
      • exponentSign
      • the code units of the decimal representation of abs(n - 1)
  12. Return the string-concatenation of:
    • the code unit 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)
    • exponentSign
    • the code units of the decimal representation of abs(n - 1)
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 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:

  1. Let n, k, and s be integers such that k ≥ 1, radixk - 1s < radixk, 𝔽(s × radixn - 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 × radixn - 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 representation of s using radix radix and that s is not divisible by radix.
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
https://ampl.com/_archive/first-website/REFS/rounding.pdf. 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.

6.1.6.2 The BigInt Type

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.

6.1.6.2.1 BigInt::unaryMinus ( x )

The abstract operation BigInt::unaryMinus takes argument x (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. If x = 0, return 0.
  2. Return -x.

6.1.6.2.2 BigInt::bitwiseNOT ( x )

The abstract operation BigInt::bitwiseNOT takes argument x (a BigInt) and returns a BigInt. It returns the one's complement of x. It performs the following steps when called:

  1. Return -x - 1.

6.1.6.2.3 BigInt::exponentiate ( base, exponent )

The abstract operation BigInt::exponentiate takes arguments base (a BigInt) and exponent (a BigInt) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. If exponent < 0, throw a RangeError exception.
  2. If base = 0 and exponent = 0, return 1.
  3. Return base raised to the power exponent.

6.1.6.2.4 BigInt::multiply ( x, y )

The abstract operation BigInt::multiply takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Return x × y.
Note
Even if the result has a much larger bit width than the input, the exact mathematical answer is given.

6.1.6.2.5 BigInt::divide ( x, y )

The abstract operation BigInt::divide takes arguments x (a BigInt) and y (a BigInt) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. If y = 0, throw a RangeError exception.
  2. Let quotient be (x) / (y).
  3. Return (truncate(quotient)).

6.1.6.2.6 BigInt::remainder ( n, d )

The abstract operation BigInt::remainder takes arguments n (a BigInt) and d (a BigInt) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. If d = 0, throw a RangeError exception.
  2. If n = 0, return 0.
  3. Let quotient be (n) / (d).
  4. Let q be (truncate(quotient)).
  5. Return n - (d × q).
Note
The sign of the result is the sign of the dividend.

6.1.6.2.7 BigInt::add ( x, y )

The abstract operation BigInt::add takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Return x + y.

6.1.6.2.8 BigInt::subtract ( x, y )

The abstract operation BigInt::subtract takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Return x - y.

6.1.6.2.9 BigInt::leftShift ( x, y )

The abstract operation BigInt::leftShift takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. If y < 0, then
    1. Return (floor((x) / 2-(y))).
  2. Return 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.

6.1.6.2.10 BigInt::signedRightShift ( x, y )

The abstract operation BigInt::signedRightShift takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Return BigInt::leftShift(x, -y).

6.1.6.2.11 BigInt::unsignedRightShift ( x, y )

The abstract operation BigInt::unsignedRightShift takes arguments x (a BigInt) and y (a BigInt) and returns a throw completion. It performs the following steps when called:

  1. Throw a TypeError exception.

6.1.6.2.12 BigInt::lessThan ( x, y )

The abstract operation BigInt::lessThan takes arguments x (a BigInt) and y (a BigInt) and returns a Boolean. It performs the following steps when called:

  1. If (x) < (y), return true; otherwise return false.

6.1.6.2.13 BigInt::equal ( x, y )

The abstract operation BigInt::equal takes arguments x (a BigInt) and y (a BigInt) and returns a Boolean. It performs the following steps when called:

  1. If (x) = (y), return true; otherwise return false.

6.1.6.2.14 BinaryAnd ( x, y )

The abstract operation BinaryAnd takes arguments x (0 or 1) and y (0 or 1) and returns 0 or 1. It performs the following steps when called:

  1. If x = 1 and y = 1, return 1.
  2. Else, return 0.

6.1.6.2.15 BinaryOr ( x, y )

The abstract operation BinaryOr takes arguments x (0 or 1) and y (0 or 1) and returns 0 or 1. It performs the following steps when called:

  1. If x = 1 or y = 1, return 1.
  2. Else, return 0.

6.1.6.2.16 BinaryXor ( x, y )

The abstract operation BinaryXor takes arguments x (0 or 1) and y (0 or 1) and returns 0 or 1. It performs the following steps when called:

  1. If x = 1 and y = 0, return 1.
  2. Else if x = 0 and y = 1, return 1.
  3. Else, return 0.

6.1.6.2.17 BigIntBitwiseOp ( op, x, y )

The abstract operation BigIntBitwiseOp takes arguments op (&, ^, or |), x (a BigInt), and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Set x to (x).
  2. Set y to (y).
  3. Let result be 0.
  4. Let shift be 0.
  5. Repeat, until (x = 0 or x = -1) and (y = 0 or y = -1),
    1. Let xDigit be x modulo 2.
    2. Let yDigit be y modulo 2.
    3. If op is &, then
      1. Set result to result + 2shift × BinaryAnd(xDigit, yDigit).
    4. Else if op is |, then
      1. Set result to result + 2shift × BinaryOr(xDigit, yDigit).
    5. Else,
      1. Assert: op is ^.
      2. Set result to result + 2shift × BinaryXor(xDigit, yDigit).
    6. Set shift to shift + 1.
    7. Set x to (x - xDigit) / 2.
    8. Set y to (y - yDigit) / 2.
  6. If op is &, then
    1. Let tmp be BinaryAnd(x modulo 2, y modulo 2).
  7. Else if op is |, then
    1. Let tmp be BinaryOr(x modulo 2, y modulo 2).
  8. Else,
    1. Assert: op is ^.
    2. Let tmp be BinaryXor(x modulo 2, y modulo 2).
  9. If tmp ≠ 0, then
    1. Set result to result - 2shift.
    2. NOTE: This extends the sign.
  10. Return the BigInt value for result.

6.1.6.2.18 BigInt::bitwiseAND ( x, y )

The abstract operation BigInt::bitwiseAND takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Return BigIntBitwiseOp(&, x, y).

6.1.6.2.19 BigInt::bitwiseXOR ( x, y )

The abstract operation BigInt::bitwiseXOR takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Return BigIntBitwiseOp(^, x, y).

6.1.6.2.20 BigInt::bitwiseOR ( x, y )

The abstract operation BigInt::bitwiseOR takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. Return BigIntBitwiseOp(|, x, y).

6.1.6.2.21 BigInt::toString ( x, radix )

The abstract operation BigInt::toString takes arguments x (a BigInt) and radix (an integer in the inclusive interval from 2 to 36) and returns a String. It represents x as a String using a positional numeral system with radix radix. The digits used in the representation of a BigInt using radix r are taken from the first r code units of "0123456789abcdefghijklmnopqrstuvwxyz" in order. The representation of BigInts other than 0 never includes leading zeroes. It performs the following steps when called:

  1. If x < 0, return the string-concatenation of "-" and BigInt::toString(-x, radix).
  2. Return the String value consisting of the representation of x using radix radix.

6.1.7 The Object Type

Each instance of the Object type, also referred to simply as “an Object”, represents 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.

The properties of an object are uniquely identified using property keys. A property key is either a String or a Symbol. All Strings and Symbols, including the empty String, are valid as property keys. A property name is a property key that is a String.

An integer index is a property name n such that CanonicalNumericIndexString(n) returns an integral Number in the inclusive interval from +0𝔽 to 𝔽(253 - 1). An array index is an integer index n such that CanonicalNumericIndexString(n) returns an integral Number in the inclusive interval from +0𝔽 to 𝔽(232 - 2).

Note

Every non-negative safe integer has a corresponding integer index. Every 32-bit unsigned integer except 232 - 1 has a corresponding array index. "-0" is neither an integer index nor an array index.

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.

In addition, some objects are callable; these are referred to as functions or function objects and are described further below. All functions in ECMAScript are members of the Object type.

6.1.7.1 Property Attributes

Attributes are used in this specification to define and explain the state of Object properties as described in Table 3. Unless specified explicitly, the initial value of each attribute is its Default Value.

Table 3: Attributes of an Object property
Attribute Name Types of property for which it is present Value Domain Default Value Description
[[Value]] data property an ECMAScript language value undefined The value retrieved by a get access of the property.
[[Writable]] data property a Boolean false If false, attempts by ECMAScript code to change the property's [[Value]] attribute using [[Set]] will not succeed.
[[Get]] accessor property an Object or undefined undefined If the value is an Object it must be a function object. The function's [[Call]] internal method (Table 5) is called with an empty arguments list to retrieve the property value each time a get access of the property is performed.
[[Set]] accessor property an Object or undefined undefined If the value is an Object it must be a function object. The function's [[Call]] internal method (Table 5) is called with an arguments list containing the assigned value as its sole argument each time a set access of the property is performed. The effect of a property's [[Set]] internal method may, but is not required to, have an effect on the value returned by subsequent calls to the property's [[Get]] internal method.
[[Enumerable]] data property or accessor property a Boolean false 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]] data property or accessor property a Boolean false If false, attempts to delete the property, change it from a data property to an accessor property or from an accessor property to a data property, or make any changes to its attributes (other than replacing an existing [[Value]] or setting [[Writable]] to false) will fail.

6.1.7.2 Object Internal Methods and Internal Slots

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, Symbols, or Private Names 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, Symbol, or Private Name and may not be dynamically added. Unless specified otherwise, the initial value of an internal slot is the value undefined. Various algorithms within this specification create values that have internal slots. However, the ECMAScript language provides no direct way to manipulate internal slots.

All objects have an internal slot named [[PrivateElements]], which is a List of PrivateElements. This List represents the values of the private fields, methods, and accessors for the object. Initially, it is an empty List.

Internal methods and internal slots are identified within this specification using names enclosed in double square brackets [[ ]].

Table 4 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 4, the object uses those defined in 10.1.
  • If the object has a [[Call]] internal method, it uses either the one defined in 10.2.1 or the one defined in 10.3.1.
  • If the object has a [[Construct]] internal method, it uses either the one defined in 10.2.2 or the one defined in 10.3.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 4 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 4: Essential Internal Methods
Internal Method Signature Description
[[GetPrototypeOf]] ( ) Object | Null Determine the object that provides inherited properties for this object. A null value indicates that there are no inherited properties.
[[SetPrototypeOf]] (Object | Null) Boolean Associate this object with another object that provides inherited properties. Passing null indicates that there are no inherited properties. Returns true indicating that the operation was completed successfully or false indicating that the operation was not successful.
[[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 Return a Property Descriptor for the own property of this object whose key is propertyKey, or undefined if no such property exists.
[[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 property keys Return a List whose elements are all of the own property keys for the object.

Table 5 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 5: 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.

6.1.7.3 Invariants of the Essential Internal Methods

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.

Definitions:

  • 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.

Return value:

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 continue completion, a break completion, or a return completion.

[[GetPrototypeOf]] ( )

  • 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.

[[SetPrototypeOf]] ( V )

  • 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.

[[IsExtensible]] ( )

  • The normal return type is Boolean.
  • If [[IsExtensible]] returns false, all future calls to [[IsExtensible]] on the target must return false.

[[PreventExtensions]] ( )

  • 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.

[[GetOwnProperty]] ( P )

  • The normal return type is either Property Descriptor or Undefined.
  • If the return value is a Property Descriptor, it 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]] and [[Value]] 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.

[[DefineOwnProperty]] ( P, Desc )

  • 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:
    1. P is a writable data property. A non-configurable writable data property can be changed into a non-configurable non-writable data property.
    2. 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.

[[HasProperty]] ( P )

  • 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.

[[Get]] ( P, Receiver )

  • 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.

[[Set]] ( P, V, Receiver )

  • 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.

[[Delete]] ( P )

  • 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.

[[OwnPropertyKeys]] ( )

  • The normal return type is List.
  • The returned List must not contain any duplicate entries.
  • Each element of the returned List must be a property key.
  • 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]].

[[Call]] ( )

[[Construct]] ( )

  • The normal return type is Object.
  • The target must also have a [[Call]] internal method.

6.1.7.4 Well-Known Intrinsic Objects

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 value 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.4. The well-known intrinsics are listed in Table 6.

Table 6: 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.4)
%ArrayIteratorPrototype% The prototype of Array Iterator objects (23.1.5)
%AsyncFromSyncIteratorPrototype% The prototype of Async-from-Sync Iterator objects (27.1.6)
%AsyncFunction% The constructor of async function objects (27.7.1)
%AsyncGeneratorFunction% The constructor of async generator function objects (27.4.1)
%AsyncGeneratorPrototype% The prototype of async generator objects (27.6)
%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.1)
%decodeURIComponent% decodeURIComponent The decodeURIComponent function (19.2.6.2)
%encodeURI% encodeURI The encodeURI function (19.2.6.3)
%encodeURIComponent% encodeURIComponent The encodeURIComponent function (19.2.6.4)
%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)
%Float16Array% Float16Array The Float16Array constructor (23.2)
%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 function objects (27.3.1)
%GeneratorPrototype% The prototype of generator objects (27.5)
%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)
%Iterator% Iterator The Iterator constructor (27.1.3.1)
%IteratorHelperPrototype% The prototype of Iterator Helper objects (27.1.2.1)
%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.4)
%RegExpStringIteratorPrototype% The prototype of RegExp String Iterator objects (22.2.9)
%Set% Set The Set constructor (24.2.2)
%SetIteratorPrototype% The prototype of Set Iterator objects (24.2.6)
%SharedArrayBuffer% SharedArrayBuffer The SharedArrayBuffer constructor (25.2.3)
%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)
%WrapForValidIteratorPrototype% The prototype of wrapped iterator objects returned by Iterator.from (27.1.3.2.1.1)
Note

Additional entries in Table 100.

6.2 ECMAScript Specification Types

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 Record, List, Completion Record, 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.

6.2.1 The Enum Specification Type

Enums are values which are internal to the specification and not directly observable from ECMAScript code. Enums are denoted using a sans-serif typeface. For instance, a Completion Record's [[Type]] field takes on values like normal, return, or throw. Enums have no characteristics other than their name. The name of an enum serves no purpose other than to distinguish it from other enums, and implies nothing about its usage or meaning in context.

6.2.2 The List and Record Specification Types

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 « ».

In this specification, the phrase "the list-concatenation of A, B, ..." (where each argument is a possibly empty List) denotes a new List value whose elements are the concatenation of the elements (in order) of each of the arguments (in order).

As applied to a List of Strings, the phrase "sorted according to lexicographic code unit order" means sorting by the numeric value of each code unit up to the length of the shorter string, and sorting the shorter string before the longer string if all are equal, as described in the abstract operation IsLessThan.

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 an ECMAScript language value or specification value. 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 }.

6.2.3 The Set and Relation Specification Types

The Set type is used to explain a collection of unordered elements for use in the memory model. It is distinct from the ECMAScript collection type of the same name. To disambiguate, instances of the ECMAScript collection are consistently referred to as "Set objects" within this specification. 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 the least Relation 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 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.

6.2.4 The Completion Record Specification Type

The Completion Record specification type is 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.

Completion Records have the fields defined in Table 7.

Table 7: Completion Record Fields
Field Name Value Meaning
[[Type]] normal, break, continue, return, or throw The type of completion that occurred.
[[Value]] any value except a Completion Record The value that was produced.
[[Target]] a String or empty The target label for directed control transfers.

The following shorthand terms are sometimes used to refer to Completion Records.

  • normal completion refers to any Completion Record with a [[Type]] value of normal.
  • break completion refers to any Completion Record with a [[Type]] value of break.
  • continue completion refers to any Completion Record with a [[Type]] value of continue.
  • return completion refers to any Completion Record with a [[Type]] value of return.
  • throw completion refers to any Completion Record with a [[Type]] value of throw.
  • abrupt completion refers to any Completion Record with a [[Type]] value other than normal.
  • a normal completion containing some type of value refers to a normal completion that has a value of that type in its [[Value]] field.

Callable objects that are defined in this specification only return a normal completion or a throw completion. Returning any other kind of Completion Record is considered an editorial error.

Implementation-defined callable objects must return either a normal completion or a throw completion.

6.2.4.1 NormalCompletion ( value )

The abstract operation NormalCompletion takes argument value (any value except a Completion Record) and returns a normal completion. It performs the following steps when called:

  1. Return Completion Record { [[Type]]: normal, [[Value]]: value, [[Target]]: empty }.

6.2.4.2 ThrowCompletion ( value )

The abstract operation ThrowCompletion takes argument value (an ECMAScript language value) and returns a throw completion. It performs the following steps when called:

  1. Return Completion Record { [[Type]]: throw, [[Value]]: value, [[Target]]: empty }.

6.2.4.3 ReturnCompletion ( value )

The abstract operation ReturnCompletion takes argument value (an ECMAScript language value) and returns a return completion. It performs the following steps when called:

  1. Return Completion Record { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.

6.2.4.4 UpdateEmpty ( completionRecord, value )

The abstract operation UpdateEmpty takes arguments completionRecord (a Completion Record) and value (any value except a Completion Record) and returns a Completion Record. It performs the following steps when called:

  1. Assert: If completionRecord is either a return completion or a throw completion, then completionRecord.[[Value]] is not empty.
  2. If completionRecord.[[Value]] is not empty, return ? completionRecord.
  3. Return Completion Record { [[Type]]: completionRecord.[[Type]], [[Value]]: value, [[Target]]: completionRecord.[[Target]] }.

6.2.5 The Reference Record Specification Type

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 (possibly not-yet-resolved) property binding; its fields are defined by Table 8.

Table 8: Reference Record Fields
Field Name Value Meaning
[[Base]] an ECMAScript language value, 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]] an ECMAScript language value or a Private Name The name of the binding. Always a String if [[Base]] value is an Environment Record. Otherwise, may be an ECMAScript language value other than a String or a Symbol until ToPropertyKey is performed.
[[Strict]] a Boolean true if the Reference Record originated in strict mode code, false otherwise.
[[ThisValue]] an 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 Reference Records:

6.2.5.1 IsPropertyReference ( V )

The abstract operation IsPropertyReference takes argument V (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. If V.[[Base]] is unresolvable, return false.
  2. If V.[[Base]] is an Environment Record, return false; otherwise return true.

6.2.5.2 IsUnresolvableReference ( V )

The abstract operation IsUnresolvableReference takes argument V (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. If V.[[Base]] is unresolvable, return true; otherwise return false.

6.2.5.3 IsSuperReference ( V )

The abstract operation IsSuperReference takes argument V (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. If V.[[ThisValue]] is not empty, return true; otherwise return false.

6.2.5.4 IsPrivateReference ( V )

The abstract operation IsPrivateReference takes argument V (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. If V.[[ReferencedName]] is a Private Name, return true; otherwise return false.

6.2.5.5 GetValue ( V )

The abstract operation GetValue takes argument V (a Reference Record or an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. If V is not a Reference Record, return V.
  2. If IsUnresolvableReference(V) is true, throw a ReferenceError exception.
  3. If IsPropertyReference(V) is true, then
    1. Let baseObj be ? ToObject(V.[[Base]]).
    2. If IsPrivateReference(V) is true, then
      1. Return ? PrivateGet(baseObj, V.[[ReferencedName]]).
    3. If V.[[ReferencedName]] is not a property key, then
      1. Set V.[[ReferencedName]] to ? ToPropertyKey(V.[[ReferencedName]]).
    4. Return ? baseObj.[[Get]](V.[[ReferencedName]], GetThisValue(V)).
  4. Else,
    1. Let base be V.[[Base]].
    2. Assert: base is an Environment Record.
    3. Return ? base.GetBindingValue(V.[[ReferencedName]], V.[[Strict]]) (see 9.1).
Note

The object that may be created in step 3.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.

6.2.5.6 PutValue ( V, W )

The abstract operation PutValue takes arguments V (a Reference Record or an ECMAScript language value) and W (an ECMAScript language value) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. If V is not a Reference Record, throw a ReferenceError exception.
  2. If IsUnresolvableReference(V) is true, then
    1. If V.[[Strict]] is true, throw a ReferenceError exception.
    2. Let globalObj be GetGlobalObject().
    3. Perform ? Set(globalObj, V.[[ReferencedName]], W, false).
    4. Return unused.
  3. If IsPropertyReference(V) is true, then
    1. Let baseObj be ? ToObject(V.[[Base]]).
    2. If IsPrivateReference(V) is true, then
      1. Return ? PrivateSet(baseObj, V.[[ReferencedName]], W).
    3. If V.[[ReferencedName]] is not a property key, then
      1. Set V.[[ReferencedName]] to ? ToPropertyKey(V.[[ReferencedName]]).
    4. Let succeeded be ? baseObj.[[Set]](V.[[ReferencedName]], W, GetThisValue(V)).
    5. If succeeded is false and V.[[Strict]] is true, throw a TypeError exception.
    6. Return unused.
  4. Else,
    1. Let base be V.[[Base]].
    2. Assert: base is an Environment Record.
    3. Return ? base.SetMutableBinding(V.[[ReferencedName]], W, V.[[Strict]]) (see 9.1).
Note

The object that may be created in step 3.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.

6.2.5.7 GetThisValue ( V )

The abstract operation GetThisValue takes argument V (a Reference Record) and returns an ECMAScript language value. It performs the following steps when called:

  1. Assert: IsPropertyReference(V) is true.
  2. If IsSuperReference(V) is true, return V.[[ThisValue]]; otherwise return V.[[Base]].

6.2.5.8 InitializeReferencedBinding ( V, W )

The abstract operation InitializeReferencedBinding takes arguments V (a Reference Record) and W (an ECMAScript language value) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. Assert: IsUnresolvableReference(V) is false.
  2. Let base be V.[[Base]].
  3. Assert: base is an Environment Record.
  4. Return ? base.InitializeBinding(V.[[ReferencedName]], W).

6.2.5.9 MakePrivateReference ( baseValue, privateIdentifier )

The abstract operation MakePrivateReference takes arguments baseValue (an ECMAScript language value) and privateIdentifier (a String) and returns a Reference Record. It performs the following steps when called:

  1. Let privateEnv be the running execution context's PrivateEnvironment.
  2. Assert: privateEnv is not null.
  3. Let privateName be ResolvePrivateIdentifier(privateEnv, privateIdentifier).
  4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: privateName, [[Strict]]: true, [[ThisValue]]: empty }.

6.2.6 The Property Descriptor Specification Type

The Property Descriptor type is used to explain the manipulation and reification of Object property attributes. A Property Descriptor is a Record with zero or more fields, where each field's name is an attribute name and its value is a corresponding attribute value as specified in 6.1.7.1. 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 (in which case it is a generic 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 corresponding fields defined in Table 3.

The following abstract operations are used in this specification to operate upon Property Descriptor values:

6.2.6.1 IsAccessorDescriptor ( Desc )

The abstract operation IsAccessorDescriptor takes argument Desc (a Property Descriptor) and returns a Boolean. It performs the following steps when called:

  1. If Desc has a [[Get]] field, return true.
  2. If Desc has a [[Set]] field, return true.
  3. Return false.

6.2.6.2 IsDataDescriptor ( Desc )

The abstract operation IsDataDescriptor takes argument Desc (a Property Descriptor) and returns a Boolean. It performs the following steps when called:

  1. If Desc has a [[Value]] field, return true.
  2. If Desc has a [[Writable]] field, return true.
  3. Return false.

6.2.6.3 IsGenericDescriptor ( Desc )

The abstract operation IsGenericDescriptor takes argument Desc (a Property Descriptor) and returns a Boolean. It performs the following steps when called:

  1. If IsAccessorDescriptor(Desc) is true, return false.
  2. If IsDataDescriptor(Desc) is true, return false.
  3. Return true.

6.2.6.4 FromPropertyDescriptor ( Desc )

The abstract operation FromPropertyDescriptor takes argument Desc (a Property Descriptor or undefined) and returns an Object or undefined. It performs the following steps when called:

  1. If Desc is undefined, return undefined.
  2. Let obj be OrdinaryObjectCreate(%Object.prototype%).
  3. Assert: obj is an extensible ordinary object with no own properties.
  4. If Desc has a [[Value]] field, then
    1. Perform ! CreateDataPropertyOrThrow(obj, "value", Desc.[[Value]]).
  5. If Desc has a [[Writable]] field, then
    1. Perform ! CreateDataPropertyOrThrow(obj, "writable", Desc.[[Writable]]).
  6. If Desc has a [[Get]] field, then
    1. Perform ! CreateDataPropertyOrThrow(obj, "get", Desc.[[Get]]).
  7. If Desc has a [[Set]] field, then
    1. Perform ! CreateDataPropertyOrThrow(obj, "set", Desc.[[Set]]).
  8. If Desc has an [[Enumerable]] field, then
    1. Perform ! CreateDataPropertyOrThrow(obj, "enumerable", Desc.[[Enumerable]]).
  9. If Desc has a [[Configurable]] field, then
    1. Perform ! CreateDataPropertyOrThrow(obj, "configurable", Desc.[[Configurable]]).
  10. Return obj.

6.2.6.5 ToPropertyDescriptor ( Obj )

The abstract operation ToPropertyDescriptor takes argument Obj (an ECMAScript language value) and returns either a normal completion containing a Property Descriptor or a throw completion. It performs the following steps when called:

  1. If Obj is not an Object, throw a TypeError exception.
  2. Let desc be a new Property Descriptor that initially has no fields.
  3. Let hasEnumerable be ? HasProperty(Obj, "enumerable").
  4. If hasEnumerable is true, then
    1. Let enumerable be ToBoolean(? Get(Obj, "enumerable")).
    2. Set desc.[[Enumerable]] to enumerable.
  5. Let hasConfigurable be ? HasProperty(Obj, "configurable").
  6. If hasConfigurable is true, then
    1. Let configurable be ToBoolean(? Get(Obj, "configurable")).
    2. Set desc.[[Configurable]] to configurable.
  7. Let hasValue be ? HasProperty(Obj, "value").
  8. If hasValue is true, then
    1. Let value be ? Get(Obj, "value").
    2. Set desc.[[Value]] to value.
  9. Let hasWritable be ? HasProperty(Obj, "writable").
  10. If hasWritable is true, then
    1. Let writable be ToBoolean(? Get(Obj, "writable")).
    2. Set desc.[[Writable]] to writable.
  11. Let hasGet be ? HasProperty(Obj, "get").
  12. 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.
  13. Let hasSet be ? HasProperty(Obj, "set").
  14. 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.
  15. If desc has a [[Get]] field or desc has a [[Set]] field, then
    1. If desc has a [[Value]] field or desc has a [[Writable]] field, throw a TypeError exception.
  16. Return desc.

6.2.6.6 CompletePropertyDescriptor ( Desc )

The abstract operation CompletePropertyDescriptor takes argument Desc (a Property Descriptor) and returns unused. It performs the following steps when called:

  1. Let like be the Record { [[Value]]: undefined, [[Writable]]: false, [[Get]]: undefined, [[Set]]: undefined, [[Enumerable]]: false, [[Configurable]]: false }.
  2. If IsGenericDescriptor(Desc) is true or IsDataDescriptor(Desc) is true, then
    1. If Desc does not have a [[Value]] field, set Desc.[[Value]] to like.[[Value]].
    2. If Desc does not have a [[Writable]] field, set Desc.[[Writable]] to like.[[Writable]].
  3. Else,
    1. If Desc does not have a [[Get]] field, set Desc.[[Get]] to like.[[Get]].
    2. If Desc does not have a [[Set]] field, set Desc.[[Set]] to like.[[Set]].
  4. If Desc does not have an [[Enumerable]] field, set Desc.[[Enumerable]] to like.[[Enumerable]].
  5. If Desc does not have a [[Configurable]] field, set Desc.[[Configurable]] to like.[[Configurable]].
  6. Return unused.

6.2.7 The Environment Record Specification Type

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.

6.2.8 The Abstract Closure Specification Type

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 must be either a normal completion or a throw completion.

Abstract Closures are created inline as part of other algorithms, shown in the following example.

  1. Let addend be 41.
  2. Let closure be a new Abstract Closure with parameters (x) that captures addend and performs the following steps when called:
    1. Return x + addend.
  3. Let val be closure(1).
  4. Assert: val is 42.

6.2.9 Data Blocks

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 in the inclusive interval from 0 to 255. 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-based 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 modelled by Records, defined in the memory model.

The following abstract operations are used in this specification to operate upon Data Block values:

6.2.9.1 CreateByteDataBlock ( size )

The abstract operation CreateByteDataBlock takes argument size (a non-negative integer) and returns either a normal completion containing a Data Block or a throw completion. It performs the following steps when called:

  1. If size > 253 - 1, throw a RangeError exception.
  2. 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.
  3. Set all of the bytes of db to 0.
  4. Return db.

6.2.9.2 CreateSharedByteDataBlock ( size )

The abstract operation CreateSharedByteDataBlock takes argument size (a non-negative integer) and returns either a normal completion containing a Shared Data Block or a throw completion. It performs the following steps when called:

  1. 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.
  2. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  3. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  4. Let zero be « 0 ».
  5. For each index i of db, do
    1. Append WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: db, [[ByteIndex]]: i, [[ElementSize]]: 1, [[Payload]]: zero } to eventsRecord.[[EventList]].
  6. Return db.

6.2.9.3 CopyDataBlockBytes ( toBlock, toIndex, fromBlock, fromIndex, count )

The abstract operation CopyDataBlockBytes takes arguments toBlock (a Data Block or a Shared Data Block), toIndex (a non-negative integer), fromBlock (a Data Block or a Shared Data Block), fromIndex (a non-negative integer), and count (a non-negative integer) and returns unused. It performs the following steps when called:

  1. Assert: fromBlock and toBlock are distinct values.
  2. Let fromSize be the number of bytes in fromBlock.
  3. Assert: fromIndex + countfromSize.
  4. Let toSize be the number of bytes in toBlock.
  5. Assert: toIndex + counttoSize.
  6. Repeat, while count > 0,
    1. If fromBlock is a Shared Data Block, then
      1. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
      2. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
      3. Let bytes be a List whose sole element is a nondeterministically chosen byte value.
      4. 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.
      5. Let readEvent be ReadSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }.
      6. Append readEvent to eventsRecord.[[EventList]].
      7. Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes } to execution.[[ChosenValues]].
      8. If toBlock is a Shared Data Block, then
        1. Append WriteSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: toBlock, [[ByteIndex]]: toIndex, [[ElementSize]]: 1, [[Payload]]: bytes } to eventsRecord.[[EventList]].
      9. Else,
        1. Set toBlock[toIndex] to bytes[0].
    2. Else,
      1. Assert: toBlock is not a Shared Data Block.
      2. Set toBlock[toIndex] to fromBlock[fromIndex].
    3. Set toIndex to toIndex + 1.
    4. Set fromIndex to fromIndex + 1.
    5. Set count to count - 1.
  7. Return unused.

6.2.10 The PrivateElement Specification Type

The PrivateElement type is a Record used in the specification of private class fields, methods, and accessors. Although Property Descriptors are not used for private elements, private fields behave similarly to non-configurable, non-enumerable, writable data properties, private methods behave similarly to non-configurable, non-enumerable, non-writable data properties, and private accessors behave similarly to non-configurable, non-enumerable accessor properties.

Values of the PrivateElement type are Record values whose fields are defined by Table 9. Such values are referred to as PrivateElements.

Table 9: PrivateElement Fields
Field Name Values of the [[Kind]] field for which it is present Value Meaning
[[Key]] All a Private Name The name of the field, method, or accessor.
[[Kind]] All field, method, or accessor The kind of the element.
[[Value]] field and method an ECMAScript language value The value of the field.
[[Get]] accessor a function object or undefined The getter for a private accessor.
[[Set]] accessor a function object or undefined The setter for a private accessor.

6.2.11 The ClassFieldDefinition Record Specification Type

The ClassFieldDefinition type is a Record used in the specification of class fields.

Values of the ClassFieldDefinition type are Record values whose fields are defined by Table 10. Such values are referred to as ClassFieldDefinition Records.

Table 10: ClassFieldDefinition Record Fields
Field Name Value Meaning
[[Name]] a Private Name, a String, or a Symbol The name of the field.
[[Initializer]] an ECMAScript function object or empty The initializer of the field, if any.

6.2.12 Private Names

The Private Name specification type is used to describe a globally unique value (one which differs from any other Private Name, even if they are otherwise indistinguishable) which represents the key of a private class element (field, method, or accessor). Each Private Name has an immutable [[Description]] internal slot which is a String. A Private Name may be installed on any ECMAScript object with PrivateFieldAdd or PrivateMethodOrAccessorAdd, and then read or written using PrivateGet and PrivateSet.

6.2.13 The ClassStaticBlockDefinition Record Specification Type

A ClassStaticBlockDefinition Record is a Record value used to encapsulate the executable code for a class static initialization block.

ClassStaticBlockDefinition Records have the fields listed in Table 11.

Table 11: ClassStaticBlockDefinition Record Fields
Field Name Value Meaning
[[BodyFunction]] an ECMAScript function object The function object to be called during static initialization of a class.

7 Abstract Operations

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.

7.1 Type Conversion

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.

7.1.1 ToPrimitive ( input [ , preferredType ] )

The abstract operation ToPrimitive takes argument input (an ECMAScript language value) and optional argument preferredType (string or number) and returns either a normal completion containing an ECMAScript language value or a throw completion. 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:

  1. If input is an Object, then
    1. Let exoticToPrim be ? GetMethod(input, %Symbol.toPrimitive%).
    2. If exoticToPrim is not undefined, then
      1. If preferredType is not present, then
        1. Let hint be "default".
      2. Else if preferredType is string, then
        1. Let hint be "string".
      3. Else,
        1. Assert: preferredType is number.
        2. Let hint be "number".
      4. Let result be ? Call(exoticToPrim, input, « hint »).
      5. If result is not an Object, return result.
      6. Throw a TypeError exception.
    3. If preferredType is not present, let preferredType be number.
    4. Return ? OrdinaryToPrimitive(input, preferredType).
  2. Return input.
Note

When ToPrimitive is called without a hint, then it generally behaves as if the hint were number. However, objects may over-ride this behaviour by defining a %Symbol.toPrimitive% method. Of the objects defined in this specification only Dates (see 21.4.4.45) and Symbol objects (see 20.4.3.5) over-ride the default ToPrimitive behaviour. Dates treat the absence of a hint as if the hint were string.

7.1.1.1 OrdinaryToPrimitive ( O, hint )

The abstract operation OrdinaryToPrimitive takes arguments O (an Object) and hint (string or number) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. If hint is string, then
    1. Let methodNames be « "toString", "valueOf" ».
  2. Else,
    1. Let methodNames be « "valueOf", "toString" ».
  3. For each element name of methodNames, do
    1. Let method be ? Get(O, name).
    2. If IsCallable(method) is true, then
      1. Let result be ? Call(method, O).
      2. If result is not an Object, return result.
  4. Throw a TypeError exception.

7.1.2 ToBoolean ( argument )

The abstract operation ToBoolean takes argument argument (an ECMAScript language value) and returns a Boolean. It converts argument to a value of type Boolean. It performs the following steps when called:

  1. If argument is a Boolean, return argument.
  2. If argument is one of undefined, null, +0𝔽, -0𝔽, NaN, 0, or the empty String, return false.
  3. If the host is a web browser or otherwise supports The [[IsHTMLDDA]] Internal Slot, then
    1. If argument is an Object and argument has an [[IsHTMLDDA]] internal slot, return false.
  4. Return true.

7.1.3 ToNumeric ( value )

The abstract operation ToNumeric takes argument value (an ECMAScript language value) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. It returns value converted to a Number or a BigInt. It performs the following steps when called:

  1. Let primValue be ? ToPrimitive(value, number).
  2. If primValue is a BigInt, return primValue.
  3. Return ? ToNumber(primValue).

7.1.4 ToNumber ( argument )

The abstract operation ToNumber takes argument argument (an ECMAScript language value) and returns either a normal completion containing a Number or a throw completion. It converts argument to a value of type Number. It performs the following steps when called:

  1. If argument is a Number, return argument.
  2. If argument is either a Symbol or a BigInt, throw a TypeError exception.
  3. If argument is undefined, return NaN.
  4. If argument is either null or false, return +0𝔽.
  5. If argument is true, return 1𝔽.
  6. If argument is a String, return StringToNumber(argument).
  7. Assert: argument is an Object.
  8. Let primValue be ? ToPrimitive(argument, number).
  9. Assert: primValue is not an Object.
  10. Return ? ToNumber(primValue).

7.1.4.1 ToNumber Applied to the String Type

The abstract operation StringToNumber specifies how to convert a String value to a Number value, using the following grammar.

Syntax

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.9.3)

Note

Some differences should be noted between the syntax of a StringNumericLiteral and a NumericLiteral:

7.1.4.1.1 StringToNumber ( str )

The abstract operation StringToNumber takes argument str (a String) and returns a Number. It performs the following steps when called:

  1. Let literal be ParseText(str, StringNumericLiteral).
  2. If literal is a List of errors, return NaN.
  3. Return the StringNumericValue of literal.

7.1.4.1.2 Runtime Semantics: StringNumericValue

The syntax-directed operation StringNumericValue takes no arguments and returns a Number.

Note

The conversion of a StringNumericLiteral to a Number value is similar overall to the determination of the NumericValue of a NumericLiteral (see 12.9.3), but some of the details are different.

It is defined piecewise over the following productions:

StringNumericLiteral ::: StrWhiteSpaceopt
  1. Return +0𝔽.
StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt
  1. Return the StringNumericValue of StrNumericLiteral.
StrNumericLiteral ::: NonDecimalIntegerLiteral
  1. Return 𝔽(MV of NonDecimalIntegerLiteral).
StrDecimalLiteral ::: - StrUnsignedDecimalLiteral
  1. Let a be the StringNumericValue of StrUnsignedDecimalLiteral.
  2. If a is +0𝔽, return -0𝔽.
  3. Return -a.
StrUnsignedDecimalLiteral ::: Infinity
  1. Return +∞𝔽.
StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigitsopt ExponentPartopt
  1. Let a be the MV of the first DecimalDigits.
  2. If the second DecimalDigits is present, then
    1. Let b be the MV of the second DecimalDigits.
    2. Let n be the number of code points in the second DecimalDigits.
  3. Else,
    1. Let b be 0.
    2. Let n be 0.
  4. If ExponentPart is present, let e be the MV of ExponentPart; otherwise let e be 0.
  5. Return RoundMVResult((a + (b × 10-n)) × 10e).
StrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPartopt
  1. Let b be the MV of DecimalDigits.
  2. If ExponentPart is present, let e be the MV of ExponentPart; otherwise let e be 0.
  3. Let n be the number of code points in DecimalDigits.
  4. Return RoundMVResult(b × 10e - n).
StrUnsignedDecimalLiteral ::: DecimalDigits ExponentPartopt
  1. Let a be the MV of DecimalDigits.
  2. If ExponentPart is present, let e be the MV of ExponentPart; otherwise let e be 0.
  3. Return RoundMVResult(a × 10e).

7.1.4.1.3 RoundMVResult ( n )

The abstract operation RoundMVResult takes argument n (a mathematical value) and returns a Number. It converts n to a Number in an implementation-defined manner. For the purposes of this abstract operation, a digit is significant if it is not zero or there is a non-zero digit to its left and there is a non-zero digit to its right. For the purposes of this abstract operation, "the mathematical value denoted by" a representation of a mathematical value is the inverse of "the decimal representation of" a mathematical value. It performs the following steps when called:

  1. If the decimal representation of n has 20 or fewer significant digits, return 𝔽(n).
  2. Let option1 be the mathematical value denoted by the result of replacing each significant digit in the decimal representation of n after the 20th with a 0 digit.
  3. Let option2 be the mathematical value denoted by the result of replacing each significant digit in the decimal representation of n after the 20th with a 0 digit and then incrementing it at the 20th position (with carrying as necessary).
  4. Let chosen be an implementation-defined choice of either option1 or option2.
  5. Return 𝔽(chosen).

7.1.5 ToIntegerOrInfinity ( argument )

The abstract operation ToIntegerOrInfinity takes argument argument (an ECMAScript language value) and returns either a normal completion containing either an integer, +∞, or -∞, or a throw completion. It converts argument to an integer representing its Number value with fractional part truncated, or to +∞ or -∞ when that Number value is infinite. It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is one of NaN, +0𝔽, or -0𝔽, return 0.
  3. If number is +∞𝔽, return +∞.
  4. If number is -∞𝔽, return -∞.
  5. Return truncate((number)).
Note
𝔽(ToIntegerOrInfinity(x)) never returns -0𝔽 for any value of x. The truncation of the fractional part is performed after converting x to a mathematical value.

7.1.6 ToInt32 ( argument )

The abstract operation ToInt32 takes argument argument (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. It converts argument to one of 232 integral Number values in the inclusive interval from 𝔽(-231) to 𝔽(231 - 1). It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  3. Let int be truncate((number)).
  4. Let int32bit be int modulo 232.
  5. 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𝔽.

7.1.7 ToUint32 ( argument )

The abstract operation ToUint32 takes argument argument (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. It converts argument to one of 232 integral Number values in the inclusive interval from +0𝔽 to 𝔽(232 - 1). It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  3. Let int be truncate((number)).
  4. Let int32bit be int modulo 232.
  5. 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𝔽.

7.1.8 ToInt16 ( argument )

The abstract operation ToInt16 takes argument argument (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. It converts argument to one of 216 integral Number values in the inclusive interval from 𝔽(-215) to 𝔽(215 - 1). It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  3. Let int be truncate((number)).
  4. Let int16bit be int modulo 216.
  5. If int16bit ≥ 215, return 𝔽(int16bit - 216); otherwise return 𝔽(int16bit).

7.1.9 ToUint16 ( argument )

The abstract operation ToUint16 takes argument argument (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. It converts argument to one of 216 integral Number values in the inclusive interval from +0𝔽 to 𝔽(216 - 1). It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  3. Let int be truncate((number)).
  4. Let int16bit be int modulo 216.
  5. 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𝔽.

7.1.10 ToInt8 ( argument )

The abstract operation ToInt8 takes argument argument (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. It converts argument to one of 28 integral Number values in the inclusive interval from -128𝔽 to 127𝔽. It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  3. Let int be truncate((number)).
  4. Let int8bit be int modulo 28.
  5. If int8bit ≥ 27, return 𝔽(int8bit - 28); otherwise return 𝔽(int8bit).

7.1.11 ToUint8 ( argument )

The abstract operation ToUint8 takes argument argument (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. It converts argument to one of 28 integral Number values in the inclusive interval from +0𝔽 to 255𝔽. It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  3. Let int be truncate((number)).
  4. Let int8bit be int modulo 28.
  5. Return 𝔽(int8bit).

7.1.12 ToUint8Clamp ( argument )

The abstract operation ToUint8Clamp takes argument argument (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. It clamps and rounds argument to one of 28 integral Number values in the inclusive interval from +0𝔽 to 255𝔽. It performs the following steps when called:

  1. Let number be ? ToNumber(argument).
  2. If number is NaN, return +0𝔽.
  3. Let mv be the extended mathematical value of number.
  4. Let clamped be the result of clamping mv between 0 and 255.
  5. Let f be floor(clamped).
  6. If clamped < f + 0.5, return 𝔽(f).
  7. If clamped > f + 0.5, return 𝔽(f + 1).
  8. If f is even, return 𝔽(f); otherwise return 𝔽(f + 1).
Note

Unlike most other ECMAScript integer conversion operations, ToUint8Clamp rounds rather than truncates non-integral values. It also uses “round half to even” tie-breaking, which differs from the “round half up” tie-breaking of Math.round.

7.1.13 ToBigInt ( argument )

The abstract operation ToBigInt takes argument argument (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. 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:

  1. Let prim be ? ToPrimitive(argument, number).
  2. Return the value that prim corresponds to in Table 12.
Table 12: 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
  1. Let n be StringToBigInt(prim).
  2. If n is undefined, throw a SyntaxError exception.
  3. Return n.
Symbol Throw a TypeError exception.

7.1.14 StringToBigInt ( str )

The abstract operation StringToBigInt takes argument str (a String) and returns a BigInt or undefined. It performs the following steps when called:

  1. Let literal be ParseText(str, StringIntegerLiteral).
  2. If literal is a List of errors, return undefined.
  3. Let mv be the MV of literal.
  4. Assert: mv is an integer.
  5. Return (mv).

7.1.14.1 StringIntegerLiteral Grammar

StringToBigInt uses the following grammar.

Syntax

StringIntegerLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrIntegerLiteral StrWhiteSpaceopt StrIntegerLiteral ::: SignedInteger[~Sep] NonDecimalIntegerLiteral[~Sep]

7.1.14.2 Runtime Semantics: MV

7.1.15 ToBigInt64 ( argument )

The abstract operation ToBigInt64 takes argument argument (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. It converts argument to one of 264 BigInt values in the inclusive interval from (-263) to (263 - 1). It performs the following steps when called:

  1. Let n be ? ToBigInt(argument).
  2. Let int64bit be (n) modulo 264.
  3. If int64bit ≥ 263, return (int64bit - 264); otherwise return (int64bit).

7.1.16 ToBigUint64 ( argument )

The abstract operation ToBigUint64 takes argument argument (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. It converts argument to one of 264 BigInt values in the inclusive interval from 0 to (264 - 1). It performs the following steps when called:

  1. Let n be ? ToBigInt(argument).
  2. Let int64bit be (n) modulo 264.
  3. Return (int64bit).

7.1.17 ToString ( argument )

The abstract operation ToString takes argument argument (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. It converts argument to a value of type String. It performs the following steps when called:

  1. If argument is a String, return argument.
  2. If argument is a Symbol, throw a TypeError exception.
  3. If argument is undefined, return "undefined".
  4. If argument is null, return "null".
  5. If argument is true, return "true".
  6. If argument is false, return "false".
  7. If argument is a Number, return Number::toString(argument, 10).
  8. If argument is a BigInt, return BigInt::toString(argument, 10).
  9. Assert: argument is an Object.
  10. Let primValue be ? ToPrimitive(argument, string).
  11. Assert: primValue is not an Object.
  12. Return ? ToString(primValue).

7.1.18 ToObject ( argument )

The abstract operation ToObject takes argument argument (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It converts argument to a value of type Object. It performs the following steps when called:

  1. If argument is either undefined or null, throw a TypeError exception.
  2. If argument is a Boolean, return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 20.3 for a description of Boolean objects.
  3. If argument is a Number, return a new Number object whose [[NumberData]] internal slot is set to argument. See 21.1 for a description of Number objects.
  4. If argument is a String, return a new String object whose [[StringData]] internal slot is set to argument. See 22.1 for a description of String objects.
  5. If argument is a Symbol, return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 20.4 for a description of Symbol objects.
  6. If argument is a BigInt, return a new BigInt object whose [[BigIntData]] internal slot is set to argument. See 21.2 for a description of BigInt objects.
  7. Assert: argument is an Object.
  8. Return argument.

7.1.19 ToPropertyKey ( argument )

The abstract operation ToPropertyKey takes argument argument (an ECMAScript language value) and returns either a normal completion containing a property key or a throw completion. It converts argument to a value that can be used as a property key. It performs the following steps when called:

  1. Let key be ? ToPrimitive(argument, string).
  2. If key is a Symbol, then
    1. Return key.
  3. Return ! ToString(key).

7.1.20 ToLength ( argument )

The abstract operation ToLength takes argument argument (an ECMAScript language value) and returns either a normal completion containing a non-negative integral Number or a throw completion. It clamps and truncates argument to a non-negative integral Number suitable for use as the length of an array-like object. It performs the following steps when called:

  1. Let len be ? ToIntegerOrInfinity(argument).
  2. If len ≤ 0, return +0𝔽.
  3. Return 𝔽(min(len, 253 - 1)).

7.1.21 CanonicalNumericIndexString ( argument )

The abstract operation CanonicalNumericIndexString takes argument argument (a String) and returns a Number or undefined. If argument is either "-0" or exactly matches ToString(n) for some Number value n, it returns the respective Number value. Otherwise, it returns undefined. It performs the following steps when called:

  1. If argument is "-0", return -0𝔽.
  2. Let n be ! ToNumber(argument).
  3. If ! ToString(n) is argument, return n.
  4. Return undefined.

A canonical numeric string is any String for which the CanonicalNumericIndexString abstract operation does not return undefined.

7.1.22 ToIndex ( value )

The abstract operation ToIndex takes argument value (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. It converts value to an integer and returns that integer if it is non-negative and corresponds with an integer index. Otherwise, it throws an exception. It performs the following steps when called:

  1. Let integer be ? ToIntegerOrInfinity(value).
  2. If integer is not in the inclusive interval from 0 to 253 - 1, throw a RangeError exception.
  3. Return integer.

7.2 Testing and Comparison Operations

7.2.1 RequireObjectCoercible ( argument )

The abstract operation RequireObjectCoercible takes argument argument (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It throws an error if argument is a value that cannot be converted to an Object using ToObject. It performs the following steps when called:

  1. If argument is either undefined or null, throw a TypeError exception.
  2. Return unused.

7.2.2 IsArray ( argument )

The abstract operation IsArray takes argument argument (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. If argument is not an Object, return false.
  2. If argument is an Array exotic object, return true.
  3. If argument is a Proxy exotic object, then
    1. Perform ? ValidateNonRevokedProxy(argument).
    2. Let proxyTarget be argument.[[ProxyTarget]].
    3. Return ? IsArray(proxyTarget).
  4. Return false.

7.2.3 IsCallable ( argument )

The abstract operation IsCallable takes argument argument (an ECMAScript language value) and returns a Boolean. It determines if argument is a callable function with a [[Call]] internal method. It performs the following steps when called:

  1. If argument is not an Object, return false.
  2. If argument has a [[Call]] internal method, return true.
  3. Return false.

7.2.4 IsConstructor ( argument )

The abstract operation IsConstructor takes argument argument (an ECMAScript language value) and returns a Boolean. It determines if argument is a function object with a [[Construct]] internal method. It performs the following steps when called:

  1. If argument is not an Object, return false.
  2. If argument has a [[Construct]] internal method, return true.
  3. Return false.

7.2.5 IsExtensible ( O )

The abstract operation IsExtensible takes argument O (an Object) and returns either a normal completion containing a Boolean or a throw completion. It is used to determine whether additional properties can be added to O. It performs the following steps when called:

  1. Return ? O.[[IsExtensible]]().

7.2.6 IsRegExp ( argument )

The abstract operation IsRegExp takes argument argument (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. If argument is not an Object, return false.
  2. Let matcher be ? Get(argument, %Symbol.match%).
  3. If matcher is not undefined, return ToBoolean(matcher).
  4. If argument has a [[RegExpMatcher]] internal slot, return true.
  5. Return false.

7.2.7 Static Semantics: IsStringWellFormedUnicode ( string )

The abstract operation IsStringWellFormedUnicode takes argument string (a String) and returns a Boolean. It interprets string as a sequence of UTF-16 encoded code points, as described in 6.1.4, and determines whether it is a well formed UTF-16 sequence. It performs the following steps when called:

  1. Let len be the length of string.
  2. Let k be 0.
  3. Repeat, while k < len,
    1. Let cp be CodePointAt(string, k).
    2. If cp.[[IsUnpairedSurrogate]] is true, return false.
    3. Set k to k + cp.[[CodeUnitCount]].
  4. Return true.

7.2.8 SameType ( x, y )

The abstract operation SameType takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. It determines whether or not the two arguments are the same type. It performs the following steps when called:

  1. If x is undefined and y is undefined, return true.
  2. If x is null and y is null, return true.
  3. If x is a Boolean and y is a Boolean, return true.
  4. If x is a Number and y is a Number, return true.
  5. If x is a BigInt and y is a BigInt, return true.
  6. If x is a Symbol and y is a Symbol, return true.
  7. If x is a String and y is a String, return true.
  8. If x is an Object and y is an Object, return true.
  9. Return false.

7.2.9 SameValue ( x, y )

The abstract operation SameValue takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. It determines whether or not the two arguments are the same value. It performs the following steps when called:

  1. If SameType(x, y) is false, return false.
  2. If x is a Number, then
    1. Return Number::sameValue(x, y).
  3. Return SameValueNonNumber(x, y).
Note

This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽.

7.2.10 SameValueZero ( x, y )

The abstract operation SameValueZero takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. It determines whether or not the two arguments are the same value (ignoring the difference between +0𝔽 and -0𝔽). It performs the following steps when called:

  1. If SameType(x, y) is false, return false.
  2. If x is a Number, then
    1. Return Number::sameValueZero(x, y).
  3. Return SameValueNonNumber(x, y).
Note

SameValueZero differs from SameValue only in that it treats +0𝔽 and -0𝔽 as equivalent.

7.2.11 SameValueNonNumber ( x, y )

The abstract operation SameValueNonNumber takes arguments x (an ECMAScript language value, but not a Number) and y (an ECMAScript language value, but not a Number) and returns a Boolean. It performs the following steps when called:

  1. Assert: SameType(x, y) is true.
  2. If x is either undefined or null, return true.
  3. If x is a BigInt, then
    1. Return BigInt::equal(x, y).
  4. If x is a String, then
    1. If x and y have the same length and the same code units in the same positions, return true; otherwise return false.
  5. If x is a Boolean, then
    1. If x and y are both true or both false, return true; otherwise return false.
  6. NOTE: All other ECMAScript language values are compared by identity.
  7. If x is y, return true; otherwise return false.
Note 1
For expository purposes, some cases are handled separately within this algorithm even if it is unnecessary to do so.
Note 2
The specifics of what "x is y" means are detailed in 5.2.7.

7.2.12 IsLessThan ( x, y, LeftFirst )

The abstract operation IsLessThan takes arguments x (an ECMAScript language value), y (an ECMAScript language value), and LeftFirst (a Boolean) and returns either a normal completion containing either a Boolean or undefined, or a throw completion. It provides the semantics for the comparison x < y, returning true, false, or undefined (which indicates that at least one operand is NaN). The LeftFirst 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. If LeftFirst is true, 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. It performs the following steps when called:

  1. If LeftFirst is true, then
    1. Let px be ? ToPrimitive(x, number).
    2. Let py be ? ToPrimitive(y, number).
  2. Else,
    1. NOTE: The order of evaluation needs to be reversed to preserve left to right evaluation.
    2. Let py be ? ToPrimitive(y, number).
    3. Let px be ? ToPrimitive(x, number).
  3. If px is a String and py is a String, then
    1. Let lx be the length of px.
    2. Let ly be the length of py.
    3. For each integer i such that 0 ≤ i < min(lx, ly), in ascending order, do
      1. Let cx be the numeric value of the code unit at index i within px.
      2. Let cy be the numeric value of the code unit at index i within py.
      3. If cx < cy, return true.
      4. If cx > cy, return false.
    4. If lx < ly, return true; otherwise return false.
  4. Else,
    1. If px is a BigInt and py is a String, then
      1. Let ny be StringToBigInt(py).
      2. If ny is undefined, return undefined.
      3. Return BigInt::lessThan(px, ny).
    2. If px is a String and py is a BigInt, then
      1. Let nx be StringToBigInt(px).
      2. If nx is undefined, return undefined.
      3. Return BigInt::lessThan(nx, py).
    3. NOTE: Because px and py are primitive values, evaluation order is not important.
    4. Let nx be ? ToNumeric(px).
    5. Let ny be ? ToNumeric(py).
    6. If SameType(nx, ny) is true, then
      1. If nx is a Number, then
        1. Return Number::lessThan(nx, ny).
      2. Else,
        1. Assert: nx is a BigInt.
        2. Return BigInt::lessThan(nx, ny).
    7. Assert: nx is a BigInt and ny is a Number, or nx is a Number and ny is a BigInt.
    8. If nx or ny is NaN, return undefined.
    9. If nx is -∞𝔽 or ny is +∞𝔽, return true.
    10. If nx is +∞𝔽 or ny is -∞𝔽, return false.
    11. If (nx) < (ny), return true; otherwise return false.
Note 1

Step 3 differs from step 1.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 UTF-16 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 but not in the same normalization form could test as unequal. Also note that lexicographic ordering by code unit differs from ordering by code point for Strings containing surrogate pairs.

7.2.13 IsLooselyEqual ( x, y )

The abstract operation IsLooselyEqual takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It provides the semantics for the == operator. It performs the following steps when called:

  1. If SameType(x, y) is true, then
    1. Return IsStrictlyEqual(x, y).
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If the host is a web browser or otherwise supports The [[IsHTMLDDA]] Internal Slot, then
    1. If x is an Object, x has an [[IsHTMLDDA]] internal slot, and y is either undefined or null, return true.
    2. If x is either undefined or null, y is an Object, and y has an [[IsHTMLDDA]] internal slot, return true.
  5. If x is a Number and y is a String, return ! IsLooselyEqual(x, ! ToNumber(y)).
  6. If x is a String and y is a Number, return ! IsLooselyEqual(! ToNumber(x), y).
  7. If x is a BigInt and y is a String, then
    1. Let n be StringToBigInt(y).
    2. If n is undefined, return false.
    3. Return ! IsLooselyEqual(x, n).
  8. If x is a String and y is a BigInt, return ! IsLooselyEqual(y, x).
  9. If x is a Boolean, return ! IsLooselyEqual(! ToNumber(x), y).
  10. If y is a Boolean, return ! IsLooselyEqual(x, ! ToNumber(y)).
  11. If x is either a String, a Number, a BigInt, or a Symbol and y is an Object, return ! IsLooselyEqual(x, ? ToPrimitive(y)).
  12. If x is an Object and y is either a String, a Number, a BigInt, or a Symbol, return ! IsLooselyEqual(? ToPrimitive(x), y).
  13. If x is a BigInt and y is a Number, or if x is a Number and y is a BigInt, then
    1. If x is not finite or y is not finite, return false.
    2. If (x) = (y), return true; otherwise return false.
  14. Return false.

7.2.14 IsStrictlyEqual ( x, y )

The abstract operation IsStrictlyEqual takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. It provides the semantics for the === operator. It performs the following steps when called:

  1. If SameType(x, y) is false, return false.
  2. If x is a Number, then
    1. Return Number::equal(x, y).
  3. Return SameValueNonNumber(x, y).
Note

This algorithm differs from the SameValue Algorithm in its treatment of signed zeroes and NaNs.

7.3 Operations on Objects

7.3.1 MakeBasicObject ( internalSlotsList )

The abstract operation MakeBasicObject takes argument internalSlotsList (a List of internal slot names) and returns an Object. 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:

  1. Set internalSlotsList to the list-concatenation of internalSlotsList and « [[PrivateElements]] ».
  2. Let obj be a newly created object with an internal slot for each name in internalSlotsList.
  3. NOTE: As described in Object Internal Methods and Internal Slots, the initial value of each such internal slot is undefined unless specified otherwise.
  4. Set obj.[[PrivateElements]] to a new empty List.
  5. Set obj's essential internal methods to the default ordinary object definitions specified in 10.1.
  6. Assert: If the caller will not be overriding both obj's [[GetPrototypeOf]] and [[SetPrototypeOf]] essential internal methods, then internalSlotsList contains [[Prototype]].
  7. Assert: If the caller will not be overriding all of obj's [[SetPrototypeOf]], [[IsExtensible]], and [[PreventExtensions]] essential internal methods, then internalSlotsList contains [[Extensible]].
  8. If internalSlotsList contains [[Extensible]], set obj.[[Extensible]] to true.
  9. 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.

7.3.2 Get ( O, P )

The abstract operation Get takes arguments O (an Object) and P (a property key) and returns either a normal completion containing an ECMAScript language value or a throw completion. It is used to retrieve the value of a specific property of an object. It performs the following steps when called:

  1. Return ? O.[[Get]](P, O).

7.3.3 GetV ( V, P )

The abstract operation GetV takes arguments V (an ECMAScript language value) and P (a property key) and returns either a normal completion containing an ECMAScript language value or a throw completion. 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:

  1. Let O be ? ToObject(V).
  2. Return ? O.[[Get]](P, V).

7.3.4 Set ( O, P, V, Throw )

The abstract operation Set takes arguments O (an Object), P (a property key), V (an ECMAScript language value), and Throw (a Boolean) and returns either a normal completion containing unused or a throw completion. 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:

  1. Let success be ? O.[[Set]](P, V, O).
  2. If success is false and Throw is true, throw a TypeError exception.
  3. Return unused.

7.3.5 CreateDataProperty ( O, P, V )

The abstract operation CreateDataProperty takes arguments O (an Object), P (a property key), and V (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It is used to create a new own property of an object. It performs the following steps when called:

  1. Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
  2. 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.

7.3.6 CreateDataPropertyOrThrow ( O, P, V )

The abstract operation CreateDataPropertyOrThrow takes arguments O (an Object), P (a property key), and V (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. 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:

  1. Let success be ? CreateDataProperty(O, P, V).
  2. If success is false, throw a TypeError exception.
  3. Return unused.
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.

7.3.7 CreateNonEnumerableDataPropertyOrThrow ( O, P, V )

The abstract operation CreateNonEnumerableDataPropertyOrThrow takes arguments O (an Object), P (a property key), and V (an ECMAScript language value) and returns unused. It is used to create a new non-enumerable own property of an ordinary object. It performs the following steps when called:

  1. Assert: O is an ordinary, extensible object with no non-configurable properties.
  2. Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }.
  3. Perform ! DefinePropertyOrThrow(O, P, newDesc).
  4. Return unused.
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 except it is not enumerable. Normally, the property will not already exist. If it does exist, DefinePropertyOrThrow is guaranteed to complete normally.

7.3.8 DefinePropertyOrThrow ( O, P, desc )

The abstract operation DefinePropertyOrThrow takes arguments O (an Object), P (a property key), and desc (a Property Descriptor) and returns either a normal completion containing unused or a throw completion. 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:

  1. Let success be ? O.[[DefineOwnProperty]](P, desc).
  2. If success is false, throw a TypeError exception.
  3. Return unused.

7.3.9 DeletePropertyOrThrow ( O, P )

The abstract operation DeletePropertyOrThrow takes arguments O (an Object) and P (a property key) and returns either a normal completion containing unused or a throw completion. 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:

  1. Let success be ? O.[[Delete]](P).
  2. If success is false, throw a TypeError exception.
  3. Return unused.

7.3.10 GetMethod ( V, P )

The abstract operation GetMethod takes arguments V (an ECMAScript language value) and P (a property key) and returns either a normal completion containing either a function object or undefined, or a throw completion. 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:

  1. Let func be ? GetV(V, P).
  2. If func is either undefined or null, return undefined.
  3. If IsCallable(func) is false, throw a TypeError exception.
  4. Return func.

7.3.11 HasProperty ( O, P )

The abstract operation HasProperty takes arguments O (an Object) and P (a property key) and returns either a normal completion containing a Boolean or a throw completion. It is used to determine whether an object has a property with the specified property key. The property may be either own or inherited. It performs the following steps when called:

  1. Return ? O.[[HasProperty]](P).

7.3.12 HasOwnProperty ( O, P )

The abstract operation HasOwnProperty takes arguments O (an Object) and P (a property key) and returns either a normal completion containing a Boolean or a throw completion. It is used to determine whether an object has an own property with the specified property key. It performs the following steps when called:

  1. Let desc be ? O.[[GetOwnProperty]](P).
  2. If desc is undefined, return false.
  3. Return true.

7.3.13 Call ( F, V [ , argumentsList ] )

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) and returns either a normal completion containing an ECMAScript language value or a throw completion. 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:

  1. If argumentsList is not present, set argumentsList to a new empty List.
  2. If IsCallable(F) is false, throw a TypeError exception.
  3. Return ? F.[[Call]](V, argumentsList).

7.3.14 Construct ( F [ , argumentsList [ , newTarget ] ] )

The abstract operation Construct takes argument F (a constructor) and optional arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. 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:

  1. If newTarget is not present, set newTarget to F.
  2. If argumentsList is not present, set argumentsList to a new empty List.
  3. Return ? F.[[Construct]](argumentsList, newTarget).
Note

If newTarget is not present, this operation is equivalent to: new F(...argumentsList)

7.3.15 SetIntegrityLevel ( O, level )

The abstract operation SetIntegrityLevel takes arguments O (an Object) and level (sealed or frozen) and returns either a normal completion containing a Boolean or a throw completion. It is used to fix the set of own properties of an object. It performs the following steps when called:

  1. Let status be ? O.[[PreventExtensions]]().
  2. If status is false, return false.
  3. Let keys be ? O.[[OwnPropertyKeys]]().
  4. If level is sealed, then
    1. For each element k of keys, do
      1. Perform ? DefinePropertyOrThrow(O, k, PropertyDescriptor { [[Configurable]]: false }).
  5. Else,
    1. Assert: level is frozen.
    2. For each element k of keys, do
      1. Let currentDesc be ? O.[[GetOwnProperty]](k).
      2. If currentDesc is not undefined, then
        1. If IsAccessorDescriptor(currentDesc) is true, then
          1. Let desc be the PropertyDescriptor { [[Configurable]]: false }.
        2. Else,
          1. Let desc be the PropertyDescriptor { [[Configurable]]: false, [[Writable]]: false }.
        3. Perform ? DefinePropertyOrThrow(O, k, desc).
  6. Return true.

7.3.16 TestIntegrityLevel ( O, level )

The abstract operation TestIntegrityLevel takes arguments O (an Object) and level (sealed or frozen) and returns either a normal completion containing a Boolean or a throw completion. It is used to determine if the set of own properties of an object are fixed. It performs the following steps when called:

  1. Let extensible be ? IsExtensible(O).
  2. If extensible is true, return false.
  3. NOTE: If the object is extensible, none of its properties are examined.
  4. Let keys be ? O.[[OwnPropertyKeys]]().
  5. For each element k of keys, do
    1. Let currentDesc be ? O.[[GetOwnProperty]](k).
    2. If currentDesc is not undefined, then
      1. If currentDesc.[[Configurable]] is true, return false.
      2. If level is frozen and IsDataDescriptor(currentDesc) is true, then
        1. If currentDesc.[[Writable]] is true, return false.
  6. Return true.

7.3.17 CreateArrayFromList ( elements )

The abstract operation CreateArrayFromList takes argument elements (a List of ECMAScript language values) and returns an Array. It is used to create an Array whose elements are provided by elements. It performs the following steps when called:

  1. Let array be ! ArrayCreate(0).
  2. Let n be 0.
  3. For each element e of elements, do
    1. Perform ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), e).
    2. Set n to n + 1.
  4. Return array.

7.3.18 LengthOfArrayLike ( obj )

The abstract operation LengthOfArrayLike takes argument obj (an Object) and returns either a normal completion containing a non-negative integer or a throw completion. It returns the value of the "length" property of an array-like object. It performs the following steps when called:

  1. Return (? ToLength(? Get(obj, "length"))).

An array-like object is any object for which this operation returns a normal completion.

Note 1
Typically, an array-like object would also have some properties with integer index names. However, that is not a requirement of this definition.
Note 2
Arrays and String objects are examples of array-like objects.

7.3.19 CreateListFromArrayLike ( obj [ , validElementTypes ] )

The abstract operation CreateListFromArrayLike takes argument obj (an ECMAScript language value) and optional argument validElementTypes (all or property-key) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It is used to create a List value whose elements are provided by the indexed properties of obj. validElementTypes indicates the types of values that are allowed as elements. It performs the following steps when called:

  1. If validElementTypes is not present, set validElementTypes to all.
  2. If obj is not an Object, throw a TypeError exception.
  3. Let len be ? LengthOfArrayLike(obj).
  4. Let list be a new empty List.
  5. Let index be 0.
  6. Repeat, while index < len,
    1. Let indexName be ! ToString(𝔽(index)).
    2. Let next be ? Get(obj, indexName).
    3. If validElementTypes is property-key and next is not a property key, throw a TypeError exception.
    4. Append next to list.
    5. Set index to index + 1.
  7. Return list.

7.3.20 Invoke ( V, P [ , argumentsList ] )

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) and returns either a normal completion containing an ECMAScript language value or a throw completion. 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:

  1. If argumentsList is not present, set argumentsList to a new empty List.
  2. Let func be ? GetV(V, P).
  3. Return ? Call(func, V, argumentsList).

7.3.21 OrdinaryHasInstance ( C, O )

The abstract operation OrdinaryHasInstance takes arguments C (an ECMAScript language value) and O (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. 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:

  1. If IsCallable(C) is false, return false.
  2. If C has a [[BoundTargetFunction]] internal slot, then
    1. Let BC be C.[[BoundTargetFunction]].
    2. Return ? InstanceofOperator(O, BC).
  3. If O is not an Object, return false.
  4. Let P be ? Get(C, "prototype").
  5. If P is not an Object, throw a TypeError exception.
  6. Repeat,
    1. Set O to ? O.[[GetPrototypeOf]]().
    2. If O is null, return false.
    3. If SameValue(P, O) is true, return true.

7.3.22 SpeciesConstructor ( O, defaultConstructor )

The abstract operation SpeciesConstructor takes arguments O (an Object) and defaultConstructor (a constructor) and returns either a normal completion containing a constructor or a throw completion. 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 %Symbol.species% property cannot be found starting from O. It performs the following steps when called:

  1. Let C be ? Get(O, "constructor").
  2. If C is undefined, return defaultConstructor.
  3. If C is not an Object, throw a TypeError exception.
  4. Let S be ? Get(C, %Symbol.species%).
  5. If S is either undefined or null, return defaultConstructor.
  6. If IsConstructor(S) is true, return S.
  7. Throw a TypeError exception.

7.3.23 EnumerableOwnProperties ( O, kind )

The abstract operation EnumerableOwnProperties takes arguments O (an Object) and kind (key, value, or key+value) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. Let ownKeys be ? O.[[OwnPropertyKeys]]().
  2. Let results be a new empty List.
  3. For each element key of ownKeys, do
    1. If key is a String, then
      1. Let desc be ? O.[[GetOwnProperty]](key).
      2. If desc is not undefined and desc.[[Enumerable]] is true, then
        1. If kind is key, then
          1. Append key to results.
        2. Else,
          1. Let value be ? Get(O, key).
          2. If kind is value, then
            1. Append value to results.
          3. Else,
            1. Assert: kind is key+value.
            2. Let entry be CreateArrayFromListkey, value »).
            3. Append entry to results.
  4. Return results.

7.3.24 GetFunctionRealm ( obj )

The abstract operation GetFunctionRealm takes argument obj (a function object) and returns either a normal completion containing a Realm Record or a throw completion. It performs the following steps when called:

  1. If obj has a [[Realm]] internal slot, then
    1. Return obj.[[Realm]].
  2. If obj is a bound function exotic object, then
    1. Let boundTargetFunction be obj.[[BoundTargetFunction]].
    2. Return ? GetFunctionRealm(boundTargetFunction).
  3. If obj is a Proxy exotic object, then
    1. Perform ? ValidateNonRevokedProxy(obj).
    2. Let proxyTarget be obj.[[ProxyTarget]].
    3. Assert: proxyTarget is a function object.
    4. Return ? GetFunctionRealm(proxyTarget).
  4. Return the current Realm Record.
Note

Step 4 will only be reached if obj is a non-standard function exotic object that does not have a [[Realm]] internal slot.

7.3.25 CopyDataProperties ( target, source, excludedItems )

The abstract operation CopyDataProperties takes arguments target (an Object), source (an ECMAScript language value), and excludedItems (a List of property keys) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. If source is either undefined or null, return unused.
  2. Let from be ! ToObject(source).
  3. Let keys be ? from.[[OwnPropertyKeys]]().
  4. For each element nextKey of keys, do
    1. Let excluded be false.
    2. For each element e of excludedItems, do
      1. If SameValue(e, nextKey) is true, then
        1. Set excluded to true.
    3. If excluded is false, then
      1. Let desc be ? from.[[GetOwnProperty]](nextKey).
      2. If desc is not undefined and desc.[[Enumerable]] is true, then
        1. Let propValue be ? Get(from, nextKey).
        2. Perform ! CreateDataPropertyOrThrow(target, nextKey, propValue).
  5. Return unused.
Note

The target passed in here is always a newly created object which is not directly accessible in case of an error being thrown.

7.3.26 PrivateElementFind ( O, P )

The abstract operation PrivateElementFind takes arguments O (an Object) and P (a Private Name) and returns a PrivateElement or empty. It performs the following steps when called:

  1. If O.[[PrivateElements]] contains a PrivateElement pe such that pe.[[Key]] is P, then
    1. Return pe.
  2. Return empty.

7.3.27 PrivateFieldAdd ( O, P, value )

The abstract operation PrivateFieldAdd takes arguments O (an Object), P (a Private Name), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. If the host is a web browser, then
    1. Perform ? HostEnsureCanAddPrivateElement(O).
  2. Let entry be PrivateElementFind(O, P).
  3. If entry is not empty, throw a TypeError exception.
  4. Append PrivateElement { [[Key]]: P, [[Kind]]: field, [[Value]]: value } to O.[[PrivateElements]].
  5. Return unused.

7.3.28 PrivateMethodOrAccessorAdd ( O, method )

The abstract operation PrivateMethodOrAccessorAdd takes arguments O (an Object) and method (a PrivateElement) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Assert: method.[[Kind]] is either method or accessor.
  2. If the host is a web browser, then
    1. Perform ? HostEnsureCanAddPrivateElement(O).
  3. Let entry be PrivateElementFind(O, method.[[Key]]).
  4. If entry is not empty, throw a TypeError exception.
  5. Append method to O.[[PrivateElements]].
  6. Return unused.
Note

The values for private methods and accessors are shared across instances. This operation does not create a new copy of the method or accessor.

7.3.29 HostEnsureCanAddPrivateElement ( O )

The host-defined abstract operation HostEnsureCanAddPrivateElement takes argument O (an Object) and returns either a normal completion containing unused or a throw completion. It allows host environments to prevent the addition of private elements to particular host-defined exotic objects.

An implementation of HostEnsureCanAddPrivateElement must conform to the following requirements:

The default implementation of HostEnsureCanAddPrivateElement is to return NormalCompletion(unused).

This abstract operation is only invoked by ECMAScript hosts that are web browsers.

7.3.30 PrivateGet ( O, P )

The abstract operation PrivateGet takes arguments O (an Object) and P (a Private Name) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Let entry be PrivateElementFind(O, P).
  2. If entry is empty, throw a TypeError exception.
  3. If entry.[[Kind]] is either field or method, then
    1. Return entry.[[Value]].
  4. Assert: entry.[[Kind]] is accessor.
  5. If entry.[[Get]] is undefined, throw a TypeError exception.
  6. Let getter be entry.[[Get]].
  7. Return ? Call(getter, O).

7.3.31 PrivateSet ( O, P, value )

The abstract operation PrivateSet takes arguments O (an Object), P (a Private Name), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Let entry be PrivateElementFind(O, P).
  2. If entry is empty, throw a TypeError exception.
  3. If entry.[[Kind]] is field, then
    1. Set entry.[[Value]] to value.
  4. Else if entry.[[Kind]] is method, then
    1. Throw a TypeError exception.
  5. Else,
    1. Assert: entry.[[Kind]] is accessor.
    2. If entry.[[Set]] is undefined, throw a TypeError exception.
    3. Let setter be entry.[[Set]].
    4. Perform ? Call(setter, O, « value »).
  6. Return unused.

7.3.32 DefineField ( receiver, fieldRecord )

The abstract operation DefineField takes arguments receiver (an Object) and fieldRecord (a ClassFieldDefinition Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Let fieldName be fieldRecord.[[Name]].
  2. Let initializer be fieldRecord.[[Initializer]].
  3. If initializer is not empty, then
    1. Let initValue be ? Call(initializer, receiver).
  4. Else,
    1. Let initValue be undefined.
  5. If fieldName is a Private Name, then
    1. Perform ? PrivateFieldAdd(receiver, fieldName, initValue).
  6. Else,
    1. Assert: fieldName is a property key.
    2. Perform ? CreateDataPropertyOrThrow(receiver, fieldName, initValue).
  7. Return unused.

7.3.33 InitializeInstanceElements ( O, constructor )

The abstract operation InitializeInstanceElements takes arguments O (an Object) and constructor (an ECMAScript function object) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Let methods be constructor.[[PrivateMethods]].
  2. For each PrivateElement method of methods, do
    1. Perform ? PrivateMethodOrAccessorAdd(O, method).
  3. Let fields be constructor.[[Fields]].
  4. For each element fieldRecord of fields, do
    1. Perform ? DefineField(O, fieldRecord).
  5. Return unused.

7.3.34 AddValueToKeyedGroup ( groups, key, value )

The abstract operation AddValueToKeyedGroup takes arguments groups (a List of Records with fields [[Key]] (an ECMAScript language value) and [[Elements]] (a List of ECMAScript language values)), key (an ECMAScript language value), and value (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. For each Record { [[Key]], [[Elements]] } g of groups, do
    1. If SameValue(g.[[Key]], key) is true, then
      1. Assert: Exactly one element of groups meets this criterion.
      2. Append value to g.[[Elements]].
      3. Return unused.
  2. Let group be the Record { [[Key]]: key, [[Elements]]: « value » }.
  3. Append group to groups.
  4. Return unused.

7.3.35 GroupBy ( items, callback, keyCoercion )

The abstract operation GroupBy takes arguments items (an ECMAScript language value), callback (an ECMAScript language value), and keyCoercion (property or collection) and returns either a normal completion containing a List of Records with fields [[Key]] (an ECMAScript language value) and [[Elements]] (a List of ECMAScript language values), or a throw completion. It performs the following steps when called:

  1. Perform ? RequireObjectCoercible(items).
  2. If IsCallable(callback) is false, throw a TypeError exception.
  3. Let groups be a new empty List.
  4. Let iteratorRecord be ? GetIterator(items, sync).
  5. Let k be 0.
  6. Repeat,
    1. If k ≥ 253 - 1, then
      1. Let error be ThrowCompletion(a newly created TypeError object).
      2. Return ? IteratorClose(iteratorRecord, error).
    2. Let next be ? IteratorStepValue(iteratorRecord).
    3. If next is done, then
      1. Return groups.
    4. Let value be next.
    5. Let key be Completion(Call(callback, undefined, « value, 𝔽(k) »)).
    6. IfAbruptCloseIterator(key, iteratorRecord).
    7. If keyCoercion is property, then
      1. Set key to Completion(ToPropertyKey(key)).
      2. IfAbruptCloseIterator(key, iteratorRecord).
    8. Else,
      1. Assert: keyCoercion is collection.
      2. Set key to CanonicalizeKeyedCollectionKey(key).
    9. Perform AddValueToKeyedGroup(groups, key, value).
    10. Set k to k + 1.

7.3.36 SetterThatIgnoresPrototypeProperties ( thisValue, home, p, v )

The abstract operation SetterThatIgnoresPrototypeProperties takes arguments thisValue (an ECMAScript language value), home (an Object), p (a property key), and v (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. If thisValue is not an Object, then
    1. Throw a TypeError exception.
  2. If SameValue(thisValue, home) is true, then
    1. NOTE: Throwing here emulates assignment to a non-writable data property on the home object in strict mode code.
    2. Throw a TypeError exception.
  3. Let desc be ? thisValue.[[GetOwnProperty]](p).
  4. If desc is undefined, then
    1. Perform ? CreateDataPropertyOrThrow(thisValue, p, v).
  5. Else,
    1. Perform ? Set(thisValue, p, v, true).
  6. Return unused.

7.4 Operations on Iterator Objects

See Common Iteration Interfaces (27.1).

7.4.1 Iterator Records

An Iterator Record is a Record value used to encapsulate an iterator or async iterator along with the next method.

Iterator Records have the fields listed in Table 13.

Table 13: Iterator Record Fields
Field Name Value Meaning
[[Iterator]] an Object An object that conforms to the iterator interface or the async iterator interface.
[[NextMethod]] an ECMAScript language value The next method of the [[Iterator]] object.
[[Done]] a Boolean Whether the iterator has completed or been closed.

7.4.2 GetIteratorDirect ( obj )

The abstract operation GetIteratorDirect takes argument obj (an Object) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. Let nextMethod be ? Get(obj, "next").
  2. Let iteratorRecord be the Iterator Record { [[Iterator]]: obj, [[NextMethod]]: nextMethod, [[Done]]: false }.
  3. Return iteratorRecord.

7.4.3 GetIteratorFromMethod ( obj, method )

The abstract operation GetIteratorFromMethod takes arguments obj (an ECMAScript language value) and method (a function object) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. Let iterator be ? Call(method, obj).
  2. If iterator is not an Object, throw a TypeError exception.
  3. Return ? GetIteratorDirect(iterator).

7.4.4 GetIterator ( obj, kind )

The abstract operation GetIterator takes arguments obj (an ECMAScript language value) and kind (sync or async) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. If kind is async, then
    1. Let method be ? GetMethod(obj, %Symbol.asyncIterator%).
    2. If method is undefined, then
      1. Let syncMethod be ? GetMethod(obj, %Symbol.iterator%).
      2. If syncMethod is undefined, throw a TypeError exception.
      3. Let syncIteratorRecord be ? GetIteratorFromMethod(obj, syncMethod).
      4. Return CreateAsyncFromSyncIterator(syncIteratorRecord).
  2. Else,
    1. Let method be ? GetMethod(obj, %Symbol.iterator%).
  3. If method is undefined, throw a TypeError exception.
  4. Return ? GetIteratorFromMethod(obj, method).

7.4.5 GetIteratorFlattenable ( obj, primitiveHandling )

The abstract operation GetIteratorFlattenable takes arguments obj (an ECMAScript language value) and primitiveHandling (iterate-string-primitives or reject-primitives) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. If obj is not an Object, then
    1. If primitiveHandling is reject-primitives, throw a TypeError exception.
    2. Assert: primitiveHandling is iterate-string-primitives.
    3. If obj is not a String, throw a TypeError exception.
  2. Let method be ? GetMethod(obj, %Symbol.iterator%).
  3. If method is undefined, then
    1. Let iterator be obj.
  4. Else,
    1. Let iterator be ? Call(method, obj).
  5. If iterator is not an Object, throw a TypeError exception.
  6. Return ? GetIteratorDirect(iterator).

7.4.6 IteratorNext ( iteratorRecord [ , value ] )

The abstract operation IteratorNext takes argument iteratorRecord (an Iterator Record) and optional argument value (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. If value is not present, then
    1. Let result be Completion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])).
  2. Else,
    1. Let result be Completion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »)).
  3. If result is a throw completion, then
    1. Set iteratorRecord.[[Done]] to true.
    2. Return ? result.
  4. Set result to ! result.
  5. If result is not an Object, then
    1. Set iteratorRecord.[[Done]] to true.
    2. Throw a TypeError exception.
  6. Return result.

7.4.7 IteratorComplete ( iteratorResult )

The abstract operation IteratorComplete takes argument iteratorResult (an Object) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. Return ToBoolean(? Get(iteratorResult, "done")).

7.4.8 IteratorValue ( iteratorResult )

The abstract operation IteratorValue takes argument iteratorResult (an Object) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Return ? Get(iteratorResult, "value").

7.4.9 IteratorStep ( iteratorRecord )

The abstract operation IteratorStep takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an Object or done, or a throw completion. It requests the next value from iteratorRecord.[[Iterator]] by calling iteratorRecord.[[NextMethod]] and returns either done 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:

  1. Let result be ? IteratorNext(iteratorRecord).
  2. Let done be Completion(IteratorComplete(result)).
  3. If done is a throw completion, then
    1. Set iteratorRecord.[[Done]] to true.
    2. Return ? done.
  4. Set done to ! done.
  5. If done is true, then
    1. Set iteratorRecord.[[Done]] to true.
    2. Return done.
  6. Return result.

7.4.10 IteratorStepValue ( iteratorRecord )

The abstract operation IteratorStepValue takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an ECMAScript language value or done, or a throw completion. It requests the next value from iteratorRecord.[[Iterator]] by calling iteratorRecord.[[NextMethod]] and returns either done indicating that the iterator has reached its end or the value from the IteratorResult object if a next value is available. It performs the following steps when called:

  1. Let result be ? IteratorStep(iteratorRecord).
  2. If result is done, then
    1. Return done.
  3. Let value be Completion(IteratorValue(result)).
  4. If value is a throw completion, then
    1. Set iteratorRecord.[[Done]] to true.
  5. Return ? value.

7.4.11 IteratorClose ( iteratorRecord, completion )

The abstract operation IteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. 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:

  1. Assert: iteratorRecord.[[Iterator]] is an Object.
  2. Let iterator be iteratorRecord.[[Iterator]].
  3. Let innerResult be Completion(GetMethod(iterator, "return")).
  4. If innerResult is a normal completion, then
    1. Let return be innerResult.[[Value]].
    2. If return is undefined, return ? completion.
    3. Set innerResult to Completion(Call(return, iterator)).
  5. If completion is a throw completion, return ? completion.
  6. If innerResult is a throw completion, return ? innerResult.
  7. If innerResult.[[Value]] is not an Object, throw a TypeError exception.
  8. Return ? completion.

7.4.12 IfAbruptCloseIterator ( value, iteratorRecord )

IfAbruptCloseIterator is a shorthand for a sequence of algorithm steps that use an Iterator Record. An algorithm step of the form:

  1. IfAbruptCloseIterator(value, iteratorRecord).

means the same thing as:

  1. Assert: value is a Completion Record.
  2. If value is an abrupt completion, return ? IteratorClose(iteratorRecord, value).
  3. Else, set value to ! value.

7.4.13 AsyncIteratorClose ( iteratorRecord, completion )

The abstract operation AsyncIteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. 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:

  1. Assert: iteratorRecord.[[Iterator]] is an Object.
  2. Let iterator be iteratorRecord.[[Iterator]].
  3. Let innerResult be Completion(GetMethod(iterator, "return")).
  4. If innerResult is a normal completion, then
    1. Let return be innerResult.[[Value]].
    2. If return is undefined, return ? completion.
    3. Set innerResult to Completion(Call(return, iterator)).
    4. If innerResult is a normal completion, set innerResult to Completion(Await(innerResult.[[Value]])).
  5. If completion is a throw completion, return ? completion.
  6. If innerResult is a throw completion, return ? innerResult.
  7. If innerResult.[[Value]] is not an Object, throw a TypeError exception.
  8. Return ? completion.

7.4.14 CreateIteratorResultObject ( value, done )

The abstract operation CreateIteratorResultObject takes arguments value (an ECMAScript language value) and done (a Boolean) and returns an Object that conforms to the IteratorResult interface. It creates an object that conforms to the IteratorResult interface. It performs the following steps when called:

  1. Let obj be OrdinaryObjectCreate(%Object.prototype%).
  2. Perform ! CreateDataPropertyOrThrow(obj, "value", value).
  3. Perform ! CreateDataPropertyOrThrow(obj, "done", done).
  4. Return obj.

7.4.15 CreateListIteratorRecord ( list )

The abstract operation CreateListIteratorRecord takes argument list (a List of ECMAScript language values) and returns an Iterator Record. It creates an Iterator Record whose [[NextMethod]] returns the successive elements of list. It performs the following steps when called:

  1. Let closure be a new Abstract Closure with no parameters that captures list and performs the following steps when called:
    1. For each element E of list, do
      1. Perform ? GeneratorYield(CreateIteratorResultObject(E, false)).
    2. Return NormalCompletion(undefined).
  2. Let iterator be CreateIteratorFromClosure(closure, empty, %Iterator.prototype%).
  3. Return the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: %GeneratorPrototype.next%, [[Done]]: false }.
Note

The list iterator object is never directly accessible to ECMAScript code.

7.4.16 IteratorToList ( iteratorRecord )

The abstract operation IteratorToList takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. Let values be a new empty List.
  2. Repeat,
    1. Let next be ? IteratorStepValue(iteratorRecord).
    2. If next is done, then
      1. Return values.
    3. Append next to values.

8 Syntax-Directed Operations

In addition to those defined in this section, specialized syntax-directed operations are defined throughout this specification.

8.1 Runtime Semantics: Evaluation

The syntax-directed operation Evaluation takes no arguments and returns a Completion Record.

Note
The definitions for this operation are distributed over the "ECMAScript Language" sections of this specification. Each definition appears after the defining occurrence of the relevant productions.

8.2 Scope Analysis

8.2.1 Static Semantics: BoundNames

The syntax-directed operation BoundNames takes no arguments and returns a List of Strings.

Note

"*default*" is used within this specification as a synthetic name for a module's default export when it does not have another name. An entry in the module's [[Environment]] is created with that name and holds the corresponding value, and resolving the export named "default" by calling ResolveExport ( exportName [ , resolveSet ] ) for the module will return a ResolvedBinding Record whose [[BindingName]] is "*default*", which will then resolve in the module's [[Environment]] to the above-mentioned value. This is done only for ease of specification, so that anonymous default exports can be resolved like any other export. This "*default*" string is never accessible to ECMAScript code or to the module linking algorithm.

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. Return a List whose sole element is the StringValue of Identifier.
BindingIdentifier : yield
  1. Return « "yield" ».
BindingIdentifier : await
  1. Return « "await" ».
LexicalDeclaration : LetOrConst BindingList ;
  1. Return the BoundNames of BindingList.
BindingList : BindingList , LexicalBinding
  1. Let names1 be the BoundNames of BindingList.
  2. Let names2 be the BoundNames of LexicalBinding.
  3. Return the list-concatenation of names1 and names2.
LexicalBinding : BindingIdentifier Initializeropt
  1. Return the BoundNames of BindingIdentifier.
LexicalBinding : BindingPattern Initializer
  1. Return the BoundNames of BindingPattern.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. Let names1 be the BoundNames of VariableDeclarationList.
  2. Let names2 be the BoundNames of VariableDeclaration.
  3. Return the list-concatenation of names1 and names2.
VariableDeclaration : BindingIdentifier Initializeropt
  1. Return the BoundNames of BindingIdentifier.
VariableDeclaration : BindingPattern Initializer
  1. Return the BoundNames of BindingPattern.
ObjectBindingPattern : { }
  1. Return a new empty List.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. Let names1 be the BoundNames of BindingPropertyList.
  2. Let names2 be the BoundNames of BindingRestProperty.
  3. Return the list-concatenation of names1 and names2.
ArrayBindingPattern : [ Elisionopt ]
  1. Return a new empty List.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. Return the BoundNames of BindingRestElement.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. Return the BoundNames of BindingElementList.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. Let names1 be the BoundNames of BindingElementList.
  2. Let names2 be the BoundNames of BindingRestElement.
  3. Return the list-concatenation of names1 and names2.
BindingPropertyList : BindingPropertyList , BindingProperty
  1. Let names1 be the BoundNames of BindingPropertyList.
  2. Let names2 be the BoundNames of BindingProperty.
  3. Return the list-concatenation of names1 and names2.
BindingElementList : BindingElementList , BindingElisionElement
  1. Let names1 be the BoundNames of BindingElementList.
  2. Let names2 be the BoundNames of BindingElisionElement.
  3. Return the list-concatenation of names1 and names2.
BindingElisionElement : Elisionopt BindingElement
  1. Return the BoundNames of BindingElement.
BindingProperty : PropertyName : BindingElement
  1. Return the BoundNames of BindingElement.
SingleNameBinding : BindingIdentifier Initializeropt
  1. Return the BoundNames of BindingIdentifier.
BindingElement : BindingPattern Initializeropt
  1. Return the BoundNames of BindingPattern.
ForDeclaration : LetOrConst ForBinding
  1. Return the BoundNames of ForBinding.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. Return the BoundNames of BindingIdentifier.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. Return « "*default*" ».
FormalParameters : [empty]
  1. Return a new empty List.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. Let names1 be the BoundNames of FormalParameterList.
  2. Let names2 be the BoundNames of FunctionRestParameter.
  3. Return the list-concatenation of names1 and names2.
FormalParameterList : FormalParameterList , FormalParameter
  1. Let names1 be the BoundNames of FormalParameterList.
  2. Let names2 be the BoundNames of FormalParameter.
  3. Return the list-concatenation of names1 and names2.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. Let formals be the ArrowFormalParameters that is covered by CoverParenthesizedExpressionAndArrowParameterList.
  2. Return the BoundNames of formals.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. Return the BoundNames of BindingIdentifier.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. Return « "*default*" ».
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. Return the BoundNames of BindingIdentifier.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. Return « "*default*" ».
ClassDeclaration : class BindingIdentifier ClassTail
  1. Return the BoundNames of BindingIdentifier.
ClassDeclaration : class ClassTail
  1. Return « "*default*" ».
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. Return the BoundNames of BindingIdentifier.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. Return « "*default*" ».
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. Let head be the AsyncArrowHead that is covered by CoverCallExpressionAndAsyncArrowHead.
  2. Return the BoundNames of head.
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. Return the BoundNames of ImportClause.
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. Return a new empty List.
ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. Let names1 be the BoundNames of ImportedDefaultBinding.
  2. Let names2 be the BoundNames of NameSpaceImport.
  3. Return the list-concatenation of names1 and names2.
ImportClause : ImportedDefaultBinding , NamedImports
  1. Let names1 be the BoundNames of ImportedDefaultBinding.
  2. Let names2 be the BoundNames of NamedImports.
  3. Return the list-concatenation of names1 and names2.
NamedImports : { }
  1. Return a new empty List.
ImportsList : ImportsList , ImportSpecifier
  1. Let names1 be the BoundNames of ImportsList.
  2. Let names2 be the BoundNames of ImportSpecifier.
  3. Return the list-concatenation of names1 and names2.
ImportSpecifier : ModuleExportName as ImportedBinding
  1. Return the BoundNames of ImportedBinding.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. Return a new empty List.
ExportDeclaration : export VariableStatement
  1. Return the BoundNames of VariableStatement.
ExportDeclaration : export Declaration
  1. Return the BoundNames of Declaration.
ExportDeclaration : export default HoistableDeclaration
  1. Let declarationNames be the BoundNames of HoistableDeclaration.
  2. If declarationNames does not include the element "*default*", append "*default*" to declarationNames.
  3. Return declarationNames.
ExportDeclaration : export default ClassDeclaration
  1. Let declarationNames be the BoundNames of ClassDeclaration.
  2. If declarationNames does not include the element "*default*", append "*default*" to declarationNames.
  3. Return declarationNames.
ExportDeclaration : export default AssignmentExpression ;
  1. Return « "*default*" ».

8.2.2 Static Semantics: DeclarationPart

The syntax-directed operation DeclarationPart takes no arguments and returns a Parse Node. It is defined piecewise over the following productions:

HoistableDeclaration : FunctionDeclaration
  1. Return FunctionDeclaration.
HoistableDeclaration : GeneratorDeclaration
  1. Return GeneratorDeclaration.
HoistableDeclaration : AsyncFunctionDeclaration
  1. Return AsyncFunctionDeclaration.
HoistableDeclaration : AsyncGeneratorDeclaration
  1. Return AsyncGeneratorDeclaration.
Declaration : ClassDeclaration
  1. Return ClassDeclaration.
Declaration : LexicalDeclaration
  1. Return LexicalDeclaration.

8.2.3 Static Semantics: IsConstantDeclaration

The syntax-directed operation IsConstantDeclaration takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. Return IsConstantDeclaration of LetOrConst.
LetOrConst : let
  1. Return false.
LetOrConst : const
  1. 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 }
  1. Return false.
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
  1. Return false.
ExportDeclaration : export ExportFromClause FromClause ; export NamedExports ; export default AssignmentExpression ;
  1. 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.

8.2.4 Static Semantics: LexicallyDeclaredNames

The syntax-directed operation LexicallyDeclaredNames takes no arguments and returns a List of Strings. It is defined piecewise over the following productions:

Block : { }
  1. Return a new empty List.
StatementList : StatementList StatementListItem
  1. Let names1 be the LexicallyDeclaredNames of StatementList.
  2. Let names2 be the LexicallyDeclaredNames of StatementListItem.
  3. Return the list-concatenation of names1 and names2.
StatementListItem : Statement
  1. If Statement is Statement : LabelledStatement , return the LexicallyDeclaredNames of LabelledStatement.
  2. Return a new empty List.
StatementListItem : Declaration
  1. Return the BoundNames of Declaration.
CaseBlock : { }
  1. Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. If the first CaseClauses is present, let names1 be the LexicallyDeclaredNames of the first CaseClauses.
  2. Else, let names1 be a new empty List.
  3. Let names2 be the LexicallyDeclaredNames of DefaultClause.
  4. If the second CaseClauses is present, let names3 be the LexicallyDeclaredNames of the second CaseClauses.
  5. Else, let names3 be a new empty List.
  6. Return the list-concatenation of names1, names2, and names3.
CaseClauses : CaseClauses CaseClause
  1. Let names1 be the LexicallyDeclaredNames of CaseClauses.
  2. Let names2 be the LexicallyDeclaredNames of CaseClause.
  3. Return the list-concatenation of names1 and names2.
CaseClause : case Expression : StatementListopt
  1. If the StatementList is present, return the LexicallyDeclaredNames of StatementList.
  2. Return a new empty List.
DefaultClause : default : StatementListopt
  1. If the StatementList is present, return the LexicallyDeclaredNames of StatementList.
  2. Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Return the LexicallyDeclaredNames of LabelledItem.
LabelledItem : Statement
  1. Return a new empty List.
LabelledItem : FunctionDeclaration
  1. Return the BoundNames of FunctionDeclaration.
FunctionStatementList : [empty]
  1. Return a new empty List.
FunctionStatementList : StatementList
  1. Return the TopLevelLexicallyDeclaredNames of StatementList.
ClassStaticBlockStatementList : [empty]
  1. Return a new empty List.
ClassStaticBlockStatementList : StatementList
  1. Return the TopLevelLexicallyDeclaredNames of StatementList.
ConciseBody : ExpressionBody
  1. Return a new empty List.
AsyncConciseBody : ExpressionBody
  1. Return a new empty List.
Script : [empty]
  1. Return a new empty List.
ScriptBody : StatementList
  1. Return the 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
  1. Let names1 be the LexicallyDeclaredNames of ModuleItemList.
  2. Let names2 be the LexicallyDeclaredNames of ModuleItem.
  3. Return the list-concatenation of names1 and names2.
ModuleItem : ImportDeclaration
  1. Return the BoundNames of ImportDeclaration.
ModuleItem : ExportDeclaration
  1. If ExportDeclaration is export VariableStatement, return a new empty List.
  2. Return the BoundNames of ExportDeclaration.
ModuleItem : StatementListItem
  1. Return the LexicallyDeclaredNames of StatementListItem.
Note 3

At the top level of a Module, function declarations are treated like lexical declarations rather than like var declarations.

8.2.5 Static Semantics: LexicallyScopedDeclarations

The syntax-directed operation LexicallyScopedDeclarations takes no arguments and returns a List of Parse Nodes. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. Let declarations1 be the LexicallyScopedDeclarations of StatementList.
  2. Let declarations2 be the LexicallyScopedDeclarations of StatementListItem.
  3. Return the list-concatenation of declarations1 and declarations2.
StatementListItem : Statement
  1. If Statement is Statement : LabelledStatement , return the LexicallyScopedDeclarations of LabelledStatement.
  2. Return a new empty List.
StatementListItem : Declaration
  1. Return a List whose sole element is the DeclarationPart of Declaration.
CaseBlock : { }
  1. Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. If the first CaseClauses is present, let declarations1 be the LexicallyScopedDeclarations of the first CaseClauses.
  2. Else, let declarations1 be a new empty List.
  3. Let declarations2 be the LexicallyScopedDeclarations of DefaultClause.
  4. If the second CaseClauses is present, let declarations3 be the LexicallyScopedDeclarations of the second CaseClauses.
  5. Else, let declarations3 be a new empty List.
  6. Return the list-concatenation of declarations1, declarations2, and declarations3.
CaseClauses : CaseClauses CaseClause
  1. Let declarations1 be the LexicallyScopedDeclarations of CaseClauses.
  2. Let declarations2 be the LexicallyScopedDeclarations of CaseClause.
  3. Return the list-concatenation of declarations1 and declarations2.
CaseClause : case Expression : StatementListopt
  1. If the StatementList is present, return the LexicallyScopedDeclarations of StatementList.
  2. Return a new empty List.
DefaultClause : default : StatementListopt
  1. If the StatementList is present, return the LexicallyScopedDeclarations of StatementList.
  2. Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Return the LexicallyScopedDeclarations of LabelledItem.
LabelledItem : Statement
  1. Return a new empty List.
LabelledItem : FunctionDeclaration
  1. Return « FunctionDeclaration ».
FunctionStatementList : [empty]
  1. Return a new empty List.
FunctionStatementList : StatementList
  1. Return the TopLevelLexicallyScopedDeclarations of StatementList.
ClassStaticBlockStatementList : [empty]
  1. Return a new empty List.
ClassStaticBlockStatementList : StatementList
  1. Return the TopLevelLexicallyScopedDeclarations of StatementList.
ConciseBody : ExpressionBody
  1. Return a new empty List.
AsyncConciseBody : ExpressionBody
  1. Return a new empty List.
Script : [empty]
  1. Return a new empty List.
ScriptBody : StatementList
  1. Return the TopLevelLexicallyScopedDeclarations of StatementList.
Module : [empty]
  1. Return a new empty List.
ModuleItemList : ModuleItemList ModuleItem
  1. Let declarations1 be the LexicallyScopedDeclarations of ModuleItemList.
  2. Let declarations2 be the LexicallyScopedDeclarations of ModuleItem.
  3. Return the list-concatenation of declarations1 and declarations2.
ModuleItem : ImportDeclaration
  1. Return a new empty List.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement
  1. Return a new empty List.
ExportDeclaration : export Declaration
  1. Return a List whose sole element is the DeclarationPart of Declaration.
ExportDeclaration : export default HoistableDeclaration
  1. Return a List whose sole element is the DeclarationPart of HoistableDeclaration.
ExportDeclaration : export default ClassDeclaration
  1. Return a List whose sole element is ClassDeclaration.
ExportDeclaration : export default AssignmentExpression ;
  1. Return a List whose sole element is this ExportDeclaration.

8.2.6 Static Semantics: VarDeclaredNames

The syntax-directed operation VarDeclaredNames takes no arguments and returns a List of Strings. It is defined piecewise over the following productions:

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. Return a new empty List.
Block : { }
  1. Return a new empty List.
StatementList : StatementList StatementListItem
  1. Let names1 be the VarDeclaredNames of StatementList.
  2. Let names2 be the VarDeclaredNames of StatementListItem.
  3. Return the list-concatenation of names1 and names2.
StatementListItem : Declaration
  1. Return a new empty List.
VariableStatement : var VariableDeclarationList ;
  1. Return the BoundNames of VariableDeclarationList.
IfStatement : if ( Expression ) Statement else Statement
  1. Let names1 be the VarDeclaredNames of the first Statement.
  2. Let names2 be the VarDeclaredNames of the second Statement.
  3. Return the list-concatenation of names1 and names2.
IfStatement : if ( Expression ) Statement
  1. Return the VarDeclaredNames of Statement.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Return the VarDeclaredNames of Statement.
WhileStatement : while ( Expression ) Statement
  1. Return the VarDeclaredNames of Statement.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. Return the VarDeclaredNames of Statement.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. Let names1 be the BoundNames of VariableDeclarationList.
  2. Let names2 be the VarDeclaredNames of Statement.
  3. Return the list-concatenation of names1 and names2.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 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
  1. 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
  1. Let names1 be the BoundNames of ForBinding.
  2. Let names2 be the VarDeclaredNames of Statement.
  3. Return the list-concatenation of names1 and names2.
Note

This section is extended by Annex B.3.5.

WithStatement : with ( Expression ) Statement
  1. Return the VarDeclaredNames of Statement.
SwitchStatement : switch ( Expression ) CaseBlock
  1. Return the VarDeclaredNames of CaseBlock.
CaseBlock : { }
  1. Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. If the first CaseClauses is present, let names1 be the VarDeclaredNames of the first CaseClauses.
  2. Else, let names1 be a new empty List.
  3. Let names2 be the VarDeclaredNames of DefaultClause.
  4. If the second CaseClauses is present, let names3 be the VarDeclaredNames of the second CaseClauses.
  5. Else, let names3 be a new empty List.
  6. Return the list-concatenation of names1, names2, and names3.
CaseClauses : CaseClauses CaseClause
  1. Let names1 be the VarDeclaredNames of CaseClauses.
  2. Let names2 be the VarDeclaredNames of CaseClause.
  3. Return the list-concatenation of names1 and names2.
CaseClause : case Expression : StatementListopt
  1. If the StatementList is present, return the VarDeclaredNames of StatementList.
  2. Return a new empty List.
DefaultClause : default : StatementListopt
  1. If the StatementList is present, return the VarDeclaredNames of StatementList.
  2. Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Return the VarDeclaredNames of LabelledItem.
LabelledItem : FunctionDeclaration
  1. Return a new empty List.
TryStatement : try Block Catch
  1. Let names1 be the VarDeclaredNames of Block.
  2. Let names2 be the VarDeclaredNames of Catch.
  3. Return the list-concatenation of names1 and names2.
TryStatement : try Block Finally
  1. Let names1 be the VarDeclaredNames of Block.
  2. Let names2 be the VarDeclaredNames of Finally.
  3. Return the list-concatenation of names1 and names2.
TryStatement : try Block Catch Finally
  1. Let names1 be the VarDeclaredNames of Block.
  2. Let names2 be the VarDeclaredNames of Catch.
  3. Let names3 be the VarDeclaredNames of Finally.
  4. Return the list-concatenation of names1, names2, and names3.
Catch : catch ( CatchParameter ) Block
  1. Return the VarDeclaredNames of Block.
FunctionStatementList : [empty]
  1. Return a new empty List.
FunctionStatementList : StatementList
  1. Return the TopLevelVarDeclaredNames of StatementList.
ClassStaticBlockStatementList : [empty]
  1. Return a new empty List.
ClassStaticBlockStatementList : StatementList
  1. Return the TopLevelVarDeclaredNames of StatementList.
ConciseBody : ExpressionBody
  1. Return a new empty List.
AsyncConciseBody : ExpressionBody
  1. Return a new empty List.
Script : [empty]
  1. Return a new empty List.
ScriptBody : StatementList
  1. Return the TopLevelVarDeclaredNames of StatementList.
ModuleItemList : ModuleItemList ModuleItem
  1. Let names1 be the VarDeclaredNames of ModuleItemList.
  2. Let names2 be the VarDeclaredNames of ModuleItem.
  3. Return the list-concatenation of names1 and names2.
ModuleItem : ImportDeclaration
  1. Return a new empty List.
ModuleItem : ExportDeclaration
  1. If ExportDeclaration is export VariableStatement, return the BoundNames of ExportDeclaration.
  2. Return a new empty List.

8.2.7 Static Semantics: VarScopedDeclarations

The syntax-directed operation VarScopedDeclarations takes no arguments and returns a List of Parse Nodes. It is defined piecewise over the following productions:

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. Return a new empty List.
Block : { }
  1. Return a new empty List.
StatementList : StatementList StatementListItem
  1. Let declarations1 be the VarScopedDeclarations of StatementList.
  2. Let declarations2 be the VarScopedDeclarations of StatementListItem.
  3. Return the list-concatenation of declarations1 and declarations2.
StatementListItem : Declaration
  1. Return a new empty List.
VariableDeclarationList : VariableDeclaration
  1. Return « VariableDeclaration ».
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. Let declarations1 be the VarScopedDeclarations of VariableDeclarationList.
  2. Return the list-concatenation of declarations1 and « VariableDeclaration ».
IfStatement : if ( Expression ) Statement else Statement
  1. Let declarations1 be the VarScopedDeclarations of the first Statement.
  2. Let declarations2 be the VarScopedDeclarations of the second Statement.
  3. Return the list-concatenation of declarations1 and declarations2.
IfStatement : if ( Expression ) Statement
  1. Return the VarScopedDeclarations of Statement.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Return the VarScopedDeclarations of Statement.
WhileStatement : while ( Expression ) Statement
  1. Return the VarScopedDeclarations of Statement.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. Return the VarScopedDeclarations of Statement.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. Let declarations1 be the VarScopedDeclarations of VariableDeclarationList.
  2. Let declarations2 be the VarScopedDeclarations of Statement.
  3. Return the list-concatenation of declarations1 and declarations2.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 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
  1. 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
  1. Let declarations1 be « ForBinding ».
  2. Let declarations2 be the VarScopedDeclarations of Statement.
  3. Return the list-concatenation of declarations1 and declarations2.
Note

This section is extended by Annex B.3.5.

WithStatement : with ( Expression ) Statement
  1. Return the VarScopedDeclarations of Statement.
SwitchStatement : switch ( Expression ) CaseBlock
  1. Return the VarScopedDeclarations of CaseBlock.
CaseBlock : { }
  1. Return a new empty List.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. If the first CaseClauses is present, let declarations1 be the VarScopedDeclarations of the first CaseClauses.
  2. Else, let declarations1 be a new empty List.
  3. Let declarations2 be the VarScopedDeclarations of DefaultClause.
  4. If the second CaseClauses is present, let declarations3 be the VarScopedDeclarations of the second CaseClauses.
  5. Else, let declarations3 be a new empty List.
  6. Return the list-concatenation of declarations1, declarations2, and declarations3.
CaseClauses : CaseClauses CaseClause
  1. Let declarations1 be the VarScopedDeclarations of CaseClauses.
  2. Let declarations2 be the VarScopedDeclarations of CaseClause.
  3. Return the list-concatenation of declarations1 and declarations2.
CaseClause : case Expression : StatementListopt
  1. If the StatementList is present, return the VarScopedDeclarations of StatementList.
  2. Return a new empty List.
DefaultClause : default : StatementListopt
  1. If the StatementList is present, return the VarScopedDeclarations of StatementList.
  2. Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Return the VarScopedDeclarations of LabelledItem.
LabelledItem : FunctionDeclaration
  1. Return a new empty List.
TryStatement : try Block Catch
  1. Let declarations1 be the VarScopedDeclarations of Block.
  2. Let declarations2 be the VarScopedDeclarations of Catch.
  3. Return the list-concatenation of declarations1 and declarations2.
TryStatement : try Block Finally
  1. Let declarations1 be the VarScopedDeclarations of Block.
  2. Let declarations2 be the VarScopedDeclarations of Finally.
  3. Return the list-concatenation of declarations1 and declarations2.
TryStatement : try Block Catch Finally
  1. Let declarations1 be the VarScopedDeclarations of Block.
  2. Let declarations2 be the VarScopedDeclarations of Catch.
  3. Let declarations3 be the VarScopedDeclarations of Finally.
  4. Return the list-concatenation of declarations1, declarations2, and declarations3.
Catch : catch ( CatchParameter ) Block
  1. Return the VarScopedDeclarations of Block.
FunctionStatementList : [empty]
  1. Return a new empty List.
FunctionStatementList : StatementList
  1. Return the TopLevelVarScopedDeclarations of StatementList.
ClassStaticBlockStatementList : [empty]
  1. Return a new empty List.
ClassStaticBlockStatementList : StatementList
  1. Return the TopLevelVarScopedDeclarations of StatementList.
ConciseBody : ExpressionBody
  1. Return a new empty List.
AsyncConciseBody : ExpressionBody
  1. Return a new empty List.
Script : [empty]
  1. Return a new empty List.
ScriptBody : StatementList
  1. Return the TopLevelVarScopedDeclarations of StatementList.
Module : [empty]
  1. Return a new empty List.
ModuleItemList : ModuleItemList ModuleItem
  1. Let declarations1 be the VarScopedDeclarations of ModuleItemList.
  2. Let declarations2 be the VarScopedDeclarations of ModuleItem.
  3. Return the list-concatenation of declarations1 and declarations2.
ModuleItem : ImportDeclaration
  1. Return a new empty List.
ModuleItem : ExportDeclaration
  1. If ExportDeclaration is export VariableStatement, return the VarScopedDeclarations of VariableStatement.
  2. Return a new empty List.

8.2.8 Static Semantics: TopLevelLexicallyDeclaredNames

The syntax-directed operation TopLevelLexicallyDeclaredNames takes no arguments and returns a List of Strings. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. Let names1 be the TopLevelLexicallyDeclaredNames of StatementList.
  2. Let names2 be the TopLevelLexicallyDeclaredNames of StatementListItem.
  3. Return the list-concatenation of names1 and names2.
StatementListItem : Statement
  1. Return a new empty List.
StatementListItem : Declaration
  1. If Declaration is Declaration : HoistableDeclaration , then
    1. Return a new empty List.
  2. 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.

8.2.9 Static Semantics: TopLevelLexicallyScopedDeclarations

The syntax-directed operation TopLevelLexicallyScopedDeclarations takes no arguments and returns a List of Parse Nodes. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. Let declarations1 be the TopLevelLexicallyScopedDeclarations of StatementList.
  2. Let declarations2 be the TopLevelLexicallyScopedDeclarations of StatementListItem.
  3. Return the list-concatenation of declarations1 and declarations2.
StatementListItem : Statement
  1. Return a new empty List.
StatementListItem : Declaration
  1. If Declaration is Declaration : HoistableDeclaration , then
    1. Return a new empty List.
  2. Return « Declaration ».

8.2.10 Static Semantics: TopLevelVarDeclaredNames

The syntax-directed operation TopLevelVarDeclaredNames takes no arguments and returns a List of Strings. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. Let names1 be the TopLevelVarDeclaredNames of StatementList.
  2. Let names2 be the TopLevelVarDeclaredNames of StatementListItem.
  3. Return the list-concatenation of names1 and names2.
StatementListItem : Declaration
  1. If Declaration is Declaration : HoistableDeclaration , then
    1. Return the BoundNames of HoistableDeclaration.
  2. Return a new empty List.
StatementListItem : Statement
  1. If Statement is Statement : LabelledStatement , return the TopLevelVarDeclaredNames of Statement.
  2. Return the VarDeclaredNames of Statement.
Note

At the top level of a function or script, inner function declarations are treated like var declarations.

LabelledStatement : LabelIdentifier : LabelledItem
  1. Return the TopLevelVarDeclaredNames of LabelledItem.
LabelledItem : Statement
  1. If Statement is Statement : LabelledStatement , return the TopLevelVarDeclaredNames of Statement.
  2. Return the VarDeclaredNames of Statement.
LabelledItem : FunctionDeclaration
  1. Return the BoundNames of FunctionDeclaration.

8.2.11 Static Semantics: TopLevelVarScopedDeclarations

The syntax-directed operation TopLevelVarScopedDeclarations takes no arguments and returns a List of Parse Nodes. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. Let declarations1 be the TopLevelVarScopedDeclarations of StatementList.
  2. Let declarations2 be the TopLevelVarScopedDeclarations of StatementListItem.
  3. Return the list-concatenation of declarations1 and declarations2.
StatementListItem : Statement
  1. If Statement is Statement : LabelledStatement , return the TopLevelVarScopedDeclarations of Statement.
  2. Return the VarScopedDeclarations of Statement.
StatementListItem : Declaration
  1. If Declaration is Declaration : HoistableDeclaration , then
    1. Let declaration be the DeclarationPart of HoistableDeclaration.
    2. Return « declaration ».
  2. Return a new empty List.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Return the TopLevelVarScopedDeclarations of LabelledItem.
LabelledItem : Statement
  1. If Statement is Statement : LabelledStatement , return the TopLevelVarScopedDeclarations of Statement.
  2. Return the VarScopedDeclarations of Statement.
LabelledItem : FunctionDeclaration
  1. Return « FunctionDeclaration ».

8.3 Labels

8.3.1 Static Semantics: ContainsDuplicateLabels

The syntax-directed operation ContainsDuplicateLabels takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. Return false.
StatementList : StatementList StatementListItem
  1. Let hasDuplicates be ContainsDuplicateLabels of StatementList with argument labelSet.
  2. If hasDuplicates is true, return true.
  3. Return ContainsDuplicateLabels of StatementListItem with argument labelSet.
IfStatement : if ( Expression ) Statement else Statement
  1. Let hasDuplicate be ContainsDuplicateLabels of the first Statement with argument labelSet.
  2. If hasDuplicate is true, return true.
  3. Return ContainsDuplicateLabels of the second Statement with argument labelSet.
IfStatement : if ( Expression ) Statement
  1. Return ContainsDuplicateLabels of Statement with argument labelSet.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Return ContainsDuplicateLabels of Statement with argument labelSet.
WhileStatement : while ( Expression ) Statement
  1. Return ContainsDuplicateLabels of Statement with argument labelSet.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 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
  1. Return ContainsDuplicateLabels of Statement with argument labelSet.
Note

This section is extended by Annex B.3.5.

WithStatement : with ( Expression ) Statement
  1. Return ContainsDuplicateLabels of Statement with argument labelSet.
SwitchStatement : switch ( Expression ) CaseBlock
  1. Return ContainsDuplicateLabels of CaseBlock with argument labelSet.
CaseBlock : { }
  1. Return false.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. If the first CaseClauses is present, then
    1. If ContainsDuplicateLabels of the first CaseClauses with argument labelSet is true, return true.
  2. If ContainsDuplicateLabels of DefaultClause with argument labelSet is true, return true.
  3. If the second CaseClauses is not present, return false.
  4. Return ContainsDuplicateLabels of the second CaseClauses with argument labelSet.
CaseClauses : CaseClauses CaseClause
  1. Let hasDuplicates be ContainsDuplicateLabels of CaseClauses with argument labelSet.
  2. If hasDuplicates is true, return true.
  3. Return ContainsDuplicateLabels of CaseClause with argument labelSet.
CaseClause : case Expression : StatementListopt
  1. If the StatementList is present, return ContainsDuplicateLabels of StatementList with argument labelSet.
  2. Return false.
DefaultClause : default : StatementListopt
  1. If the StatementList is present, return ContainsDuplicateLabels of StatementList with argument labelSet.
  2. Return false.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Let label be the StringValue of LabelIdentifier.
  2. If labelSet contains label, return true.
  3. Let newLabelSet be the list-concatenation of labelSet and « label ».
  4. Return ContainsDuplicateLabels of LabelledItem with argument newLabelSet.
LabelledItem : FunctionDeclaration
  1. Return false.
TryStatement : try Block Catch
  1. Let hasDuplicates be ContainsDuplicateLabels of Block with argument labelSet.
  2. If hasDuplicates is true, return true.
  3. Return ContainsDuplicateLabels of Catch with argument labelSet.
TryStatement : try Block Finally
  1. Let hasDuplicates be ContainsDuplicateLabels of Block with argument labelSet.
  2. If hasDuplicates is true, return true.
  3. Return ContainsDuplicateLabels of Finally with argument labelSet.
TryStatement : try Block Catch Finally
  1. If ContainsDuplicateLabels of Block with argument labelSet is true, return true.
  2. If ContainsDuplicateLabels of Catch with argument labelSet is true, return true.
  3. Return ContainsDuplicateLabels of Finally with argument labelSet.
Catch : catch ( CatchParameter ) Block
  1. Return ContainsDuplicateLabels of Block with argument labelSet.
FunctionStatementList : [empty]
  1. Return false.
ClassStaticBlockStatementList : [empty]
  1. Return false.
ModuleItemList : ModuleItemList ModuleItem
  1. Let hasDuplicates be ContainsDuplicateLabels of ModuleItemList with argument labelSet.
  2. If hasDuplicates is true, return true.
  3. Return ContainsDuplicateLabels of ModuleItem with argument labelSet.
ModuleItem : ImportDeclaration ExportDeclaration
  1. Return false.

8.3.2 Static Semantics: ContainsUndefinedBreakTarget

The syntax-directed operation ContainsUndefinedBreakTarget takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. Return false.
StatementList : StatementList StatementListItem
  1. Let hasUndefinedLabels be ContainsUndefinedBreakTarget of StatementList with argument labelSet.
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedBreakTarget of StatementListItem with argument labelSet.
IfStatement : if ( Expression ) Statement else Statement
  1. Let hasUndefinedLabels be ContainsUndefinedBreakTarget of the first Statement with argument labelSet.
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedBreakTarget of the second Statement with argument labelSet.
IfStatement : if ( Expression ) Statement
  1. Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
WhileStatement : while ( Expression ) Statement
  1. Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 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
  1. Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
Note

This section is extended by Annex B.3.5.

BreakStatement : break ;
  1. Return false.
BreakStatement : break LabelIdentifier ;
  1. If labelSet does not contain the StringValue of LabelIdentifier, return true.
  2. Return false.
WithStatement : with ( Expression ) Statement
  1. Return ContainsUndefinedBreakTarget of Statement with argument labelSet.
SwitchStatement : switch ( Expression ) CaseBlock
  1. Return ContainsUndefinedBreakTarget of CaseBlock with argument labelSet.
CaseBlock : { }
  1. Return false.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. If the first CaseClauses is present, then
    1. If ContainsUndefinedBreakTarget of the first CaseClauses with argument labelSet is true, return true.
  2. If ContainsUndefinedBreakTarget of DefaultClause with argument labelSet is true, return true.
  3. If the second CaseClauses is not present, return false.
  4. Return ContainsUndefinedBreakTarget of the second CaseClauses with argument labelSet.
CaseClauses : CaseClauses CaseClause
  1. Let hasUndefinedLabels be ContainsUndefinedBreakTarget of CaseClauses with argument labelSet.
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedBreakTarget of CaseClause with argument labelSet.
CaseClause : case Expression : StatementListopt
  1. If the StatementList is present, return ContainsUndefinedBreakTarget of StatementList with argument labelSet.
  2. Return false.
DefaultClause : default : StatementListopt
  1. If the StatementList is present, return ContainsUndefinedBreakTarget of StatementList with argument labelSet.
  2. Return false.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Let label be the StringValue of LabelIdentifier.
  2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  3. Return ContainsUndefinedBreakTarget of LabelledItem with argument newLabelSet.
LabelledItem : FunctionDeclaration
  1. Return false.
TryStatement : try Block Catch
  1. Let hasUndefinedLabels be ContainsUndefinedBreakTarget of Block with argument labelSet.
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedBreakTarget of Catch with argument labelSet.
TryStatement : try Block Finally
  1. Let hasUndefinedLabels be ContainsUndefinedBreakTarget of Block with argument labelSet.
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedBreakTarget of Finally with argument labelSet.
TryStatement : try Block Catch Finally
  1. If ContainsUndefinedBreakTarget of Block with argument labelSet is true, return true.
  2. If ContainsUndefinedBreakTarget of Catch with argument labelSet is true, return true.
  3. Return ContainsUndefinedBreakTarget of Finally with argument labelSet.
Catch : catch ( CatchParameter ) Block
  1. Return ContainsUndefinedBreakTarget of Block with argument labelSet.
FunctionStatementList : [empty]
  1. Return false.
ClassStaticBlockStatementList : [empty]
  1. Return false.
ModuleItemList : ModuleItemList ModuleItem
  1. Let hasUndefinedLabels be ContainsUndefinedBreakTarget of ModuleItemList with argument labelSet.
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedBreakTarget of ModuleItem with argument labelSet.
ModuleItem : ImportDeclaration ExportDeclaration
  1. Return false.

8.3.3 Static Semantics: ContainsUndefinedContinueTarget

The syntax-directed operation ContainsUndefinedContinueTarget takes arguments iterationSet (a List of Strings) and labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. Return false.
Statement : BlockStatement
  1. Return ContainsUndefinedContinueTarget of BlockStatement with arguments iterationSet and « ».
BreakableStatement : IterationStatement
  1. Let newIterationSet be the list-concatenation of iterationSet and labelSet.
  2. Return ContainsUndefinedContinueTarget of IterationStatement with arguments newIterationSet and « ».
StatementList : StatementList StatementListItem
  1. Let hasUndefinedLabels be ContainsUndefinedContinueTarget of StatementList with arguments iterationSet and « ».
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedContinueTarget of StatementListItem with arguments iterationSet and « ».
IfStatement : if ( Expression ) Statement else Statement
  1. Let hasUndefinedLabels be ContainsUndefinedContinueTarget of the first Statement with arguments iterationSet and « ».
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedContinueTarget of the second Statement with arguments iterationSet and « ».
IfStatement : if ( Expression ) Statement
  1. Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
DoWhileStatement : do Statement while ( Expression ) ;
  1. Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
WhileStatement : while ( Expression ) Statement
  1. 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
  1. 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
  1. Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
Note

This section is extended by Annex B.3.5.

ContinueStatement : continue ;
  1. Return false.
ContinueStatement : continue LabelIdentifier ;
  1. If iterationSet does not contain the StringValue of LabelIdentifier, return true.
  2. Return false.
WithStatement : with ( Expression ) Statement
  1. Return ContainsUndefinedContinueTarget of Statement with arguments iterationSet and « ».
SwitchStatement : switch ( Expression ) CaseBlock
  1. Return ContainsUndefinedContinueTarget of CaseBlock with arguments iterationSet and « ».
CaseBlock : { }
  1. Return false.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. If the first CaseClauses is present, then
    1. If ContainsUndefinedContinueTarget of the first CaseClauses with arguments iterationSet and « » is true, return true.
  2. If ContainsUndefinedContinueTarget of DefaultClause with arguments iterationSet and « » is true, return true.
  3. If the second CaseClauses is not present, return false.
  4. Return ContainsUndefinedContinueTarget of the second CaseClauses with arguments iterationSet and « ».
CaseClauses : CaseClauses CaseClause
  1. Let hasUndefinedLabels be ContainsUndefinedContinueTarget of CaseClauses with arguments iterationSet and « ».
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedContinueTarget of CaseClause with arguments iterationSet and « ».
CaseClause : case Expression : StatementListopt
  1. If the StatementList is present, return ContainsUndefinedContinueTarget of StatementList with arguments iterationSet and « ».
  2. Return false.
DefaultClause : default : StatementListopt
  1. If the StatementList is present, return ContainsUndefinedContinueTarget of StatementList with arguments iterationSet and « ».
  2. Return false.
LabelledStatement : LabelIdentifier : LabelledItem
  1. Let label be the StringValue of LabelIdentifier.
  2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  3. Return ContainsUndefinedContinueTarget of LabelledItem with arguments iterationSet and newLabelSet.
LabelledItem : FunctionDeclaration
  1. Return false.
TryStatement : try Block Catch
  1. Let hasUndefinedLabels be ContainsUndefinedContinueTarget of Block with arguments iterationSet and « ».
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedContinueTarget of Catch with arguments iterationSet and « ».
TryStatement : try Block Finally
  1. Let hasUndefinedLabels be ContainsUndefinedContinueTarget of Block with arguments iterationSet and « ».
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedContinueTarget of Finally with arguments iterationSet and « ».
TryStatement : try Block Catch Finally
  1. If ContainsUndefinedContinueTarget of Block with arguments iterationSet and « » is true, return true.
  2. If ContainsUndefinedContinueTarget of Catch with arguments iterationSet and « » is true, return true.
  3. Return ContainsUndefinedContinueTarget of Finally with arguments iterationSet and « ».
Catch : catch ( CatchParameter ) Block
  1. Return ContainsUndefinedContinueTarget of Block with arguments iterationSet and « ».
FunctionStatementList : [empty]
  1. Return false.
ClassStaticBlockStatementList : [empty]
  1. Return false.
ModuleItemList : ModuleItemList ModuleItem
  1. Let hasUndefinedLabels be ContainsUndefinedContinueTarget of ModuleItemList with arguments iterationSet and « ».
  2. If hasUndefinedLabels is true, return true.
  3. Return ContainsUndefinedContinueTarget of ModuleItem with arguments iterationSet and « ».
ModuleItem : ImportDeclaration ExportDeclaration
  1. Return false.

8.4 Function Name Inference

8.4.1 Static Semantics: HasName

The syntax-directed operation HasName takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. Let expr be the ParenthesizedExpression that is covered by CoverParenthesizedExpressionAndArrowParameterList.
  2. If IsFunctionDefinition of expr is false, return false.
  3. 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
  1. 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
  1. Return true.

8.4.2 Static Semantics: IsFunctionDefinition

The syntax-directed operation IsFunctionDefinition takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. Let expr be the ParenthesizedExpression that is covered by CoverParenthesizedExpressionAndArrowParameterList.
  2. Return IsFunctionDefinition of expr.
PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral RegularExpressionLiteral TemplateLiteral MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier 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 PrivateIdentifier 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
  1. 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
  1. Return true.

8.4.3 Static Semantics: IsAnonymousFunctionDefinition ( expr )

The abstract operation IsAnonymousFunctionDefinition takes argument expr (an AssignmentExpression Parse Node, an Initializer Parse Node, or an Expression Parse Node) and returns a Boolean. It determines if its argument is a function definition that does not bind a name. It performs the following steps when called:

  1. If IsFunctionDefinition of expr is false, return false.
  2. Let hasName be HasName of expr.
  3. If hasName is true, return false.
  4. Return true.

8.4.4 Static Semantics: IsIdentifierRef

The syntax-directed operation IsIdentifierRef takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : IdentifierReference
  1. 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 MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
  1. Return false.

8.4.5 Runtime Semantics: NamedEvaluation

The syntax-directed operation NamedEvaluation takes argument name (a property key or a Private Name) and returns either a normal completion containing a function object or an abrupt completion. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. Let expr be the ParenthesizedExpression that is covered by CoverParenthesizedExpressionAndArrowParameterList.
  2. Return ? NamedEvaluation of expr with argument name.
ParenthesizedExpression : ( Expression )
  1. Assert: IsAnonymousFunctionDefinition(Expression) is true.
  2. Return ? NamedEvaluation of Expression with argument name.
FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. Return InstantiateOrdinaryFunctionExpression of FunctionExpression with argument name.
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. Return InstantiateGeneratorFunctionExpression of GeneratorExpression with argument name.
AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. Return InstantiateAsyncGeneratorFunctionExpression of AsyncGeneratorExpression with argument name.
AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. Return InstantiateAsyncFunctionExpression of AsyncFunctionExpression with argument name.
ArrowFunction : ArrowParameters => ConciseBody
  1. Return InstantiateArrowFunctionExpression of ArrowFunction with argument name.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. Return InstantiateAsyncArrowFunctionExpression of AsyncArrowFunction with argument name.
ClassExpression : class ClassTail
  1. Let sourceText be the source text matched by ClassExpression.
  2. Return ? ClassDefinitionEvaluation of ClassTail with arguments undefined, name, and sourceText.

8.5 Contains

8.5.1 Static Semantics: Contains

The syntax-directed operation Contains takes argument symbol (a grammar symbol) and returns a Boolean.

Every grammar production alternative in this specification which is not listed below implicitly has the following default definition of Contains:

  1. For each child node child of this Parse Node, do
    1. If child is an instance of symbol, return true.
    2. If child is an instance of a nonterminal, then
      1. Let contained be the result of child Contains symbol.
      2. If contained is true, return true.
  2. 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 }
  1. Return false.
Note 1

Static semantic rules that depend upon substructure generally do not look into function definitions.

ClassTail : ClassHeritageopt { ClassBody }
  1. If symbol is ClassBody, return true.
  2. If symbol is ClassHeritage, then
    1. If ClassHeritage is present, return true; otherwise return false.
  3. If ClassHeritage is present, then
    1. If ClassHeritage Contains symbol is true, return true.
  4. Return the result of ComputedPropertyContains of ClassBody with argument symbol.
Note 2

Static semantic rules that depend upon substructure generally do not look into class bodies except for PropertyNames.

ClassStaticBlock : static { ClassStaticBlockBody }
  1. Return false.
Note 3

Static semantic rules that depend upon substructure generally do not look into static initialization blocks.

ArrowFunction : ArrowParameters => ConciseBody
  1. If symbol is not one of NewTarget, SuperProperty, SuperCall, super, or this, return false.
  2. If ArrowParameters Contains symbol is true, return true.
  3. Return ConciseBody Contains symbol.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. Let formals be the ArrowFormalParameters that is covered by CoverParenthesizedExpressionAndArrowParameterList.
  2. Return formals Contains symbol.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. If symbol is not one of NewTarget, SuperProperty, SuperCall, super, or this, return false.
  2. Return AsyncConciseBody Contains symbol.
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. If symbol is not one of NewTarget, SuperProperty, SuperCall, super, or this, return false.
  2. Let head be the AsyncArrowHead that is covered by CoverCallExpressionAndAsyncArrowHead.
  3. If head Contains symbol is true, return true.
  4. Return AsyncConciseBody Contains symbol.
Note 4

Contains is used to detect new.target, this, and super usage within an ArrowFunction or AsyncArrowFunction.

PropertyDefinition : MethodDefinition
  1. If symbol is MethodDefinition, return true.
  2. Return the result of ComputedPropertyContains of MethodDefinition with argument symbol.
LiteralPropertyName : IdentifierName
  1. Return false.
MemberExpression : MemberExpression . IdentifierName
  1. If MemberExpression Contains symbol is true, return true.
  2. Return false.
SuperProperty : super . IdentifierName
  1. If symbol is the ReservedWord super, return true.
  2. Return false.
CallExpression : CallExpression . IdentifierName
  1. If CallExpression Contains symbol is true, return true.
  2. Return false.
OptionalChain : ?. IdentifierName
  1. Return false.
OptionalChain : OptionalChain . IdentifierName
  1. If OptionalChain Contains symbol is true, return true.
  2. Return false.

8.5.2 Static Semantics: ComputedPropertyContains

The syntax-directed operation ComputedPropertyContains takes argument symbol (a grammar symbol) and returns a Boolean. It is defined piecewise over the following productions:

ClassElementName : PrivateIdentifier PropertyName : LiteralPropertyName
  1. Return false.
PropertyName : ComputedPropertyName
  1. Return the result of ComputedPropertyName Contains symbol.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. Return the result of ComputedPropertyContains of ClassElementName with argument symbol.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. Return the result of ComputedPropertyContains of ClassElementName with argument symbol.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. Return the result of ComputedPropertyContains of ClassElementName with argument symbol.
ClassElementList : ClassElementList ClassElement
  1. Let inList be ComputedPropertyContains of ClassElementList with argument symbol.
  2. If inList is true, return true.
  3. Return the result of ComputedPropertyContains of ClassElement with argument symbol.
ClassElement : ClassStaticBlock
  1. Return false.
ClassElement : ;
  1. Return false.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. Return the result of ComputedPropertyContains of ClassElementName with argument symbol.
FieldDefinition : ClassElementName Initializeropt
  1. Return the result of ComputedPropertyContains of ClassElementName with argument symbol.

8.6 Miscellaneous

These operations are used in multiple places throughout the specification.

8.6.1 Runtime Semantics: InstantiateFunctionObject

The syntax-directed operation InstantiateFunctionObject takes arguments env (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody }
  1. Return InstantiateOrdinaryFunctionObject of FunctionDeclaration with arguments env and privateEnv.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody }
  1. Return InstantiateGeneratorFunctionObject of GeneratorDeclaration with arguments env and privateEnv.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. Return InstantiateAsyncGeneratorFunctionObject of AsyncGeneratorDeclaration with arguments env and privateEnv.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. Return InstantiateAsyncFunctionObject of AsyncFunctionDeclaration with arguments env and privateEnv.

8.6.2 Runtime Semantics: BindingInitialization

The syntax-directed operation BindingInitialization takes arguments value (an ECMAScript language value) and environment (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

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.11). In those cases a lexical binding is hoisted and preinitialized prior to evaluation of its initializer.

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. Let name be the StringValue of Identifier.
  2. Return ? InitializeBoundName(name, value, environment).
BindingIdentifier : yield
  1. Return ? InitializeBoundName("yield", value, environment).
BindingIdentifier : await
  1. Return ? InitializeBoundName("await", value, environment).
BindingPattern : ObjectBindingPattern
  1. Perform ? RequireObjectCoercible(value).
  2. Return ? BindingInitialization of ObjectBindingPattern with arguments value and environment.
BindingPattern : ArrayBindingPattern
  1. Let iteratorRecord be ? GetIterator(value, sync).
  2. Let result be Completion(IteratorBindingInitialization of ArrayBindingPattern with arguments iteratorRecord and environment).
  3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  4. Return ? result.
ObjectBindingPattern : { }
  1. Return unused.
ObjectBindingPattern : { BindingPropertyList } { BindingPropertyList , }
  1. Perform ? PropertyBindingInitialization of BindingPropertyList with arguments value and environment.
  2. Return unused.
ObjectBindingPattern : { BindingRestProperty }
  1. Let excludedNames be a new empty List.
  2. Return ? RestBindingInitialization of BindingRestProperty with arguments value, environment, and excludedNames.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. Let excludedNames be ? PropertyBindingInitialization of BindingPropertyList with arguments value and environment.
  2. Return ? RestBindingInitialization of BindingRestProperty with arguments value, environment, and excludedNames.

8.6.2.1 InitializeBoundName ( name, value, environment )

The abstract operation InitializeBoundName takes arguments name (a String), value (an ECMAScript language value), and environment (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. If environment is not undefined, then
    1. Perform ! environment.InitializeBinding(name, value).
    2. Return unused.
  2. Else,
    1. Let lhs be ? ResolveBinding(name).
    2. Return ? PutValue(lhs, value).

8.6.3 Runtime Semantics: IteratorBindingInitialization

The syntax-directed operation IteratorBindingInitialization takes arguments iteratorRecord (an Iterator Record) and environment (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

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.

It is defined piecewise over the following productions:

ArrayBindingPattern : [ ]
  1. Return unused.
ArrayBindingPattern : [ Elision ]
  1. Return ? IteratorDestructuringAssignmentEvaluation of Elision with argument iteratorRecord.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. If Elision is present, then
    1. Perform ? IteratorDestructuringAssignmentEvaluation of Elision with argument iteratorRecord.
  2. Return ? IteratorBindingInitialization of BindingRestElement with arguments iteratorRecord and environment.
ArrayBindingPattern : [ BindingElementList , Elision ]
  1. Perform ? IteratorBindingInitialization of BindingElementList with arguments iteratorRecord and environment.
  2. Return ? IteratorDestructuringAssignmentEvaluation of Elision with argument iteratorRecord.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. Perform ? IteratorBindingInitialization of BindingElementList with arguments iteratorRecord and environment.
  2. If Elision is present, then
    1. Perform ? IteratorDestructuringAssignmentEvaluation of Elision with argument iteratorRecord.
  3. Return ? IteratorBindingInitialization of BindingRestElement with arguments iteratorRecord and environment.
BindingElementList : BindingElementList , BindingElisionElement
  1. Perform ? IteratorBindingInitialization of BindingElementList with arguments iteratorRecord and environment.
  2. Return ? IteratorBindingInitialization of BindingElisionElement with arguments iteratorRecord and environment.
BindingElisionElement : Elision BindingElement
  1. Perform ? IteratorDestructuringAssignmentEvaluation of Elision with argument iteratorRecord.
  2. Return ? IteratorBindingInitialization of BindingElement with arguments iteratorRecord and environment.
SingleNameBinding : BindingIdentifier Initializeropt
  1. Let bindingId be the StringValue of BindingIdentifier.
  2. Let lhs be ? ResolveBinding(bindingId, environment).
  3. Let v be undefined.
  4. If iteratorRecord.[[Done]] is false, then
    1. Let next be ? IteratorStepValue(iteratorRecord).
    2. If next is not done, then
      1. Set v to next.
  5. If Initializer is present and v is undefined, then
    1. If IsAnonymousFunctionDefinition(Initializer) is true, then
      1. Set v to ? NamedEvaluation of Initializer with argument bindingId.
    2. Else,
      1. Let defaultValue be ? Evaluation of Initializer.
      2. Set v to ? GetValue(defaultValue).
  6. If environment is undefined, return ? PutValue(lhs, v).
  7. Return ? InitializeReferencedBinding(lhs, v).
BindingElement : BindingPattern Initializeropt
  1. Let v be undefined.
  2. If iteratorRecord.[[Done]] is false, then
    1. Let next be ? IteratorStepValue(iteratorRecord).
    2. If next is not done, then
      1. Set v to next.
  3. If Initializer is present and v is undefined, then
    1. Let defaultValue be ? Evaluation of Initializer.
    2. Set v to ? GetValue(defaultValue).
  4. Return ? BindingInitialization of BindingPattern with arguments v and environment.
BindingRestElement : ... BindingIdentifier
  1. Let lhs be ? ResolveBinding(StringValue of BindingIdentifier, environment).
  2. Let A be ! ArrayCreate(0).
  3. Let n be 0.
  4. Repeat,
    1. Let next be done.
    2. If iteratorRecord.[[Done]] is false, then
      1. Set next to ? IteratorStepValue(iteratorRecord).
    3. If next is done, then
      1. If environment is undefined, return ? PutValue(lhs, A).
      2. Return ? InitializeReferencedBinding(lhs, A).
    4. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), next).
    5. Set n to n + 1.
BindingRestElement : ... BindingPattern
  1. Let A be ! ArrayCreate(0).
  2. Let n be 0.
  3. Repeat,
    1. Let next be done.
    2. If iteratorRecord.[[Done]] is false, then
      1. Set next to ? IteratorStepValue(iteratorRecord).
    3. If next is done, then
      1. Return ? BindingInitialization of BindingPattern with arguments A and environment.
    4. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), next).
    5. Set n to n + 1.
FormalParameters : [empty]
  1. Return unused.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. Perform ? IteratorBindingInitialization of FormalParameterList with arguments iteratorRecord and environment.
  2. Return ? IteratorBindingInitialization of FunctionRestParameter with arguments iteratorRecord and environment.
FormalParameterList : FormalParameterList , FormalParameter
  1. Perform ? IteratorBindingInitialization of FormalParameterList with arguments iteratorRecord and environment.
  2. Return ? IteratorBindingInitialization of FormalParameter with arguments iteratorRecord and environment.
ArrowParameters : BindingIdentifier
  1. Let v be undefined.
  2. Assert: iteratorRecord.[[Done]] is false.
  3. Let next be ? IteratorStepValue(iteratorRecord).
  4. If next is not done, then
    1. Set v to next.
  5. Return ? BindingInitialization of BindingIdentifier with arguments v and environment.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. Let formals be the ArrowFormalParameters that is covered by CoverParenthesizedExpressionAndArrowParameterList.
  2. Return ? IteratorBindingInitialization of formals with arguments iteratorRecord and environment.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. Let v be undefined.
  2. Assert: iteratorRecord.[[Done]] is false.
  3. Let next be ? IteratorStepValue(iteratorRecord).
  4. If next is not done, then
    1. Set v to next.
  5. Return ? BindingInitialization of BindingIdentifier with arguments v and environment.

8.6.4 Static Semantics: AssignmentTargetType

The syntax-directed operation AssignmentTargetType takes no arguments and returns simple, web-compat, or invalid. It is defined piecewise over the following productions:

IdentifierReference : Identifier
  1. If IsStrict(this IdentifierReference) is true and the StringValue of Identifier is either "eval" or "arguments", return invalid.
  2. Return simple.
IdentifierReference : yield await CallExpression : CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MemberExpression . PrivateIdentifier
  1. Return simple.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. Let expr be the ParenthesizedExpression that is covered by CoverParenthesizedExpressionAndArrowParameterList.
  2. Return the AssignmentTargetType of expr.
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments
  1. If the host is a web browser or otherwise supports Runtime Errors for Function Call Assignment Targets and IsStrict(this CallExpression) is false, then
    1. Return web-compat.
  2. Return invalid.
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CallExpression : SuperCall ImportCall 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 PrivateIdentifier 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
  1. Return invalid.

8.6.5 Static Semantics: PropName

The syntax-directed operation PropName takes no arguments and returns a String or empty. It is defined piecewise over the following productions:

PropertyDefinition : IdentifierReference
  1. Return the StringValue of IdentifierReference.
PropertyDefinition : ... AssignmentExpression
  1. Return empty.
PropertyDefinition : PropertyName : AssignmentExpression
  1. Return the PropName of PropertyName.
LiteralPropertyName : IdentifierName AttributeKey : IdentifierName
  1. Return the StringValue of IdentifierName.
LiteralPropertyName : StringLiteral AttributeKey : StringLiteral
  1. Return the SV of StringLiteral.
LiteralPropertyName : NumericLiteral
  1. Let nbr be the NumericValue of NumericLiteral.
  2. Return ! ToString(nbr).
ComputedPropertyName : [ AssignmentExpression ]
  1. Return empty.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. Return the PropName of ClassElementName.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. Return the PropName of ClassElementName.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. Return the PropName of ClassElementName.
ClassElement : ClassStaticBlock
  1. Return empty.
ClassElement : ;
  1. Return empty.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. Return the PropName of ClassElementName.
FieldDefinition : ClassElementName Initializeropt
  1. Return the PropName of ClassElementName.
ClassElementName : PrivateIdentifier
  1. Return empty.

9 Executable Code and Execution Contexts

9.1 Environment Records

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.

9.1.1 The Environment Record Type Hierarchy

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.

The Environment Record abstract class includes the abstract specification methods defined in Table 14. These abstract methods have distinct concrete algorithms for each of the concrete subclasses.

Table 14: 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. If it returns true it implies that the Environment Record is a Function Environment Record, although the reverse implication does not hold.
WithBaseObject() If this Environment Record is associated with a with statement, return the with object. Otherwise, return undefined.

9.1.1.1 Declarative Environment Records

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.

9.1.1.1.1 HasBinding ( N )

The HasBinding concrete method of a Declarative Environment Record envRec takes argument N (a String) and returns a normal completion containing a Boolean. It determines if the argument identifier is one of the identifiers bound by the record. It performs the following steps when called:

  1. If envRec has a binding for N, return true.
  2. Return false.

9.1.1.1.2 CreateMutableBinding ( N, D )

The CreateMutableBinding concrete method of a Declarative Environment Record envRec takes arguments N (a String) and D (a Boolean) and returns a normal completion containing unused. 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 is true, the new binding is marked as being subject to deletion. It performs the following steps when called:

  1. Assert: envRec does not already have a binding for N.
  2. 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.
  3. Return unused.

9.1.1.1.3 CreateImmutableBinding ( N, S )

The CreateImmutableBinding concrete method of a Declarative Environment Record envRec takes arguments N (a String) and S (a Boolean) and returns a normal completion containing unused. 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 is true, the new binding is marked as a strict binding. It performs the following steps when called:

  1. Assert: envRec does not already have a binding for N.
  2. 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.
  3. Return unused.

9.1.1.1.4 InitializeBinding ( N, V )

The InitializeBinding concrete method of a Declarative Environment Record envRec takes arguments N (a String) and V (an ECMAScript language value) and returns a normal completion containing unused. It is used to set the bound value of the current binding of the identifier whose name is N to the value V. An uninitialized binding for N must already exist. It performs the following steps when called:

  1. Assert: envRec must have an uninitialized binding for N.
  2. Set the bound value for N in envRec to V.
  3. Record that the binding for N in envRec has been initialized.
  4. Return unused.

9.1.1.1.5 SetMutableBinding ( N, V, S )

The SetMutableBinding concrete method of a Declarative Environment Record envRec takes arguments N (a String), V (an ECMAScript language value), and S (a Boolean) and returns either a normal completion containing unused or a throw completion. It attempts to change the bound value of the current binding of the identifier whose name is N to the value 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:

  1. If envRec does not have a binding for N, then
    1. If S is true, throw a ReferenceError exception.
    2. Perform ! envRec.CreateMutableBinding(N, true).
    3. Perform ! envRec.InitializeBinding(N, V).
    4. Return unused.
  2. If the binding for N in envRec is a strict binding, set S to true.
  3. If the binding for N in envRec has not yet been initialized, then
    1. Throw a ReferenceError exception.
  4. Else if the binding for N in envRec is a mutable binding, then
    1. Change its bound value to V.
  5. Else,
    1. Assert: This is an attempt to change the value of an immutable binding.
    2. If S is true, throw a TypeError exception.
  6. Return unused.
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);"); }

9.1.1.1.6 GetBindingValue ( N, S )

The GetBindingValue concrete method of a Declarative Environment Record envRec takes arguments N (a String) and S (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. It returns the value of its bound identifier whose name is 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:

  1. Assert: envRec has a binding for N.
  2. If the binding for N in envRec is an uninitialized binding, throw a ReferenceError exception.
  3. Return the value currently bound to N in envRec.

9.1.1.1.7 DeleteBinding ( N )

The DeleteBinding concrete method of a Declarative Environment Record envRec takes argument N (a String) and returns a normal completion containing a Boolean. It can only delete bindings that have been explicitly designated as being subject to deletion. It performs the following steps when called:

  1. Assert: envRec has a binding for N.
  2. If the binding for N in envRec cannot be deleted, return false.
  3. Remove the binding for N from envRec.
  4. Return true.

9.1.1.1.8 HasThisBinding ( )

The HasThisBinding concrete method of a Declarative Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. 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.

9.1.1.1.9 HasSuperBinding ( )

The HasSuperBinding concrete method of a Declarative Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. 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.

9.1.1.1.10 WithBaseObject ( )

The WithBaseObject concrete method of a Declarative Environment Record envRec takes no arguments and returns undefined. It performs the following steps when called:

  1. Return undefined.

9.1.1.2 Object Environment Records

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 is 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 Boolean [[IsWithEnvironment]] field.

Object Environment Records have the additional state fields listed in Table 15.

Table 15: Additional Fields of Object Environment Records
Field Name Value Meaning
[[BindingObject]] an Object The binding object of this Environment Record.
[[IsWithEnvironment]] a Boolean Indicates whether this Environment Record is created for a with statement.

9.1.1.2.1 HasBinding ( N )

The HasBinding concrete method of an Object Environment Record envRec takes argument N (a String) and returns either a normal completion containing a Boolean or a throw completion. It determines if its associated binding object has a property whose name is N. It performs the following steps when called:

  1. Let bindingObject be envRec.[[BindingObject]].
  2. Let foundBinding be ? HasProperty(bindingObject, N).
  3. If foundBinding is false, return false.
  4. If envRec.[[IsWithEnvironment]] is false, return true.
  5. Let unscopables be ? Get(bindingObject, %Symbol.unscopables%).
  6. If unscopables is an Object, then
    1. Let blocked be ToBoolean(? Get(unscopables, N)).
    2. If blocked is true, return false.
  7. Return true.

9.1.1.2.2 CreateMutableBinding ( N, D )

The CreateMutableBinding concrete method of an Object Environment Record envRec takes arguments N (a String) and D (a Boolean) and returns either a normal completion containing unused or a throw completion. It creates in an Environment Record's associated binding object a property whose name is N and initializes it to the value undefined. If D is true, the new property's [[Configurable]] attribute is set to true; otherwise it is set to false. It performs the following steps when called:

  1. Let bindingObject be envRec.[[BindingObject]].
  2. Perform ? DefinePropertyOrThrow(bindingObject, N, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }).
  3. Return unused.
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.

9.1.1.2.3 CreateImmutableBinding ( N, S )

The CreateImmutableBinding concrete method of an Object Environment Record is never used within this specification.

9.1.1.2.4 InitializeBinding ( N, V )

The InitializeBinding concrete method of an Object Environment Record envRec takes arguments N (a String) and V (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It is used to set the bound value of the current binding of the identifier whose name is N to the value V. It performs the following steps when called:

  1. Perform ? envRec.SetMutableBinding(N, V, false).
  2. Return unused.
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.

9.1.1.2.5 SetMutableBinding ( N, V, S )

The SetMutableBinding concrete method of an Object Environment Record envRec takes arguments N (a String), V (an ECMAScript language value), and S (a Boolean) and returns either a normal completion containing unused or a throw completion. It attempts to set the value of the Environment Record's associated binding object's property whose name is N to the value 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:

  1. Let bindingObject be envRec.[[BindingObject]].
  2. Let stillExists be ? HasProperty(bindingObject, N).
  3. If stillExists is false and S is true, throw a ReferenceError exception.
  4. Perform ? Set(bindingObject, N, V, S).
  5. Return unused.

9.1.1.2.6 GetBindingValue ( N, S )

The GetBindingValue concrete method of an Object Environment Record envRec takes arguments N (a String) and S (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. It returns the value of its associated binding object's property whose name is N. The property should already exist but if it does not the result depends upon S. It performs the following steps when called:

  1. Let bindingObject be envRec.[[BindingObject]].
  2. Let value be ? HasProperty(bindingObject, N).
  3. If value is false, then
    1. If S is false, return undefined; otherwise throw a ReferenceError exception.
  4. Return ? Get(bindingObject, N).

9.1.1.2.7 DeleteBinding ( N )

The DeleteBinding concrete method of an Object Environment Record envRec takes argument N (a String) and returns either a normal completion containing a Boolean or a throw completion. 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:

  1. Let bindingObject be envRec.[[BindingObject]].
  2. Return ? bindingObject.[[Delete]](N).

9.1.1.2.8 HasThisBinding ( )

The HasThisBinding concrete method of an Object Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. Return false.
Note

Object Environment Records do not provide a this binding.

9.1.1.2.9 HasSuperBinding ( )

The HasSuperBinding concrete method of an Object Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. Return false.
Note

Object Environment Records do not provide a super binding.

9.1.1.2.10 WithBaseObject ( )

The WithBaseObject concrete method of an Object Environment Record envRec takes no arguments and returns an Object or undefined. It performs the following steps when called:

  1. If envRec.[[IsWithEnvironment]] is true, return envRec.[[BindingObject]].
  2. Otherwise, return undefined.

9.1.1.3 Function Environment Records

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 16.

Table 16: Additional Fields of Function Environment Records
Field Name Value Meaning
[[ThisValue]] an ECMAScript language value This is the this value used for this invocation of the function.
[[ThisBindingStatus]] lexical, initialized, or uninitialized If the value is lexical, this is an ArrowFunction and does not have a local this value.
[[FunctionObject]] an ECMAScript function object The function object whose invocation caused this Environment Record to be created.
[[NewTarget]] a constructor or undefined If this Environment Record was created by the [[Construct]] internal method, [[NewTarget]] is the value of the [[Construct]] newTarget parameter. Otherwise, its value is undefined.

Function Environment Records support all of the Declarative Environment Record methods listed in Table 14 and share the same specifications for all of those methods except for HasThisBinding and HasSuperBinding. In addition, Function Environment Records support the methods listed in Table 17:

Table 17: Additional Methods of Function Environment Records
Method Purpose
GetThisBinding() Return the value of this Environment Record's this binding. Throws a ReferenceError if the this binding has not been initialized.

9.1.1.3.1 BindThisValue ( envRec, V )

The abstract operation BindThisValue takes arguments envRec (a Function Environment Record) and V (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It sets the envRec.[[ThisValue]] and records that it has been initialized. It performs the following steps when called:

  1. Assert: envRec.[[ThisBindingStatus]] is not lexical.
  2. If envRec.[[ThisBindingStatus]] is initialized, throw a ReferenceError exception.
  3. Set envRec.[[ThisValue]] to V.
  4. Set envRec.[[ThisBindingStatus]] to initialized.
  5. Return unused.

9.1.1.3.2 HasThisBinding ( )

The HasThisBinding concrete method of a Function Environment Record envRec takes no arguments and returns a Boolean. It performs the following steps when called:

  1. If envRec.[[ThisBindingStatus]] is lexical, return false; otherwise return true.

9.1.1.3.3 HasSuperBinding ( )

The HasSuperBinding concrete method of a Function Environment Record envRec takes no arguments and returns a Boolean. It performs the following steps when called:

  1. If envRec.[[ThisBindingStatus]] is lexical, return false.
  2. If envRec.[[FunctionObject]].[[HomeObject]] is undefined, return false; otherwise return true.

9.1.1.3.4 GetThisBinding ( )

The GetThisBinding concrete method of a Function Environment Record envRec takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Assert: envRec.[[ThisBindingStatus]] is not lexical.
  2. If envRec.[[ThisBindingStatus]] is uninitialized, throw a ReferenceError exception.
  3. Return envRec.[[ThisValue]].

9.1.1.3.5 GetSuperBase ( envRec )

The abstract operation GetSuperBase takes argument envRec (a Function Environment Record) and returns an Object, null, or undefined. It returns the object that is the base for super property accesses bound in envRec. The value undefined indicates that such accesses will produce runtime errors. It performs the following steps when called:

  1. Let home be envRec.[[FunctionObject]].[[HomeObject]].
  2. If home is undefined, return undefined.
  3. Assert: home is an ordinary object.
  4. Return ! home.[[GetPrototypeOf]]().

9.1.1.4 Global Environment Records

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.2.9, 8.2.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 the CreateGlobalVarBinding and CreateGlobalFunctionBinding abstract operations.

Global Environment Records have the additional fields listed in Table 18 and the additional methods listed in Table 19.

Table 18: Additional Fields of Global Environment Records
Field Name Value Meaning
[[ObjectRecord]] an 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]] an Object The value returned by this in global scope. Hosts may provide any ECMAScript Object value.
[[DeclarativeRecord]] a 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.
Table 19: Additional Methods of Global Environment Records
Method Purpose
GetThisBinding() Return the value of this Environment Record's this binding.

9.1.1.4.1 HasBinding ( N )

The HasBinding concrete method of a Global Environment Record envRec takes argument N (a String) and returns either a normal completion containing a Boolean or a throw completion. It determines if the argument identifier is one of the identifiers bound by the record. It performs the following steps when called:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. If ! DclRec.HasBinding(N) is true, return true.
  3. Let ObjRec be envRec.[[ObjectRecord]].
  4. Return ? ObjRec.HasBinding(N).

9.1.1.4.2 CreateMutableBinding ( N, D )

The CreateMutableBinding concrete method of a Global Environment Record envRec takes arguments N (a String) and D (a Boolean) and returns either a normal completion containing unused or a throw completion. 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 is true, the new binding is marked as being subject to deletion. It performs the following steps when called:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. If ! DclRec.HasBinding(N) is true, throw a TypeError exception.
  3. Return ! DclRec.CreateMutableBinding(N, D).

9.1.1.4.3 CreateImmutableBinding ( N, S )

The CreateImmutableBinding concrete method of a Global Environment Record envRec takes arguments N (a String) and S (a Boolean) and returns either a normal completion containing unused or a throw completion. 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 is true, the new binding is marked as a strict binding. It performs the following steps when called:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. If ! DclRec.HasBinding(N) is true, throw a TypeError exception.
  3. Return ! DclRec.CreateImmutableBinding(N, S).

9.1.1.4.4 InitializeBinding ( N, V )

The InitializeBinding concrete method of a Global Environment Record envRec takes arguments N (a String) and V (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It is used to set the bound value of the current binding of the identifier whose name is N to the value V. An uninitialized binding for N must already exist. It performs the following steps when called:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. If ! DclRec.HasBinding(N) is true, then
    1. Return ! DclRec.InitializeBinding(N, V).
  3. Assert: If the binding exists, it must be in the Object Environment Record.
  4. Let ObjRec be envRec.[[ObjectRecord]].
  5. Return ? ObjRec.InitializeBinding(N, V).

9.1.1.4.5 SetMutableBinding ( N, V, S )

The SetMutableBinding concrete method of a Global Environment Record envRec takes arguments N (a String), V (an ECMAScript language value), and S (a Boolean) and returns either a normal completion containing unused or a throw completion. It attempts to change the bound value of the current binding of the identifier whose name is N to the value V. If the binding is an immutable binding and S is true, a TypeError is thrown. 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:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. If ! DclRec.HasBinding(N) is true, then
    1. Return ? DclRec.SetMutableBinding(N, V, S).
  3. Let ObjRec be envRec.[[ObjectRecord]].
  4. Return ? ObjRec.SetMutableBinding(N, V, S).

9.1.1.4.6 GetBindingValue ( N, S )

The GetBindingValue concrete method of a Global Environment Record envRec takes arguments N (a String) and S (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. It returns the value of its bound identifier whose name is 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:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. If ! DclRec.HasBinding(N) is true, then
    1. Return ? DclRec.GetBindingValue(N, S).
  3. Let ObjRec be envRec.[[ObjectRecord]].
  4. Return ? ObjRec.GetBindingValue(N, S).

9.1.1.4.7 DeleteBinding ( N )

The DeleteBinding concrete method of a Global Environment Record envRec takes argument N (a String) and returns either a normal completion containing a Boolean or a throw completion. It can only delete bindings that have been explicitly designated as being subject to deletion. It performs the following steps when called:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. If ! DclRec.HasBinding(N) is true, then
    1. Return ! DclRec.DeleteBinding(N).
  3. Let ObjRec be envRec.[[ObjectRecord]].
  4. Let globalObject be ObjRec.[[BindingObject]].
  5. Let existingProp be ? HasOwnProperty(globalObject, N).
  6. If existingProp is true, then
    1. Return ? ObjRec.DeleteBinding(N).
  7. Return true.

9.1.1.4.8 HasThisBinding ( )

The HasThisBinding concrete method of a Global Environment Record envRec takes no arguments and returns true. It performs the following steps when called:

  1. Return true.
Note

Global Environment Records always provide a this binding.

9.1.1.4.9 HasSuperBinding ( )

The HasSuperBinding concrete method of a Global Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. Return false.
Note

Global Environment Records do not provide a super binding.

9.1.1.4.10 WithBaseObject ( )

The WithBaseObject concrete method of a Global Environment Record envRec takes no arguments and returns undefined. It performs the following steps when called:

  1. Return undefined.

9.1.1.4.11 GetThisBinding ( )

The GetThisBinding concrete method of a Global Environment Record envRec takes no arguments and returns a normal completion containing an Object. It performs the following steps when called:

  1. Return envRec.[[GlobalThisValue]].

9.1.1.4.12 HasLexicalDeclaration ( envRec, N )

The abstract operation HasLexicalDeclaration takes arguments envRec (a Global Environment Record) and N (a String) and returns a Boolean. It determines if the argument identifier has a binding in envRec that was created using a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. It performs the following steps when called:

  1. Let DclRec be envRec.[[DeclarativeRecord]].
  2. Return ! DclRec.HasBinding(N).

9.1.1.4.13 HasRestrictedGlobalProperty ( envRec, N )

The abstract operation HasRestrictedGlobalProperty takes arguments envRec (a Global Environment Record) and N (a String) and returns either a normal completion containing a Boolean or a throw completion. 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:

  1. Let ObjRec be envRec.[[ObjectRecord]].
  2. Let globalObject be ObjRec.[[BindingObject]].
  3. Let existingProp be ? globalObject.[[GetOwnProperty]](N).
  4. If existingProp is undefined, return false.
  5. If existingProp.[[Configurable]] is true, return false.
  6. 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.

9.1.1.4.14 CanDeclareGlobalVar ( envRec, N )

The abstract operation CanDeclareGlobalVar takes arguments envRec (a Global Environment Record) and N (a String) and returns either a normal completion containing a Boolean or a throw completion. 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:

  1. Let ObjRec be envRec.[[ObjectRecord]].
  2. Let globalObject be ObjRec.[[BindingObject]].
  3. Let hasProperty be ? HasOwnProperty(globalObject, N).
  4. If hasProperty is true, return true.
  5. Return ? IsExtensible(globalObject).

9.1.1.4.15 CanDeclareGlobalFunction ( envRec, N )

The abstract operation CanDeclareGlobalFunction takes arguments envRec (a Global Environment Record) and N (a String) and returns either a normal completion containing a Boolean or a throw completion. It determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N. It performs the following steps when called:

  1. Let ObjRec be envRec.[[ObjectRecord]].
  2. Let globalObject be ObjRec.[[BindingObject]].
  3. Let existingProp be ? globalObject.[[GetOwnProperty]](N).
  4. If existingProp is undefined, return ? IsExtensible(globalObject).
  5. If existingProp.[[Configurable]] is true, return true.
  6. If IsDataDescriptor(existingProp) is true and existingProp has attribute values { [[Writable]]: true, [[Enumerable]]: true }, return true.
  7. Return false.

9.1.1.4.16 CreateGlobalVarBinding ( envRec, N, D )

The abstract operation CreateGlobalVarBinding takes arguments envRec (a Global Environment Record), N (a String), and D (a Boolean) and returns either a normal completion containing unused or a throw completion. It creates and initializes a mutable binding in the associated Object Environment Record. If a binding already exists, it is reused and assumed to be initialized. It performs the following steps when called:

  1. Let ObjRec be envRec.[[ObjectRecord]].
  2. Let globalObject be ObjRec.[[BindingObject]].
  3. Let hasProperty be ? HasOwnProperty(globalObject, N).
  4. Let extensible be ? IsExtensible(globalObject).
  5. If hasProperty is false and extensible is true, then
    1. Perform ? ObjRec.CreateMutableBinding(N, D).
    2. Perform ? ObjRec.InitializeBinding(N, undefined).
  6. Return unused.

9.1.1.4.17 CreateGlobalFunctionBinding ( envRec, N, V, D )

The abstract operation CreateGlobalFunctionBinding takes arguments envRec (a Global Environment Record), N (a String), V (an ECMAScript language value), and D (a Boolean) and returns either a normal completion containing unused or a throw completion. It creates and initializes a mutable binding in the associated Object Environment Record. If a binding already exists, it is replaced. It performs the following steps when called:

  1. Let ObjRec be envRec.[[ObjectRecord]].
  2. Let globalObject be ObjRec.[[BindingObject]].
  3. Let existingProp be ? globalObject.[[GetOwnProperty]](N).
  4. If existingProp is undefined or existingProp.[[Configurable]] is true, then
    1. Let desc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }.
  5. Else,
    1. Let desc be the PropertyDescriptor { [[Value]]: V }.
  6. Perform ? DefinePropertyOrThrow(globalObject, N, desc).
  7. Perform ? Set(globalObject, N, V, false).
  8. Return unused.
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.

9.1.1.5 Module Environment Records

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 14 and share the same specifications for all of those methods except for GetBindingValue, DeleteBinding, HasThisBinding and GetThisBinding. In addition, Module Environment Records support the methods listed in Table 20:

Table 20: Additional Methods of Module Environment Records
Method Purpose
GetThisBinding() Return the value of this Environment Record's this binding.

9.1.1.5.1 GetBindingValue ( N, S )

The GetBindingValue concrete method of a Module Environment Record envRec takes arguments N (a String) and S (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. It returns the value of its bound identifier whose name is 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:

  1. Assert: S is true.
  2. Assert: envRec has a binding for N.
  3. If the binding for N is an indirect binding, then
    1. Let M and N2 be the indirection values provided when this binding for N was created.
    2. Let targetEnv be M.[[Environment]].
    3. If targetEnv is empty, throw a ReferenceError exception.
    4. Return ? targetEnv.GetBindingValue(N2, true).
  4. If the binding for N in envRec is an uninitialized binding, throw a ReferenceError exception.
  5. Return the value currently bound to N in envRec.
Note

S will always be true because a Module is always strict mode code.

9.1.1.5.2 DeleteBinding ( N )

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.

9.1.1.5.3 HasThisBinding ( )

The HasThisBinding concrete method of a Module Environment Record envRec takes no arguments and returns true. It performs the following steps when called:

  1. Return true.
Note

Module Environment Records always provide a this binding.

9.1.1.5.4 GetThisBinding ( )

The GetThisBinding concrete method of a Module Environment Record envRec takes no arguments and returns a normal completion containing undefined. It performs the following steps when called:

  1. Return undefined.

9.1.1.5.5 CreateImportBinding ( envRec, N, M, N2 )

The abstract operation CreateImportBinding takes arguments envRec (a Module Environment Record), N (a String), M (a Module Record), and N2 (a String) and returns unused. It creates a new initialized immutable indirect binding for the name N. A binding must not already exist in envRec 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:

  1. Assert: envRec does not already have a binding for N.
  2. Assert: When M.[[Environment]] is instantiated, it will have a direct binding for N2.
  3. 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.
  4. Return unused.

9.1.2 Environment Record Operations

The following abstract operations are used in this specification to operate upon Environment Records:

9.1.2.1 GetIdentifierReference ( env, name, strict )

The abstract operation GetIdentifierReference takes arguments env (an Environment Record or null), name (a String), and strict (a Boolean) and returns either a normal completion containing a Reference Record or a throw completion. It performs the following steps when called:

  1. If env is null, then
    1. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  2. Let exists be ? env.HasBinding(name).
  3. If exists is true, then
    1. Return the Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  4. Else,
    1. Let outer be env.[[OuterEnv]].
    2. Return ? GetIdentifierReference(outer, name, strict).

9.1.2.2 NewDeclarativeEnvironment ( E )

The abstract operation NewDeclarativeEnvironment takes argument E (an Environment Record or null) and returns a Declarative Environment Record. It performs the following steps when called:

  1. Let env be a new Declarative Environment Record containing no bindings.
  2. Set env.[[OuterEnv]] to E.
  3. Return env.

9.1.2.3 NewObjectEnvironment ( O, W, E )

The abstract operation NewObjectEnvironment takes arguments O (an Object), W (a Boolean), and E (an Environment Record or null) and returns an Object Environment Record. It performs the following steps when called:

  1. Let env be a new Object Environment Record.
  2. Set env.[[BindingObject]] to O.
  3. Set env.[[IsWithEnvironment]] to W.
  4. Set env.[[OuterEnv]] to E.
  5. Return env.

9.1.2.4 NewFunctionEnvironment ( F, newTarget )

The abstract operation NewFunctionEnvironment takes arguments F (an ECMAScript function object) and newTarget (an Object or undefined) and returns a Function Environment Record. It performs the following steps when called:

  1. Let env be a new Function Environment Record containing no bindings.
  2. Set env.[[FunctionObject]] to F.
  3. If F.[[ThisMode]] is lexical, set env.[[ThisBindingStatus]] to lexical.
  4. Else, set env.[[ThisBindingStatus]] to uninitialized.
  5. Set env.[[NewTarget]] to newTarget.
  6. Set env.[[OuterEnv]] to F.[[Environment]].
  7. Return env.

9.1.2.5 NewGlobalEnvironment ( G, thisValue )

The abstract operation NewGlobalEnvironment takes arguments G (an Object) and thisValue (an Object) and returns a Global Environment Record. It performs the following steps when called:

  1. Let objRec be NewObjectEnvironment(G, false, null).
  2. Let dclRec be NewDeclarativeEnvironment(null).
  3. Let env be a new Global Environment Record.
  4. Set env.[[ObjectRecord]] to objRec.
  5. Set env.[[GlobalThisValue]] to thisValue.
  6. Set env.[[DeclarativeRecord]] to dclRec.
  7. Set env.[[OuterEnv]] to null.
  8. Return env.

9.1.2.6 NewModuleEnvironment ( E )

The abstract operation NewModuleEnvironment takes argument E (an Environment Record) and returns a Module Environment Record. It performs the following steps when called:

  1. Let env be a new Module Environment Record containing no bindings.
  2. Set env.[[OuterEnv]] to E.
  3. Return env.

9.2 PrivateEnvironment Records

A PrivateEnvironment Record is a specification mechanism used to track Private Names based upon the lexical nesting structure of ClassDeclarations and ClassExpressions in ECMAScript code. They are similar to, but distinct from, Environment Records. Each PrivateEnvironment Record is associated with a ClassDeclaration or ClassExpression. Each time such a class is evaluated, a new PrivateEnvironment Record is created to record the Private Names declared by that class.

Each PrivateEnvironment Record has the fields defined in Table 21.

Table 21: PrivateEnvironment Record Fields
Field Name Value Type Meaning
[[OuterPrivateEnvironment]] a PrivateEnvironment Record or null The PrivateEnvironment Record of the nearest containing class. null if the class with which this PrivateEnvironment Record is associated is not contained in any other class.
[[Names]] a List of Private Names The Private Names declared by this class.

9.2.1 PrivateEnvironment Record Operations

The following abstract operations are used in this specification to operate upon PrivateEnvironment Records:

9.2.1.1 NewPrivateEnvironment ( outerPrivateEnv )

The abstract operation NewPrivateEnvironment takes argument outerPrivateEnv (a PrivateEnvironment Record or null) and returns a PrivateEnvironment Record. It performs the following steps when called:

  1. Let names be a new empty List.
  2. Return the PrivateEnvironment Record { [[OuterPrivateEnvironment]]: outerPrivateEnv, [[Names]]: names }.

9.2.1.2 ResolvePrivateIdentifier ( privateEnv, identifier )

The abstract operation ResolvePrivateIdentifier takes arguments privateEnv (a PrivateEnvironment Record) and identifier (a String) and returns a Private Name. It performs the following steps when called:

  1. Let names be privateEnv.[[Names]].
  2. For each Private Name pn of names, do
    1. If pn.[[Description]] is identifier, then
      1. Return pn.
  3. Let outerPrivateEnv be privateEnv.[[OuterPrivateEnvironment]].
  4. Assert: outerPrivateEnv is not null.
  5. Return ResolvePrivateIdentifier(outerPrivateEnv, identifier).

9.3 Realms

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 22:

Table 22: Realm Record Fields
Field Name Value Meaning
[[AgentSignifier]] an agent signifier The agent that owns this realm
[[Intrinsics]] a Record whose field names are intrinsic keys and whose values are objects The intrinsic values used by code associated with this realm
[[GlobalObject]] an Object The global object for this realm
[[GlobalEnv]] a Global Environment Record The global environment for this realm
[[TemplateMap]] a List of Records with fields [[Site]] (a TemplateLiteral Parse Node) and [[Array]] (an Array)

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 1
Once a Parse Node becomes unreachable, the corresponding [[Array]] is also unreachable, and it would be unobservable if an implementation removed the pair from the [[TemplateMap]] list.
[[LoadedModules]] a List of LoadedModuleRequest Records

A map from the specifier strings imported by this realm to the resolved Module Record. The list does not contain two different Records r1 and r2 such that ModuleRequestsEqual(r1, r2) is true.

Note 2
As mentioned in HostLoadImportedModule (16.2.1.10 Note 1), [[LoadedModules]] in Realm Records is only used when running an import() expression in a context where there is no active script or module.
[[HostDefined]] anything (default value is undefined) Field reserved for use by hosts that need to associate additional information with a Realm Record.

9.3.1 InitializeHostDefinedRealm ( )

The abstract operation InitializeHostDefinedRealm takes no arguments and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Let realm be a new Realm Record.
  2. Perform CreateIntrinsics(realm).
  3. Set realm.[[AgentSignifier]] to AgentSignifier().
  4. Set realm.[[TemplateMap]] to a new empty List.
  5. Let newContext be a new execution context.
  6. Set the Function of newContext to null.
  7. Set the Realm of newContext to realm.
  8. Set the ScriptOrModule of newContext to null.
  9. Push newContext onto the execution context stack; newContext is now the running execution context.
  10. If the host requires use of an exotic object to serve as realm's global object, then
    1. Let global be such an object created in a host-defined manner.
  11. Else,
    1. Let global be OrdinaryObjectCreate(realm.[[Intrinsics]].[[%Object.prototype%]]).
  12. If the host requires that the this binding in realm's global scope return an object other than the global object, then
    1. Let thisValue be such an object created in a host-defined manner.
  13. Else,
    1. Let thisValue be global.
  14. Set realm.[[GlobalObject]] to global.
  15. Set realm.[[GlobalEnv]] to NewGlobalEnvironment(global, thisValue).
  16. Perform ? SetDefaultGlobalBindings(realm).
  17. Create any host-defined global object properties on global.
  18. Return unused.

9.3.2 CreateIntrinsics ( realmRec )

The abstract operation CreateIntrinsics takes argument realmRec (a Realm Record) and returns unused. It performs the following steps when called:

  1. Set realmRec.[[Intrinsics]] to a new Record.
  2. Set fields of realmRec.[[Intrinsics]] with the values listed in Table 6. The field names are the names listed in column one of the table. The value of each field is a new object value fully and recursively populated with property values as defined by the specification of each object in 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's "length" 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.
  3. Perform AddRestrictedFunctionProperties(realmRec.[[Intrinsics]].[[%Function.prototype%]], realmRec).
  4. Return unused.

9.3.3 SetDefaultGlobalBindings ( realmRec )

The abstract operation SetDefaultGlobalBindings takes argument realmRec (a Realm Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Let global be realmRec.[[GlobalObject]].
  2. For each property of the Global Object specified in clause 19, do
    1. Let name be the String value of the property name.
    2. 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.
    3. Perform ? DefinePropertyOrThrow(global, name, desc).
  3. Return unused.

9.4 Execution Contexts

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 23.

Table 23: State Components for All Execution Contexts
Component Purpose
code evaluation state Any state needed to perform, suspend, and resume evaluation of the code associated with 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.

ECMAScript code execution contexts have the additional state components listed in Table 24.

Table 24: 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.
PrivateEnvironment Identifies the PrivateEnvironment Record that holds Private Names created by ClassElements in the nearest containing class. null if there is no containing class.

The LexicalEnvironment and VariableEnvironment components of an execution context are always Environment Records.

Execution contexts representing the evaluation of Generators have the additional state components listed in Table 25.

Table 25: Additional State Components for Generator Execution Contexts
Component Purpose
Generator The Generator 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.

9.4.1 GetActiveScriptOrModule ( )

The abstract operation GetActiveScriptOrModule takes no arguments and returns a Script Record, a Module Record, or null. It is used to determine the running script or module, based on the running execution context. It performs the following steps when called:

  1. If the execution context stack is empty, return null.
  2. Let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is not null.
  3. If no such execution context exists, return null; otherwise return ec's ScriptOrModule.

9.4.2 ResolveBinding ( name [ , env ] )

The abstract operation ResolveBinding takes argument name (a String) and optional argument env (an Environment Record or undefined) and returns either a normal completion containing a Reference Record or a throw completion. 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:

  1. If env is not present or env is undefined, then
    1. Set env to the running execution context's LexicalEnvironment.
  2. Assert: env is an Environment Record.
  3. Let strict be IsStrict(the syntactic production that is being evaluated).
  4. Return ? GetIdentifierReference(env, name, strict).
Note

The result of ResolveBinding is always a Reference Record whose [[ReferencedName]] field is name.

9.4.3 GetThisEnvironment ( )

The abstract operation GetThisEnvironment takes no arguments and returns an Environment Record. It finds the Environment Record that currently supplies the binding of the keyword this. It performs the following steps when called:

  1. Let env be the running execution context's LexicalEnvironment.
  2. Repeat,
    1. Let exists be env.HasThisBinding().
    2. If exists is true, return env.
    3. Let outer be env.[[OuterEnv]].
    4. Assert: outer is not null.
    5. 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.

9.4.4 ResolveThisBinding ( )

The abstract operation ResolveThisBinding takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion. It determines the binding of the keyword this using the LexicalEnvironment of the running execution context. It performs the following steps when called:

  1. Let envRec be GetThisEnvironment().
  2. Return ? envRec.GetThisBinding().

9.4.5 GetNewTarget ( )

The abstract operation GetNewTarget takes no arguments and returns an Object or undefined. It determines the NewTarget value using the LexicalEnvironment of the