This is not the official ECMAScript Language Specification.
The most recent final ECMAScript standard is Edition 5.1, the PDF document located at http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf.
This is a draft of the next edition of the standard.
This page is based on the current working draft published at http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts. The program used to convert that Word doc to HTML is a custom-piled heap of hacks. It may have stripped out or garbled some of the formatting that makes the specification comprehensible. You can help improve the program here.
For copyright information, see Ecma International’s legal disclaimer in the document itself.
Report Errors and Issues at: https://bugs.ecmascript.org
Product: Draft for 6th Edition
Component: choose an appropriate one
Version: Rev 14, March 8, 2013 Draft
This Ecma Standard 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 this Standard 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 forthcoming internationalisation facilities and 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.
Since publication of the third edition, ECMAScript has 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. Although that work was not completed and not published as the fourth edition of ECMAScript, it informs continuing evolution of the language. The fifth edition of ECMAScript (published as ECMA-262 5th edition) codifies de facto interpretations of the language specification that have become common among browser implementations and adds support for new features that have 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 edition 5.1 of the ECMAScript Standard has been fully aligned with the third edition of the international standard ISO/IEC 16262:2011.
This present sixth edition of the Standard………
ECMAScript is a vibrant language and the evolution of the language is not complete. Significant technical enhancement will continue with future editions of this specification.
This Ecma Standard has been adopted by the General Assembly of <month> <year>.
"DISCLAIMER
This draft document may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published, and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this section are included on all such copies and derivative works. However, this document itself may not be modified in any way, including by removing the copyright notice or references to Ecma International, except as needed for the purpose of developing any document or deliverable produced by Ecma International.
This disclaimer is valid only prior to final version of this document. After approval all rights on the standard are reserved by Ecma International.
The limited permissions are granted through the standardization phase and will not be revoked by Ecma International or its successors or assigns during this time.
This document and the information contained herein is provided on an "AS IS" basis and ECMA INTERNATIONAL DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE."
This Standard defines the ECMAScript scripting language.
A conforming implementation of ECMAScript must provide and support all the types, values, objects, properties, functions, and program syntax and semantics described in this specification.
A conforming implementation of this Standard shall interpret characters in conformance with the Unicode Standard, Version 5.1.0 or later and ISO/IEC 10646. If the adopted ISO/IEC 10646-1 subset is not otherwise specified, it is presumed to be the Unicode set, collection 10646.
A conforming implementation of ECMAScript is permitted to provide additional types, values, objects, properties, and functions beyond those described in this specification. In particular, a conforming implementation of ECMAScript is permitted to 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 is permitted to support program and regular expression syntax not described in this specification. In particular, a conforming implementation of ECMAScript is permitted to support program syntax that makes use of the “future reserved words” listed in 7.6.1.2 of this specification.
The following referenced documents are indispensable for the application of this document. For dated references, only the edition cited applies. For undated references, the latest edition of the referenced document (including any amendments) applies.
ISO/IEC 9899:1996, Programming Languages – C, including amendment 1 and technical corrigenda 1 and 2
ISO/IEC 10646:2003: Information Technology – Universal Multiple-Octet Coded Character Set (UCS) plus Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, and Amendment 4:2008, plus additional amendments and corrigenda, or successor
The Unicode Standard, Version 5.0, as amended by Unicode 5.1.0, or successor
Unicode Standard Annex #15, Unicode Normalization Forms, version Unicode 5.1.0, or successor
Unicode Standard Annex #31, Unicode Identifiers and Pattern Syntax, version Unicode 5.1.0, or successor.
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.
A scripting language is a programming language that is used to manipulate, customise, 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 used as a scripting language, but has become widely used as a general purpose programming language.
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 both as a general propose programming language and 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.
Some of the facilities of ECMAScript are similar to those used in other programming languages; in particular Java™, Self, and Scheme as described in:
Gosling, James, Bill Joy and Guy Steele. The Java™ Language Specification. Addison Wesley Publishing Co., 1996.
Ungar, David, and Smith, Randall B. Self: The Power of Simplicity. OOPSLA '87 Conference Proceedings, pp. 227–241, Orlando, FL, October 1987.
IEEE Standard for the Scheme Programming Language. IEEE Std 1178-1990.
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 customised 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.
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. An ECMAScript object is a collection of properties each with zero or more 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 change the value of 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, and String; an object is a member of the remaining built-in type Object; and a function is a callable object. A function that is associated with an object via a property is 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, the Object object, the Function object, the Array object, the String object, the Boolean object, the Number object, the Math object, the Date object, the RegExp object, the JSON object, and the Error objects Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError and URIError.
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.
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.
ECMAScript does not use classes 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
initialises 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.
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 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.
The ECMAScript Language recognises 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 code units. Because strict mode is selected at the level of a syntactic code unit, strict mode only imposes restrictions that have local effect within such a code unit. Strict mode does not restrict or modify any aspect of the ECMAScript semantics that must operate consistently across multiple code units. A complete ECMAScript program may be composed for both strict mode and non-strict mode ECMAScript code units. In this case, strict mode only applies when actually executing code that is defined within a strict mode code unit.
In order to conform to this specification, an ECMAScript implementation must implement both the full unrestricted ECMAScript language and the strict mode variant of the ECMAScript language as defined by this specification. In addition, an implementation must support the combination of unrestricted and strict mode code units into a single composite program.
For the purposes of this document, the following terms and definitions apply.
set of data values as defined in Clause 8 of this specification
member of one of the types Undefined, Null, Boolean, Number, or String as defined in Clause 8
NOTE A primitive value is a datum that is represented directly at the lowest level of the language implementation.
member of the type Object
NOTE An object is a collection of properties and has a single prototype object. The prototype may be the null value.
function object that creates and initialises objects
NOTE The value of a constructor’s “prototype” property is a prototype object that is used to implement inheritance and shared properties.
object that provides shared properties for other objects
NOTE When a constructor creates an object, that object implicitly references the
constructor’s “prototype” property for the purpose of resolving property references. The
constructor’s “prototype” property can be referenced by the program expression constructor.prototype, and properties added to an object’s
prototype are shared, through inheritance, by all objects sharing the prototype. Alternatively, a new object may be
created with an explicitly specified prototype by using the Object.create built-in function.
object that has the default behaviour for the internal methods that must be supported by all ECMAScript objects.
object that has some alternative behaviour for one or more of the internal methods that must be supported by all ECMAScript objects.
NOTE Any object that is not an ordinary object is an exotic object.
object whose semantics are defined by this specification.
object supplied by an ECMAScript implementation, independent of the host environment, that is present at the start of the execution of an ECMAScript program
NOTE Standard built-in objects are defined in this specification, and an ECMAScript implementation may specify and define others. A built-in constructor is a built-in object that is also a constructor.
primitive value used when a variable has not been assigned a value
type whose sole value is the undefined value
primitive value that represents the intentional absence of any object value
type whose sole value is the null value
member of the Boolean type
NOTE There are only two Boolean values, true and false.
type consisting of the primitive values true and false
member of the Object type that is an instance of the standard built-in Boolean constructor
NOTE A Boolean object is created by using the Boolean constructor in a
new expression, supplying a Boolean value as an argument. The resulting object has an internal data property
whose value is the Boolean value. A Boolean object can be coerced to a Boolean value.
primitive value that is a finite ordered sequence of zero or more 16-bit unsigned integer
NOTE A String value is a member of the String type. Each integer value in the sequence usually represents a single 16-bit unit of UTF-16 text. However, ECMAScript does not place any restrictions or requirements on the values except that they must be 16-bit unsigned integers.
set of all possible String values
member of the Object type that is an instance of the standard built-in String constructor
NOTE A String object is created by using the String constructor in a
new expression, supplying a String value as an argument. The resulting object has an internal data property
whose value is the String value. A String object can be coerced to a String value by calling the String
constructor as a function (15.5.1).
primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value
NOTE A Number value is a member of the Number type and is a direct representation of a number.
set of all possible Number values including the special “Not-a-Number” (NaN) value, positive infinity, and negative infinity
member of the Object type that is an instance of the standard built-in Number constructor
NOTE A Number object is created by using the Number constructor in a
new expression, supplying a Number value as an argument. The resulting object has an internal data property
whose value is the Number value. A Number object can be coerced to a Number value by calling the Number
constructor as a function (15.7.1).
number value that is the positive infinite Number value
number value that is a IEEE 754 “Not-a-Number” value
member of the Object type that may be invoked as a subroutine
NOTE In addition to its properties, a function contains executable code and state that determine how it behaves when invoked. A function’s code may or may not be written in ECMAScript.
built-in object that is a function
NOTE Examples of built-in functions include parseInt and Math.exp. An
implementation may provide implementation-dependent built-in functions that are not described in this specification.
association between a name and a value that is a part of an object
NOTE Depending upon the form of the property the value may be represented either directly as a data value (a primitive value, an object, or a function object) or indirectly by a pair of accessor functions.
function that is the value of a property
NOTE When a function is called as a method of an object, the object is passed to the function as its this value.
method that is a built-in function
NOTE Standard built-in methods are defined in this specification, and an ECMAScript implementation may specify and provide other additional built-in methods.
internal value that defines some characteristic of a property
property that is directly contained by its object
property of an object that is not an own property but is a property (either own or inherited) of the object’s prototype
A context-free grammar consists of a number of productions. Each production has an abstract symbol called a nonterminal as its left-hand side, and a sequence of zero or more nonterminal and terminal symbols as its right-hand side. For each grammar, the terminal symbols are drawn from a specified alphabet.
A chain production is a production that has exactly one nonterminal symbol on its right-hand side along with zero or more terminal symbols.
Starting from a sentence consisting of a single distinguished nonterminal, called the goal symbol, a given context-free grammar specifies a language, namely, the (perhaps infinite) set of possible sequences of terminal symbols that can result from repeatedly replacing any nonterminal in the sequence with a right-hand side of a production for which the nonterminal is the left-hand side.
A lexical grammar for ECMAScript is given in clause 7. This grammar has as its terminal symbols characters (Unicode code units) that conform to the rules for SourceCharacter defined in Clause 6. It defines a set of productions, starting from the goal symbol InputElementDiv or InputElementRegExp, that describe how sequences of such characters 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 (7.9). Simple white space and single-line comments are discarded and do not appear in the stream of input elements for the syntactic grammar. A MultiLineComment (that is, a comment of the form “/*…*/” regardless of whether it spans more than one line) is likewise simply discarded if it contains no line terminator; but if a MultiLineComment contains one or more line terminators, then it is replaced by a single line terminator, which becomes part of the stream of input elements for the syntactic grammar.
A RegExp grammar for ECMAScript is given in 15.10. This grammar also has as its terminal symbols the characters as defined by SourceCharacter. It defines a set of productions, starting from the goal symbol Pattern, that describe how sequences of characters are translated into regular expression patterns.
Productions of the lexical and RegExp grammars are distinguished by having two colons “::” as separating punctuation. The lexical and RegExp grammars share some productions.
Another grammar is used for translating Strings into numeric values. This grammar is similar to the part of the lexical grammar having to do with numeric literals and has as its terminal symbols SourceCharacter. This grammar appears in 9.3.1.
Productions of the numeric string grammar are distinguished by having three colons “:::” as punctuation.
The syntactic grammar for ECMAScript is given in clauses 11, 12, 13 and 14. 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 the goal symbol Script, that describe how sequences of tokens can form syntactically correct independent components of an ECMAScript programs.
When a stream of characters is to be parsed as an ECMAScript script, 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 script 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, with no tokens left over.
Productions of the syntactic grammar are distinguished by having just one colon “:” as punctuation.
The syntactic grammar as presented in clauses 11, 12, 13 and 14 is actually not a complete account of which token sequences are accepted as correct ECMAScript scripts. 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 terminator character appears in certain “awkward” places.
In certain cases in order to avoid ambiguities the syntactic grammar uses generalize productions that permit token sequences that are not valid ECMAScript scripts. For example, this technique is used in with object literals and object destructuring patterns. In such cases a more restrictive supplemental grammar is provided that further restricts the acceptable token sequences. In certain contexts, when explicitly specific, the input elements corresponding to such a production are parsed again using a goal symbol of a supplemental grammar. The script is syntactically in error if the tokens in the stream of input elements cannot be parsed as a single instance of the supplemental goal symbol, with no tokens left over.
The JSON grammar is used to translate a String describing a set of ECMAScript objects into actual objects. The JSON grammar is given in 15.12.1.
The JSON grammar consists of the JSON lexical grammar and the JSON syntactic grammar. The JSON lexical grammar is used to translate character sequences into tokens and is similar to parts of the ECMAScript lexical grammar. The JSON syntactic grammar describes how sequences of tokens from the JSON lexical grammar can form syntactically correct JSON object descriptions.
Productions of the JSON lexical grammar are distinguished by having two colons “::” as separating punctuation. The JSON lexical grammar uses some productions from the ECMAScript lexical grammar. The JSON syntactic grammar is similar to parts of the ECMAScript syntactic grammar. Productions of the JSON syntactic grammar are distinguished by using one colon “:” as separating punctuation.
Terminal symbols of the lexical, RegExp, and numeric string grammars, and some of the terminal symbols of the other
grammars, are shown in fixed width font, both in the productions of the grammars and throughout this
specification whenever the text directly refers to such a terminal symbol. These are to appear in a script either exactly as
written or using equalvant Unicode escape sequences (see clause 6). All terminal symbol characters
specified in this way are to be understood as the appropriate Unicode character from the ASCII range, as opposed to any
similar-looking characters from other Unicode ranges.
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:
while ( Expression ) Statementstates 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:
, AssignmentExpressionstates that an ArgumentList may represent either a single AssignmentExpression or an ArgumentList, followed by a comma, followed by an AssignmentExpression. This definition of ArgumentList is recursive, that is, it is defined in terms of itself. The result is that an ArgumentList may contain any positive number of arguments, separated by commas, where each argument expression is an AssignmentExpression. Such recursive definitions of nonterminals are common.
The subscripted suffix “opt”, which may appear after a terminal or nonterminal, indicates an optional symbol. The alternative containing the optional symbol actually specifies two right-hand sides, one that omits the optional element and one that includes it. This means that:
is a convenient abbreviation for:
and that:
for ( ExpressionNoInopt ; Expressionopt ; Expressionopt ) Statementis a convenient abbreviation for:
for ( ; Expressionopt ; Expressionopt ) Statementfor ( ExpressionNoIn ; Expressionopt ; Expressionopt ) Statementwhich in turn is an abbreviation for:
for ( ; ; Expressionopt ) Statementfor ( ; Expression ; Expressionopt ) Statementfor ( ExpressionNoIn ; ; Expressionopt ) Statementfor ( ExpressionNoIn ; Expression ; Expressionopt ) Statementwhich in turn is an abbreviation for:
for ( ; ; ) Statementfor ( ; ; Expression ) Statementfor ( ; Expression ; ) Statementfor ( ; Expression ; Expression ) Statementfor ( ExpressionNoIn ; ; ) Statementfor ( ExpressionNoIn ; ; Expression ) Statementfor ( ExpressionNoIn ; Expression ; ) Statementfor ( ExpressionNoIn ; Expression ; Expression ) Statementso the nonterminal IterationStatement actually has eight alternative right-hand sides.
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:
1 2 3 4 5 6 7 8 9which is merely a convenient abbreviation for:
123456789If the phrase “[empty]” appears as the right-hand side of a production, it indicates that the production's right-hand side contains no terminals or nonterminals.
If the phrase “[lookahead ∉ set]” appears in the right-hand side of a production, it indicates that the production may not be used if the immediately following input token is a member of the given set. The set can be written as a list of terminals enclosed in curly braces. For convenience, the set can also be written as a nonterminal, in which case it represents the set of all terminals to which that nonterminal could expand. For example, given the definitions
0 1 2 3 4 5 6 7 8 9the definition
n [lookahead ∉ {1, 3, 5, 7, 9}] DecimalDigitsmatches 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.
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:
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.
The lexical grammar has multiple goal symbols and the appropriate goal symbol to use depends upon the syntactic grammar context. If a phrase of the form “[Lexical goal LexicalGoalSymbol]” appears on the right-hand-side of a syntactic production then the next token must be lexically recognized using the indicated goal symbol. In the absence of such a phrase the default lexical goal symbol is used.
When an alternative in a production of the lexical grammar or the numeric string grammar appears to be a multi-character token, it represents the sequence of characters that would make up such a token.
The right-hand side of a production may specify that certain expansions are not permitted by using the phrase “but not” and then indicating the expansions to be excluded. For example, the production:
means that the nonterminal Identifier may be replaced by any sequence of characters that could replace IdentifierName provided that the same sequence of characters could not replace ReservedWord.
Finally, a few nonterminal symbols are described by a descriptive phrase in sans-serif type in cases where it would be impractical to list all the alternatives:
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 parameterised, in which case the names and usage of the parameters must be provided as part of the algorithm’s definition. In order to facilitate their use in multiple parts of this specification, some algorithms, called abstract operations, are named and written in parameterised functional form so that they may be referenced by name from within other algorithms.
Algorithms may be associated with productions of 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 non-terminal symbols of the production alternative as if they were parameters of the algorithm. When used in this manner, non-terminal symbols refer to the actual alternative definition that is matched when parsing the script souce code.
Unless explicitly specified otherwise, all chain productions have an implicit associated definition for every algorithm that is might be applied to that production’s left-hand side nonterminal. The implicit simply reapplies the same algorithm name with the same parameters, if any, to the chain production’s sole right-hand side nonterminal and then result. For example, assume there is a production
{ StatementList }but there is no evalution algorithm that is explicitly specified for that production. If in some algorithm there is a statement of the form: “Return the result of evaluating Block” it is implicit that the algorithm has an evalution algorithm of the form:
Runtime Semantics: Evaluation
}For clarity of expression, algorithm steps may be subdivided into sequential substeps. Substeps are indented and may themselves be further divided into indented substeps. Outline numbering conventions are used to identify substeps with the first level of substeps labelled with lower case alphabetic characters and the second level of substeps labelled with lower case roman numerals. If more than three levels are required these rules repeat with the fourth level using numeric labels. For example:
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 may assert 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.
Mathematical operations such as addition, subtraction, negation, multiplication, division, and the mathematical functions defined later in this clause should always be understood as computing exact mathematical results on mathematical real numbers, which do not include infinities and do not include a negative zero that is distinguished from positive zero. Algorithms in this standard that model floating-point arithmetic include explicit steps, where necessary, to handle infinities and signed zero and to perform rounding. If a mathematical operation or function is applied to a floating-point number, it should be understood as being applied to the exact mathematical value represented by that floating-point number; such a floating-point number must be finite, and if it is +0 or −0 then the corresponding mathematical value is simply 0.
The mathematical function abs(x) yields the absolute value of x, which is −x if x is negative (less than zero) and otherwise is x itself.
The mathematical function sign(x) yields 1 if x is positive and −1 if x is negative. The sign function is not used in this standard for cases when x is zero.
The mathematical function min(x1, x2, ..., xn) yields the mathematically smallest of x1 through xn.
The notation “x modulo y” (y must be finite and nonzero) 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 mathematical function floor(x) yields the largest integer (closest to positive infinity) that is not larger than x.
NOTE floor(x) = x−(x modulo 1).
If an algorithm is defined to “throw an exception”, execution of the algorithm is terminated and no result is returned. The calling algorithms are also terminated, until an algorithm step is reached that explicitly deals with the exception, using terminology such as “If an exception was thrown…”. Once such an algorithm step has been encountered the exception is no longer considered to have occurred.
Context-free grammars are not sufficiently powerful to express all the rules that define whether a stream of input elements make up a valid ECMAScript script 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.
Unless otherwise specified every grammar production alternative in this specification implicitly has a definition for a static semantic rule named Contains which takes an argument named symbol whose value is a terminal or non-terminal of the grammar that includes the associated production. The default definition of Contains is:
The above definition is explicitly over-ridden for specific productions.
A special kind of static semantic rule is an Early Error Rule. Early error rules define early error conditions (see clause 16) that are associate with specific grammar productions. Evaluation of most early error rules are not explicitly invoked within the algorithms of this specification. A comforming implementation must, prior to the first evaluation of a Script, validate all of the early error rules of the productions used to parse that Script. If any of the early error rules are violated the Script is invalid and can not be evaluated.
The ECMAScript code is expressed using Unicode, version 5.1 or later. ECMAScript source text is a sequence of Unicode characters. The phrase “Unicode character” refers to the abstract linguistic or typographical unit represented by a single Unicode scalar value. The actual encodings used to store and interchange ECMAScript source text is not relevant to this specification. Any well-defined encoding such as UTF-32 or UTF-16 may be used. Source text might even be externally represented using a non-Unicode character encoding. Regardless of the external source text encoding, a conforming ECMAScript implementation processes the source text as if it was an equivalent sequence of SourceCharacter values. Each SourceCharacter being an abstract Unicode character with a corresponding Unicode scalar value. Conforming ECMAScript implementations are not required to perform any normalisation of text, or behave as though they were performing normalisation of text.
The phrase “code point” refers to such a Unicode scalar value. “Unicode character” only refers to entities represented by single Unicode scalar values: the components of a combining character sequence are still individual “Unicode characters,” even though a user might think of the whole sequence as a single character.
In string literals, regular expression literals,template literals and identifiers, any Unicode characters may also be expressed as a Unicode escape sequence that explicitly express a code point’s numeric value. Within a comment, such an escape sequence is effectively ignored as part of the comment. Within other contexts, such an escape sequence contextually contributes one Unicode character.
NOTE
ECMAScript differs from the Java programming language in the behaviour of Unicode escape sequences. In a Java
program, if the Unicode escape sequence \u000A, for example, occurs within a single-line comment, it is interpreted
as a line terminator (Unicode character 000A is line feed) and therefore the next Unicode character is not part of
the comment. Similarly, if the Unicode escape sequence \u000A occurs within a string literal in a Java program, it
is likewise interpreted as a line terminator, which is not allowed within a string literal—one must write \n
instead of \u000A to cause a line feed to be part of the string value of a string literal. In an ECMAScript
program, a Unicode escape sequence occurring within a comment is never interpreted and therefore cannot contribute to
termination of the comment. Similarly, a Unicode escape sequence occurring within a string literal in an ECMAScript program
always contributes a Unicode character to the literal and is never interpreted as a line terminator or as a quote mark that
might terminate the string literal.
ECMAScript String values (8.4) are computational sequences of 16-bit integer values called “code units”. ECMAScript language constructs that generate string values from SourceCharacter sequences use UTF-16 encoding to generate the code unit values.
Static Semantics: UTF-16 Encoding
The UTF-16 Encoding of a numeric code point value, cp, is determined as follows:
The source text of an ECMAScript script is first converted into a sequence of input elements, which are tokens, line terminators, comments, or white space. The source text is scanned from left to right, repeatedly taking the longest possible sequence of characters as the next input element.
There are several situations where the identification of lexical input elements is sensitive to the syntactic grammar context
that is consuming the input elements. This requires multiple goal symbols for the lexical grammar. The InputElementDiv goal symbol is the default goal symbol and is used in those syntactic grammar contexts where a
leading division (/) or division-assignment (/=) operator is permitted. The InputElementRegExp goal symbol is used in all syntactic grammar contexts where a RegularExpressionLiteral is permitted. The InputElementTemplateTail goal is used in
syntactic grammar contexts where a TemplateLiteral logically continues after a substitution element.
NOTE There are no syntactic grammar contexts where both a leading division or division-assignment, and a leading RegularExpressionLiteral are permitted. This is not affected by semicolon insertion (see 7.9); in examples such as the following:
a = b
/hi/g.exec(c).map(d);
where the first non-whitespace, non-comment character after a LineTerminator is slash
(/) and the syntactic context allows division or division-assignment, no semicolon is inserted at the LineTerminator. That is, the above example is interpreted in the same way as:
a = b / hi / g.exec(c).map(d);
The Unicode format-control characters (i.e., the characters in category “Cf” in the Unicode Character Database such as left-to-right mark or right-to-left mark) are control codes used to control the formatting of a range of text in the absence of higher-level protocols for this (such as mark-up languages).
It is useful to allow format-control characters in source text to facilitate editing and display. All format control characters may be used within comments, and within string literals, template literals, and regular expression literals.
<ZWNJ> and <ZWJ> are format-control characters that are used to make necessary distinctions when forming words or phrases in certain languages. In ECMAScript source text, <ZWNJ> and <ZWJ> may also be used in an identifier after the first character.
<BOM> is a format-control character used primarily at the start of a text to mark it as Unicode and to allow detection of the text's encoding and byte order. <BOM> characters intended for this purpose can sometimes also appear after the start of a text, for example as a result of concatenating files. <BOM> characters are treated as white space characters (see 7.2).
The special treatment of certain format-control characters outside of comments, string literals, and regular expression literals is summarised in Table 1.
| Code Point | Name | Formal Name | Usage |
|---|---|---|---|
U+200C |
Zero width non-joiner | <ZWNJ> | IdentifierPart |
U+200D |
Zero width joiner | <ZWJ> | IdentifierPart |
U+FEFF |
Byte Order Mark | <BOM> | Whitespace |
White space characters are used to improve source text readability and to separate tokens (indivisible lexical units) from each other, but are otherwise insignificant. White space characters may occur between any two tokens and at the start or end of input. White space characters may occur within a StringLiteral, a RegularExpressionLiteral, a Template, or a TemplateSubstitutionTail where they are considered significant characters forming part of a literal value. They may also occur within a Comment, but cannot appear within any other kind of token.
The ECMAScript white space characters are listed in Table 2.
| Code Point | Name | Formal Name |
|---|---|---|
U+0009 |
Tab | <TAB> |
U+000B |
Vertical Tab | <VT> |
U+000C |
Form Feed | <FF> |
U+0020 |
Space | <SP> |
U+00A0 |
No-break space | <NBSP> |
U+FEFF |
Byte Order Mark | <BOM> |
| Other category “Zs” | Any other Unicode “space separator” | <USP> |
ECMAScript implementations must recognise all of the white space characters defined in Unicode 5.1. Later editions of the Unicode Standard may define other white space characters. ECMAScript implementations may recognise white space characters from later editions of the Unicode Standard.
Like white space characters, line terminator characters are used to improve source text readability and to separate tokens (indivisible lexical units) from each other. However, unlike white space characters, line terminators have some influence over the behaviour of the syntactic grammar. In general, line terminators may occur between any two tokens, but there are a few places where they are forbidden by the syntactic grammar. Line terminators also affect the process of automatic semicolon insertion (7.9). A line terminator cannot occur within any token except a StringLiteral, Template, or TemplateSubstitutionTail. Line terminators may only occur within a StringLiteral token as part of a LineContinuation.
A line terminator can occur within a MultiLineComment (7.4) but cannot occur within a SingleLineComment.
Line terminators are included in the set of white space characters that are matched by the \s class in regular
expressions.
The ECMAScript line terminator characters are listed in Table 3.
| Code Point | Name | Formal Name |
|---|---|---|
U+000A |
Line Feed | <LF> |
U+000D |
Carriage Return | <CR> |
U+2028 |
Line separator | <LS> |
U+2029 |
Paragraph separator | <PS> |
Only the Unicode characters in Table 3 are treated as line terminators. Other new line or line breaking Unicode characters are treated as white space but not as line terminators. The sequence <CR><LF> is commonly used as a line terminator. It should be considered a single SourceCharacter for the purpose of reporting line numbers.
Comments can be either single or multi-line. Multi-line comments cannot nest.
Because a single-line comment can contain any Unicode character except a LineTerminator character,
and because of the general rule that a token is always as long as possible, a single-line comment always consists of all
characters from the // marker to the end of the line. However, the LineTerminator at the
end of the line is not considered to be part of the single-line comment; it is recognised separately by the lexical grammar
and becomes part of the stream of input elements for the syntactic grammar. This point is very important, because it implies
that the presence or absence of single-line comments does not affect the process of automatic semicolon
insertion (see 7.9).
Comments behave like white space and are discarded except that, if a MultiLineComment contains a line terminator character, then the entire comment is considered to be a LineTerminator for purposes of parsing by the syntactic grammar.
/* MultiLineCommentCharsopt */* PostAsteriskCommentCharsopt* PostAsteriskCommentCharsopt*/ or *// SingleLineCommentCharsoptNOTE The DivPunctuator, RegularExpressionLiteral, RightBracePunctuator, and TemplateSubstitutionTail productions define tokens, but are not included in the Token production.
IdentifierName, Identifier, and ReservedWord are tokens that are interpreted according to the Default Identifier Syntax given in Unicode Standard Annex #31, Identifier and Pattern Syntax, with some small modifications. ReservedWord is is an enumerated subset of IdentifierName and Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on character properties specified by the Unicode Standard. The Unicode characters in the specified categories in version 5.1.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations. ECMAScript implementations may recognise identifier characters defined in later editions of the Unicode Standard.
NOTE 1 This standard specifies specific character additions: The dollar sign
(U+0024) and the underscore (U+005f) are permitted anywhere in an IdentifierName, and the characters zero width non-joiner (U+200C) and zero width joiner (U+200D) are
permitted anywhere after the first character of an IdentifierName.
Unicode escape sequences are permitted in an IdentifierName, where they contribute a single Unicode
character to the IdentifierName. The code point of the contributed character is expressed by the HexDigits of the UnicodeEscapeSequence (see 7.8.4). The
\ preceding the UnicodeEscapeSequence and the u and { }
characters, if they appear, do not contribute characters to the IdentifierName. A UnicodeEscapeSequence cannot be used to put a character into an IdentifierName that
would otherwise be illegal. In other words, if a \ UnicodeEscapeSequence sequence were
replaced by the Unicode character it constributes, the result must still be a valid IdentifierName
that has the exact same sequence of characters as the original IdentifierName. All interpretations of
IdentifierName within this specification are based upon their actual characters regardless of whether
or not an escape sequence was used to contribute any particular characters.
Two IdentifierName that are canonically equivalent according to the Unicode standard are not equal unless they are represented by the exact same sequence of code units (in other words, conforming ECMAScript implementations are only required to do bitwise comparison on IdentifierName values).
NOTE 2 If maximal portability is a concern, programmers should only employ the identifier characters that were defined in Unicode 3.0.
$_\ UnicodeEscapeSequence$_\ UnicodeEscapeSequenceThe definitions of the nonterminal UnicodeEscapeSequence is given in 7.8.4
Static Semantics: StringValue
Identifier :: IdentifierName but not ReservedWord
\ UnicodeEscapeSequence are first replaced with the code point
represented by the UnicodeEscapeSequence and then the code points of the entire IdentifierName are
converted to code units by UTF-16 Encoding (clause 6) each code point.A reserved word is an IdentifierName that cannot be used as an Identifier.
The ReservedWord definitions are specified as literal sequences of Unicode characters. However,
any Unicode character in a ReservedWord can also be expressed by a \ UnicodeEscapeSequence that expresses that same Unicode character’s code point. Use of such escape
sequences does not change the meaning of the ReservedWord.
The following tokens are ECMAScript keywords and may not be used as Identifiers in ECMAScript programs.
| break | delete | import | this |
| case | do | in | throw |
| catch | else | instanceof | try |
| class | export | let | typeof |
| continue | finally | new | var |
| const | for | return | void |
| debugger | function | super | while |
| default | if | switch | with |
The following words are used as keywords in proposed extensions and are therefore reserved to allow for the possibility of future adoption of those extensions.
| enum | extends | ||
The following tokens are also considered to be FutureReservedWords when they occur within strict mode code (see 10.1.1). The occurrence of any of these tokens within strict mode code in any context where the occurrence of a FutureReservedWord would produce an error must also produce an equivalent error:
| implements | private | public | yield | |
| interface | package | protected | static |
| { | ( | ) | [ | ] | . |
| ... | ; | , | < | > | <= |
| >= | == | != | === | !== | |
| + | - | * | % | ++ | -- |
| << | >> | >>> | & | | | ^ |
| ! | ~ | && | || | ? | : |
| = | += | -= | *= | %= | <<= |
| >>= | >>>= | &= | |= | ^= | => |
| / | /= |
| } |
nulltruefalse. DecimalDigitsopt ExponentPartopt. DecimalDigits ExponentPartopt00 1 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 9e E+ DecimalDigits- DecimalDigits0b BinaryDigit0B BinaryDigit0 10o OctalDigit0O OctalDigit0 1 2 3 4 5 6 70x HexDigits0X HexDigits0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E FThe SourceCharacter immediately following a NumericLiteral must not be an IdentifierStart or DecimalDigit.
NOTE For example:
3in
is an error and not the two input elements 3 and in.
A conforming implementation, when processing strict mode code (see 10.1.1), must not extend the syntax of NumericLiteral to include OctalIntegerLiteral as described in B.1.1.
A numeric literal stands for a value of the Number type. This value is determined in two steps: first, a mathematical value (MV) is derived from the literal; second, this mathematical value is rounded as described below.
The MV of NumericLiteral :: DecimalLiteral is the MV of DecimalLiteral.
The MV of NumericLiteral :: BinaryIntegerLiteral is the MV of BinaryIntegerLiteral.
The MV of NumericLiteral :: OctalIntegerLiteral is the MV of OctalIntegerLiteral.
The MV of NumericLiteral :: HexIntegerLiteral is the MV of HexIntegerLiteral.
The MV of DecimalLiteral :: DecimalIntegerLiteral . is the MV of DecimalIntegerLiteral.
The MV of DecimalLiteral :: DecimalIntegerLiteral . DecimalDigits is the MV
of DecimalIntegerLiteral plus (the MV of DecimalDigits times 10–n), where n
is the number of characters in DecimalDigits.
The MV of DecimalLiteral :: DecimalIntegerLiteral . ExponentPart is the MV
of DecimalIntegerLiteral times 10e, where e is the MV of ExponentPart.
The MV of DecimalLiteral :: DecimalIntegerLiteral . DecimalDigits ExponentPart is (the MV of DecimalIntegerLiteral plus (the MV of DecimalDigits
times 10–n)) times 10e, where n is the number of characters in
DecimalDigits and e is the MV of ExponentPart.
The MV of DecimalLiteral :: . DecimalDigits is the MV of DecimalDigits times
10–n, where n is the number of characters in DecimalDigits.
The MV of DecimalLiteral :: . DecimalDigits ExponentPart is the MV of
DecimalDigits times 10e–n, where n is the number of characters in
DecimalDigits and e is the MV of ExponentPart.
The MV of DecimalLiteral :: DecimalIntegerLiteral is the MV of DecimalIntegerLiteral.
The MV of DecimalLiteral :: DecimalIntegerLiteral ExponentPart is the MV of DecimalIntegerLiteral times 10e, where e is the MV of ExponentPart.
The MV of DecimalIntegerLiteral :: 0 is 0.
The MV of DecimalIntegerLiteral :: NonZeroDigit is the MV of NonZeroDigit.
The MV of DecimalIntegerLiteral :: NonZeroDigit DecimalDigits is (the MV of NonZeroDigit times 10n) plus the MV of DecimalDigits, where n is the number of characters in DecimalDigits.
The MV of DecimalDigits :: DecimalDigit is the MV of DecimalDigit.
The MV of DecimalDigits :: DecimalDigits DecimalDigit is (the MV of DecimalDigits times 10) plus the MV of DecimalDigit.
The MV of ExponentPart :: ExponentIndicator SignedInteger is the MV of SignedInteger.
The MV of SignedInteger :: DecimalDigits is the MV of DecimalDigits.
The MV of SignedInteger :: + DecimalDigits is the MV of DecimalDigits.
The MV of SignedInteger :: - DecimalDigits is the negative of the MV of DecimalDigits.
The MV of DecimalDigit :: 0 or of HexDigit :: 0 or of OctalDigit :: 0 or of BinaryDigit :: 0 is 0.
The MV of DecimalDigit :: 1 or of NonZeroDigit ::
1 or of HexDigit ::
1 or of OctalDigit ::
1 or
of BinaryDigit :: 1 is 1.
The MV of DecimalDigit :: 2 or of NonZeroDigit ::
2 or of HexDigit ::
2 or of OctalDigit ::
2 is 2.
The MV of DecimalDigit :: 3 or of NonZeroDigit ::
3 or of HexDigit ::
3 or of OctalDigit ::
3 is 3.
The MV of DecimalDigit :: 4 or of NonZeroDigit ::
4 or of HexDigit ::
4 or of OctalDigit ::
4 is 4.
The MV of DecimalDigit :: 5 or of NonZeroDigit ::
5 or of HexDigit ::
5 or of OctalDigit ::
5 is 5.
The MV of DecimalDigit :: 6 or of NonZeroDigit ::
6 or of HexDigit ::
6 or of OctalDigit ::
6 is 6.
The MV of DecimalDigit :: 7 or of NonZeroDigit ::
7 or of HexDigit ::
7 or of OctalDigit ::
7 is 7.
The MV of DecimalDigit :: 8 or of NonZeroDigit ::
8 or of HexDigit ::
8 is 8.
The MV of DecimalDigit :: 9 or of NonZeroDigit ::
9 or of HexDigit ::
9 is 9.
The MV of HexDigit :: a or of HexDigit :: A is 10.
The MV of HexDigit :: b or of HexDigit :: B is 11.
The MV of HexDigit :: c or of HexDigit :: C is 12.
The MV of HexDigit :: d or of HexDigit :: D is 13.
The MV of HexDigit :: e or of HexDigit :: E is 14.
The MV of HexDigit :: f or of HexDigit :: F is 15.
The MV of BinaryIntegerLiteral :: 0b BinaryDigit is the MV of BinaryDigit.
The MV of BinaryIntegerLiteral :: 0B BinaryDigit is the MV of BinaryDigit.
The MV of BinaryIntegerLiteral :: BinaryIntegerLiteral BinaryDigit is (the MV of BinaryIntegerLiteral times 2) plus the MV of BinaryDigit.
The MV of OctalIntegerLiteral :: 0o OctalDigit is the MV of OctalDigit.
The MV of OctalIntegerLiteral :: 0O OctalDigit is the MV of OctalDigit.
The MV of OctalIntegerLiteral :: OctalIntegerLiteral OctalDigit is (the MV of OctalIntegerLiteral times 8) plus the MV of OctalDigit.
The MV of HexIntegerLiteral :: 0x HexDigits is the MV of HexDigits.
The MV of HexIntegerLiteral :: 0X HexDigits is the MV of HexDigits.
The MV of HexDigits :: HexDigit is the MV of HexDigit.
The MV of HexDigits :: HexDigits HexDigit is (the MV of HexDigits times 16) plus the MV of HexDigit.
Once the exact MV for a numeric literal has been determined, it is then rounded to a value of the Number type. If the MV
is 0, then the rounded value is +0; otherwise, the rounded value must be the Number value for the
MV (as specified in 8.5), unless the literal is a DecimalLiteral and the
literal has more than 20 significant digits, in which case the Number value may be either the Number value for the MV of a
literal produced by replacing each significant digit after the 20th with a 0 digit or the Number value for the
MV of a literal produced by replacing each significant digit after the 20th with a 0 digit and then
incrementing the literal at the 20th significant digit position. A digit is significant if it is not part of an ExponentPart and
0; or
NOTE A regular expression literal is an input element that is converted to a RegExp object (see 15.10) each time the literal is evaluated. Two regular expression literals in a program evaluate
to regular expression objects that never compare as === to each other even if the two literals' contents are
identical. A RegExp object may also be created at runtime by new RegExp (see
15.10.4) or calling the RegExp constructor as a function (15.10.3).
The productions below describe the syntax for a regular expression literal and are used by the input element scanner to find the end of the regular expression literal. The source code comprising the RegularExpressionBody and the RegularExpressionFlags are subsequently parsed using the more stringent ECMAScript Regular Expression grammar (15.10.1).
An implementation may extend the ECMAScript Regular Expression grammar defined in 15.10.1, but it must not extend the RegularExpressionBody and RegularExpressionFlags productions defined below or the productions used by these productions.
/ RegularExpressionBody / RegularExpressionFlags* or \ or / or [\ or / or [\ RegularExpressionNonTerminator[ RegularExpressionClassChars ]] or \NOTE Regular expression literals may not be empty; instead of representing an empty regular
expression literal, the characters // start a single-line comment. To specify an empty regular expression,
use: /(?:)/.
Static Semantics: BodyText
RegularExpressionLiteral :: /
RegularExpressionBody / RegularExpressionFlags
Static Semantics: FlagText
RegularExpressionLiteral :: /
RegularExpressionBody / RegularExpressionFlags
` TemplateCharactersopt `` TemplateCharactersopt ${} TemplateCharactersopt ${} TemplateCharactersopt `` or \ or $$ [lookahead ∉ { ]\ EscapeSequenceStatic Semantics: TV’s and TRV’s
A template literal component is interpreted as a sequence of Unicode characters. The Template Value (TV) of a literal component is described in terms of code unit values (CV, 7.8.4) contributed by the various parts of the template literal component. As part of this process, some Unicode characters within the template component are interpreted as having a mathematical value (MV, 7.8.3). In determining a TV, escape sequences are replaced by the code unit of the Unicode characters represented by the escape sequence. The Template Raw Value (TRV) is similar to a Template Value with the difference that in TRVs escape sequences are interpreted literally.
The TV and TRV of NoSubstitutionTemplate :: `` is the empty code unit sequence.
The TV and TRV of TemplateHead :: `${ is the empty code unit sequence.
The TV and TRV of TemplateMiddle :: }${ is the empty code unit sequence.
The TV and TRV of TemplateTail :: }` is the empty code unit sequence.
The TV of NoSubstitutionTemplate :: ` TemplateCharacters ` is the TV of
TemplateCharacters.
The TV of TemplateHead :: ` TemplateCharacters ${ is the TV of
TemplateCharacters.
The TV of TemplateMiddle :: } TemplateCharacters ${ is the TV of
TemplateCharacters.
The TV of TemplateTail :: } TemplateCharacters ` is the TV of
TemplateCharacters.
The TV of TemplateCharacters :: TemplateCharacter is the TV of TemplateCharacter.
The TV of TemplateCharacters :: TemplateCharacter TemplateCharacters is a sequence consisting of the code units in the TV of TemplateCharacter followed by all the code units in the TV of TemplateCharacters in order.
The TV of TemplateCharacter :: SourceCharacter but not one of ` or \ or $ is
the UTF-16 Encoding (clause 6) of the code point value of SourceCharacter.
The TV of TemplateCharacter :: $ [lookahead ∉ { ] is the code unit value 0x0024.
The TV of TemplateCharacter :: \ EscapeSequence is the CV of EscapeSequence.
The TV of TemplateCharacter :: LineContinuation is the TV of LineContinuation.
The TV of LineContinuation :: \ LineTerminatorSequence is the empty code unit sequence.
The TRV of NoSubstitutionTemplate :: ` TemplateCharacters ` is the TRV of
TemplateCharacters.
The TRV of TemplateHead :: ` TemplateCharacters ${ is the TRV of
TemplateCharacters.
The TRV of TemplateMiddle :: } TemplateCharacters ${ is the TRV of
TemplateCharacters.
The TRV of TemplateTail :: } TemplateCharacters ` is the TRV of
TemplateCharacters.
The TRV of TemplateCharacters :: TemplateCharacter is the TRV of TemplateCharacter.
The TRV of TemplateCharacters :: TemplateCharacter TemplateCharacters is a sequence consisting of the code units in the TRV of TemplateCharacter followed by all the code units in the TRV of TemplateCharacters, in order.
The TRV of TemplateCharacter :: SourceCharacter but not one of ` or \ or $ is
the UTF-16 Encoding (clause 6) of the code point value of SourceCharacter.
The TRV of TemplateCharacter :: $ [lookahead ∉ { ] is the code unit value 0x0024.
The TRV of TemplateCharacter :: \ EscapeSequence is the sequence consisting of the code unit value
0x005C followed by the code units of TRV of EscapeSequence.
The TRV of TemplateCharacter :: LineContinuation is the TRV of LineContinuation.
The TRV of EscapeSequence :: CharacterEscapeSequence is the TRV of the CharacterEscapeSequence.
The TRV of EscapeSequence :: 0 [lookahead ∉ DecimalDigit] is the
code unit value 0x0030.
The TRV of EscapeSequence :: HexEscapeSequence is the TRV of the HexEscapeSequence.
The TRV of EscapeSequence :: UnicodeEscapeSequence is the TRV of the UnicodeEscapeSequence.
The TRV of CharacterEscapeSequence :: SingleEscapeCharacter is the TRV of the SingleEscapeCharacter.
The TRV of CharacterEscapeSequence :: NonEscapeCharacter is the CV of the NonEscapeCharacter.
The TRV of SingleEscapeCharacter :: one of ' " \ b f n r t
v is the CV of the SourceCharacter that is that single character.
The TRV of HexEscapeSequence :: x HexDigit HexDigit is the sequence consisting
of code unit value 0x0078 followed by TRV of the first HexDigit followed by the TRV of the second
HexDigit.
The TRV of UnicodeEscapeSequence :: u HexDigit HexDigit HexDigit
HexDigit is the sequence consisting of code unit value 0x0075 followed by TRV of the
first HexDigit followed by the TRV of the second HexDigit followed by TRV of the third HexDigit
followed by the TRV of the fourth HexDigit.
The TRV of UnicodeEscapeSequence :: u{ HexDigits } is the sequence consisting of code
unit value 0x0075 followed by code unit value 0x007B followed by TRV of HexDigits followed by code unit value
0x007D.
The TRV of HexDigits :: HexDigit is the TRV of HexDigit.
The TRV of HexDigits :: HexDigits HexDigit is the sequence consisting of TRV of HexDigits followed by TRV of HexDigit.
The TRV of a HexDigit is the CV of the SourceCharacter that is that HexDigit.
The TRV of LineContinuation :: \ LineTerminatorSequence is the sequence consisting of the code unit
value 0x005C followed by the code units of TRV of LineTerminatorSequence.
The TRV of LineTerminatorSequence :: <LF> is the code unit value 0x000A.
The TRV of LineTerminatorSequence :: <CR> [lookahead ∉ <LF> ] is the code unit value 0x000D.
The TRV of LineTerminatorSequence :: <LS> is the code unit value 0x2028.
The TRV of LineTerminatorSequence :: <PS> is the code unit value 0x2029.
The TRV of LineTerminatorSequence :: <CR><LF> is the sequence consisting of the code unit value 0x000D followed by the code unit value 0x000A.
NOTE TV excludes the code units of LineContinuation while TRV includes them.
NOTE A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be be represented by an escape sequence. All characters may appear literally in a string literal except for the closing quote character, backslash, carriage return, line separator, paragraph separator, and line feed. Any character may appear in the form of an escape sequence. String literals evaluate to ECAMScript String values. When generating these string values Unicode code points are UTF-16 encoded as defined in clause 6. Code points belonging to Basic Multilingual Plane are encoded as a single code unit element of the string. All other code points are encoded as two code unit elements of the string.
" DoubleStringCharactersopt "' SingleStringCharactersopt '" or \ or LineTerminator\ EscapeSequence' or \ or LineTerminator\ EscapeSequence\ LineTerminatorSequence0 [lookahead ∉ DecimalDigit]A conforming implementation, when processing strict mode code (see 10.1.1), must not extend the syntax of EscapeSequence to include OctalEscapeSequence as described in B.1.2.
' " \ b f n r t vxux HexDigit HexDigitu HexDigit HexDigit HexDigit HexDigitu{ HexDigits }The definition of the nonterminal HexDigit is given in 7.8.3. SourceCharacter is defined in clause 6.
NOTE A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator
character to be part of the String value of a string literal is to use an escape sequence such as \n or
\u000A.
Static Semantics
Static Semantics: Early Errors
UnicodeEscapeSequence :: u{
HexDigits }
Static Semantics: SV’s and CV’s
A string literal stands for a value of the String type. The String value (SV) of the literal is described in terms of code unit values (CV) contributed by the various parts of the string literal. As part of this process, some Unicode characters within the string literal are interpreted as having a mathematical value (MV), as described below or in 7.8.3.
The SV of StringLiteral :: "" is the empty code unit sequence.
The SV of StringLiteral :: '' is the empty code unit sequence.
The SV of StringLiteral :: " DoubleStringCharacters " is the SV of
DoubleStringCharacters.
The SV of StringLiteral :: ' SingleStringCharacters ' is the SV of
SingleStringCharacters.
The SV of DoubleStringCharacters :: DoubleStringCharacter is a sequence of one or two code units that is the CV of DoubleStringCharacter.
The SV of DoubleStringCharacters :: DoubleStringCharacter DoubleStringCharacters is a sequence of one or two code units that is the CV of DoubleStringCharacter followed by all the code units in the SV of DoubleStringCharacters in order.
The SV of SingleStringCharacters :: SingleStringCharacter is a sequence of one or two code units that is the CV of SingleStringCharacter.
The SV of SingleStringCharacters :: SingleStringCharacter SingleStringCharacters is a sequence of one or two code units that is the CV of SingleStringCharacter followed by all the code units in the SV of SingleStringCharacters in order.
The SV of LineContinuation :: \ LineTerminatorSequence is the empty code unit sequence.
The CV of DoubleStringCharacter :: SourceCharacter but not one of " or \ or LineTerminator is the UTF-16 Encoding (clause 6) of the code point value
of SourceCharacter.
The CV of DoubleStringCharacter :: \ EscapeSequence is the CV of the EscapeSequence.
The CV of DoubleStringCharacter :: LineContinuation is the empty character sequence.
The CV of SingleStringCharacter :: SourceCharacter but not one of ' or \ or LineTerminator is the UTF-16 Encoding (clause 6) of the code point value
of SourceCharacter .
The CV of SingleStringCharacter :: \ EscapeSequence is the CV of the EscapeSequence.
The CV of SingleStringCharacter :: LineContinuation is the empty character sequence.
The CV of EscapeSequence :: CharacterEscapeSequence is the CV of the CharacterEscapeSequence.
The CV of EscapeSequence :: 0 [lookahead ∉ DecimalDigit] is the
code unit value 0.
The CV of EscapeSequence :: HexEscapeSequence is the CV of the HexEscapeSequence.
The CV of EscapeSequence :: UnicodeEscapeSequence is the CV of the UnicodeEscapeSequence.
The CV of CharacterEscapeSequence :: SingleEscapeCharacter is the character whose code unit value is determined by the SingleEscapeCharacter according to { REF _Ref327353613 \h \* MERGEFORMAT }:
| Escape Sequence | Code Unit Value | Name | Symbol |
|---|---|---|---|
\b |
0x0008 |
backspace | <BS> |
\t |
0x0009 |
horizontal tab | <HT> |
\n |
0x000A |
line feed (new line) | <LF> |
\v |
0x000B |
vertical tab | <VT> |
\f |
0x000C |
form feed | <FF> |
\r |
0x000D |
carriage return | <CR> |
\" |
0x0022 |
double quote | " |
\' |
0x0027 |
single quote | ' |
\\ |
0x005C |
backslash | \ |
The CV of CharacterEscapeSequence :: NonEscapeCharacter is the CV of the NonEscapeCharacter.
The CV of NonEscapeCharacter :: SourceCharacter but not one of EscapeCharacter or LineTerminator is the UTF-16 Encoding (clause 6) of the code point value of SourceCharacter .
The CV of HexEscapeSequence :: x HexDigit HexDigit is the code unit value that
is (16 times the MV of the first HexDigit) plus the MV of the second HexDigit.
The CV of UnicodeEscapeSequence :: u HexDigit HexDigit HexDigit
HexDigit is the code unit value that is (4096 times the MV of the first HexDigit)
plus (256 times the MV of the second HexDigit) plus (16 times the MV of the third HexDigit) plus the MV of
the fourth HexDigit.
The CV of UnicodeEscapeSequence :: u{ HexDigits } the is the UTF-16 Encoding (clause 6) of the MV of HexDigits.
Certain ECMAScript statements (empty statement, variable statement, expression statement,
do-while statement, continue statement, break statement,
return statement, and throw statement) must be terminated with semicolons. Such semicolons may
always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in
certain situations. These situations are described by saying that semicolons are automatically inserted into the source code
token stream in those situations.
There are three basic rules of semicolon insertion:
}.However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically
if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in
the header of a for statement (see 12.6.3).
NOTE The following are the only restricted productions in the grammar:
++--continue [no LineTerminator here] Identifier ;break [no LineTerminator here] Identifier ;return [no LineTerminator here] Expression ;throw [no LineTerminator here] Expression ;The practical effect of these restricted productions is as follows:
When a ++ or -- token is encountered where the parser would treat it as a postfix operator, and
at least one LineTerminator occurred between the preceding token and the ++ or
-- token, then a semicolon is automatically inserted before the ++ or -- token.
When a continue, break, return, or throw token is encountered and a
LineTerminator is encountered before the next token, a semicolon is automatically inserted after the
continue, break, return, or throw token.
The resulting practical advice to ECMAScript programmers is:
A postfix ++ or -- operator should appear on the same line as its operand.
An Expression in a return or throw statement should start on the same
line as the return or throw token.
An Identifier in a break or continue statement should be on the same
line as the break or continue token.
The source
{ 1 2 } 3
is not a valid sentence in the ECMAScript grammar, even with the automatic semicolon insertion rules. In contrast, the source
{ 1
2 } 3
is also not a valid ECMAScript sentence, but is transformed by automatic semicolon insertion into the following:
{ 1
;2 ;} 3;
which is a valid ECMAScript sentence.
The source
for (a; b
)
is not a valid ECMAScript sentence and is not altered by automatic semicolon insertion because the semicolon is needed
for the header of a for statement. Automatic semicolon insertion never inserts one of the two semicolons in the
header of a for statement.
The source
return
a + b
is transformed by automatic semicolon insertion into the following:
return;
a + b;
NOTE The expression a + b is not treated as a value to be returned by the
return statement, because a LineTerminator separates it from the token
return.
The source
a = b
++c
is transformed by automatic semicolon insertion into the following:
a = b;
++c;
NOTE The token ++ is not treated as a postfix operator applying to the variable
b, because a LineTerminator occurs between b and ++.
The source
if (a > b)
else c = d
is not a valid ECMAScript sentence and is not altered by automatic semicolon insertion before the else
token, even though no production of the grammar applies at that point, because an automatically inserted semicolon would
then be parsed as an empty statement.
The source
a = b + c
(d + e).print()
is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the second line can be interpreted as an argument list for a function call:
a = b + c(d + e).print()
In the circumstance that an assignment statement must begin with a left parenthesis, it is a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement rather than to rely on automatic semicolon insertion.
Algorithms within this specification manipulate values each of which has an associated type. The possible value types are exactly those defined in this clause. Types are further subclassified into ECMAScript language types and specification types.
Within this specification, the notation “Type(x)” is used as shorthand for “the type of x” where “type” refers to the ECMAScript language and specification types defined in this clause.
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, Number, and Object. An ECMAScript language value is a value that is characterized by an ECMAScript language type.
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
The Null type has exactly one value, called null.
The Boolean type represents a logical entity having two values, called true and false.
The String type is the set of all finite ordered sequences of zero or more 16-bit unsigned integer values (“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 nonnegative 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.
Where ECMAScript operations interpret String values, each element is interpreted as a single UTF-16 code unit. However, ECMAScript does not place any restrictions or requirements on the sequence of code units in a String value, so they may be ill-formed when interpreted as UTF-16 code unit sequences. Operations that do not interpret String contents treat them as sequences of undifferentiated 16-bit unsigned integers. No operations ensure that Strings are in a normalized form. Only operations that are explicitly specified to be language or locale sensitive produce language-sensitive results
NOTE The rationale behind this design was to keep the implementation of Strings as simple and high-performing as possible. If ECMAScript source code is in Normalised Form C, string literals are guaranteed to also be normalised, as long as they do not contain any Unicode escape sequences.
Some operations interpret String contents as UTF-16 encoded Unicode code points. In that case the interpretation is:
A code unit in the range 0 to 0xD7FF or in the range 0xE000 to 0xFFFF is interpreted as a code point with the same value.
A sequence of two code units, where the first code unit c1 is in the range 0xD800 to 0xDBFF and the second code unit c2 is in the range 0xDC00 to 0xDFFF, is a surrogate pair and is interpreted as a code point with the value (c1 - 0xD800) × 0x400 + (c2 – 0xDC00) + 0x10000.
A code unit that is in the range 0xD800 to 0xDFFF, but is not part of a surrogate pair, is interpreted as a code point with the same value.
The Number type has exactly 18437736874454810627 (that is, 264−253+3) values, representing the double-precision
64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic, except that the 9007199254740990 (that is, 253−2) distinct “Not-a-Number” values of the IEEE Standard are represented in
ECMAScript as a single special NaN value. (Note that the NaN value is produced by the program expression
NaN.) In some implementations, external code might be able to detect a difference between various Not-a-Number
values, but such behaviour is implementation-dependent; to ECMAScript code, all NaN values are indistinguishable from each
other.
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 18437736874454810624 (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 18437736874454810622 (that is, 264−253−2) finite nonzero values are of two kinds:
18428729675200069632 (that is, 264−254) of them are normalised, having the form
where s is +1 or −1, m is a positive integer less than 253 but not less than 252, and e is an integer ranging from −1074 to 971, inclusive.
The remaining 9007199254740990 (that is, 253−2) values are denormalised, having the form
where s is +1 or −1, m is a positive integer less than 252, and e is −1074.
Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the Number type (indeed, the integer 0 has two representations, +0 and -0).
A finite number has an odd significand if it is nonzero 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 nonzero 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 is less than zero; 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 “round to nearest” mode.)
Some ECMAScript operators deal only with integers in the range −231 through 231−1, inclusive, or in the range 0 through 232−1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 232 integer values. See the descriptions of the ToInt32 and ToUint32 operators in 9.5 and 9.6, respectively.
An Object is logically a collection of properties. Each property is either a data property, or an accessor property:
A data property associates a key value with an ECMAScript language value and a set of Boolean attributes.
A accessor property associates a key value with one or two accessor functions, and a set of Boolean attributes. The accessor functions are used to store or retrieve an ECMAScript language value that is associated with the property.
Properties are identified using key values. A key value is either an ECMAScript String value or an Exotic Symbol object (8.4.3).
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.
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. Ordinary objects are the most common form of objects and have the default object semantics. An exotic object is any form of object whose property semantics differ in any way from the default semantics.
Attributes are used in this specification to define and explain the state of Object properties. A data property associates a key value with the attributes listed in Table 5.
| Attribute Name | Value Domain | Description |
|---|---|---|
| [[Value]] | Any ECMAScript language type | The value retrieved by a get access of the property. |
| [[Writable]] | Boolean | If false, attempts by ECMAScript code to change the property’s [[Value]] attribute using [[Set]] will not succeed. |
| [[Enumerable]] | Boolean | If true, the property will be enumerated by a for-in enumeration (see 12.6.4). Otherwise, the property is said to be non-enumerable. |
| [[Configurable]] | Boolean | If false, attempts to delete the property, change the property to be an accessor property, or change its attributes (other than [[Value]], or changing [[Writable]] to false) will fail. |
An accessor property associates a key value with the attributes listed in Table 6.
| Attribute Name | Value Domain | Description |
|---|---|---|
| [[Get]] | Object or Undefined | If the value is an Object it must be a function Object. The function’s [[Call]] internal method (8.6.2) is called with an empty arguments list to retrieve the property value each time a get access of the property is performed. |
| [[Set]] | Object or Undefined | If the value is an Object it must be a function Object. The function’s [[Call]] internal method (8.6.2) 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]] | Boolean | If true, the property is to be enumerated by a for-in enumeration (see 12.6.4). Otherwise, the property is said to be non-enumerable. |
| [[Configurable]] | Boolean | If false, attempts to delete the property, change the property to be a data property, or change its attributes will fail. |
If the initial values of a property’s attributes are not explicitly specified by this specification, the default value defined in Table 7 is used.
| Attribute Name | Default Value |
|---|---|
| [[Value]] | undefined |
| [[Get]] | undefined |
| [[Set]] | undefined |
| [[Writable]] | false |
| [[Enumerable]] | false |
| [[Configurable]] | false |
The actual semantics of ECMAScript objects 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 methods are identified within this specification using names enclosed in double square brackets [[ ]]. Internal method names are polymorphic. This means that different ECMAScript object values may perform different algorithms when a common internal method name is invoked upon them. 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 data properties correspond to internal state that is associated with objects and used by various ECMAScript specification algorithms. Depending upon the specific internal data property such state may consist of values of any ECMAScript language type or of specific ECMA specification type values. Unless explicitly specified otherwise, internal data properties are allocated as part of the process of creating an an ECMAScript object and may not be dynamically added to ECMAScript objects. Unless specified otherwise, the initial value of an internal data property is the value undefined.
Table 8{ REF _Ref327354012 \h } summarises the essential internal methods used by this specification that are applicable to all ECMAScript objects. 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.
The “Signature” column of Table 8 and other similar tables describes the invocation pattern for each internal method. The invocation pattern always includes a parenthesised 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 8 augmented by the following additional names. “any” means the value may be any ECMAScript language type. “primitive” means Undefined, Null, Boolean, String, or Number. An internal method implicitly returns a Completion Record as described in 8.8. In addition to its parameters, an internal method always has access to the object upon which it is invoked as a method.
| Internal Method | Signature | Description |
|---|---|---|
| [[GetInheritance]] | ()→Object or Null | Determine the object that provides inherited properties for this object. A null value indicates that there are no inherited properties. an object. |
| [[SetInheritance]] | (Object or Null)→Boolean | Associate with an object 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. |
| [[HasIntegrity]] | (String)→Boolean | Determine whether the property structure of an object is fixed to at least the specified level. The argument is one of the values "nonextensible", "sealed", or "frozen". |
| [[SetIntegrity]] | (String)→Boolean | Restrict the mutability of an object’s properties to that which is allowed for the specified integtry level. The argument is one of the values "nonextensible", "sealed", or "frozen". Returns true indicating that the operation was completed successfully or false indicating that the operation was not successful. The integrity level of an object may be raised but may not be lower. |
| [[HasOwnProperty]] | (propertyKey) → Boolean | Returns a Boolean value indicating whether the object already has an own property whose key is propertyKey. |
| [[GetOwnProperty]] |
(propertyKey) → Undefined or Property Descriptor |
Returns a Property Descriptor for the own property of this object whose key is propertyKey, or undefined if no such property exists. |
| [[HasProperty]] | (propertyKey) → Boolean | Returns a Boolean value indicating whether the object already has either an own or inherited property whose key is propertyKey. |
| [[Set]] | (propertyKey,value, Receiver) → Boolean | Try to set the value of an object’s property indentified by 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 indicating that the property value was set or false indicating that it could not be set. |
| [[Delete]] | (propertyKey) → Boolean | Removes the own property indentified by the propertyKey parameter from the object. Return false if the property was not deleted and is still present. Return true if the property was deleted or was not present. |
| [[DefineOwnProperty]] | (propertyKey, PropertyDescriptor) → Boolean | Creates or alters the named own property to have the state described by a Property Descriptor. Returns true indicating that the property was successfully created/updated or false indicating that the property could not be created or updated. |
| [[Enumerate]] | ()→Object | Returns an iterator object over the string values of the keys of the enumerable properties of the object. |
| [[OwnPropertyKeys]] | ()→Object | Returns an interator object that produces all of the own property keys for the object except those that are private Symbols. |
Table 9 summarises additional essential internal methods that must be supported by all objects that may be called as functions..
| Internal Method | Signature | Description |
|---|---|---|
| [[Call]] | (any, a List of any) → any or Reference | Executes code associated with the object. Invoked via a function call expression. The arguments to the internal method are a this value and a list containing the arguments passed to the function by a call expression. Objects that implement this internal method are callable. Only callable objects that are host objects may return Reference values. |
| [[Construct]] | (a List of any) → Object | Creates an object. Invoked via the new operator. The arguments to the internal are the arguments passed to the new operator. Objects that implement this internal method are called constructors. |
Current this section is just a bunch of material merged together from the ES5 spec. and from the wiki Proxy pages. It need to be completely reworked.
The intent is that it lists all invariants of the Essential Internal Methods. This includes both invariants that are enforced for Proxy objects and other invariants that may not be enfored.
Definitions:
The target of an internal method is the object the internal method is called upon.
A sealed property is a non-configurable own property of a target.
A frozen property is a non-configurable non-writable own property of a target.
A new property is a property that does not exist on a non-extensible target.
Two property descriptors desc1 and desc2 for a property key value are incompatible if:
Exotic objects may define additional constraints upon their [[Set]] internal method behavior. If possible, exotic objects should not allow [[Set]] operations in situations where this definition of [[CanPut]] returns false.
[[GetInheritance]]
Every [[Prototype]] chain must have finite length (that is, starting from any object, recursively accessing the [[Prototype]] internal data property must eventually lead to a null value).
getOwnPropertyDescriptor
Non-configurability invariant: cannot return incompatible descriptors for sealed properties
Non-extensibility invariant: must return undefined for new properties
Invariant checks:
if trap returns undefined, check if the property is configurable
if property exists on target, check if the returned descriptor is compatible
if returned descriptor is non-configurable, check if the property exists on the target and is also non-configurable
defineProperty
Non-configurability invariant: cannot succeed (return true) for incompatible changes to sealed properties
Non-extensibility invariant: must reject (return false) for new properties
Invariant checks:
on success, if property exists on target, check if existing descriptor is compatible with argument descriptor
on success, if argument descriptor is non-configurable, check if the property exists on the target and is also non-configurable
getOwnPropertyNames
Non-configurability invariant: must report all sealed properties
Non-extensibility invariant: must not list new property names
Invariant checks:
check whether all sealed target properties are present in the trap result
If the target is non-extensible, check that no new properties are listed in the trap result
deleteProperty
Non-configurability invariant: cannot succeed (return true) for sealed properties
Invariant checks:
on success, check if the target property is configurable
getPrototypeOf
Invariant check: check whether the target’s prototype and the trap result are identical (according to the egal operator)
freeze | seal | preventExtensions
Invariant checks:
on success, check if isFrozen(target), isSealed(target) or !isExtensible(target)
isFrozen | isSealed | isExtensible
Invariant check: check whether the boolean trap result is equal to isFrozen(target), isSealed(target) or isExtensible(target)
hasOwn
Non-configurability invariant: cannot return false for sealed properties
Non-extensibility invariant: must return false for new properties
Invariant checks:
if false is returned, check if the target property is configurable
if false is returned, the property does not exist on target, and the target is non-extensible, throw a TypeError
has
Non-configurability invariant: cannot return false for sealed properties
Invariant checks:
if false is returned, check if the target property is configurable
get
Non-configurability invariant: cannot return inconsistent values for frozen data properties, and must return undefined for sealed accessors with an undefined getter
Invariant checks:
if property exists on target as a data property, check whether the target property’s value and the trap result are identical (according to the egal operator)
if property exists on target as an accessor, and the accessor’s get attribute is undefined, check whether the trap result is also undefined.
set
Non-configurability invariant: cannot succeed (return true) for frozen data properties or sealed accessors with an undefined setter
Invariant checks:
on success, if property exists on target as a data property, check whether the target property’s value and the update value are identical (according to the egal operator)
on success, if property exists on target as an accessor, check whether the accessor’s set attribute is not undefined
keys
Non-configurability invariant: must report all enumerable sealed properties
Non-extensibility invariant: must not list new property names
Invariant checks:
Check whether all enumerable sealed target properties are listed in the trap result
If the target is non-extensible, check that no new properties are listed in the trap result
enumerate
Non-configurability invariant: must report all enumerable sealed properties
Invariant checks:
Check whether all enumerable sealed target properties are listed in the trap result
NOTE This specification defines no ECMAScript language operators or built-in functions that permit a program to modify an object’s [[Prototype]] internal properties or to change the value of [[Extensible]] from false to true. Implementation specific extensions that modify [[Prototype]] or [[Extensible]] must not violate the invariants defined in the preceding paragraph.
Unless otherwise specified, the standard ECMAScript objects are ordinary objects and behave as described in 8.3. Some standard objects are exotic objects and have behaviour defined in 8.4..
Exotic objects may implement internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Set]] for a particular exotic object indeed fetch and store property values but [[HasOwnProperty]] always generates false. However, if any specified manipulation of an exotic object's internal properties is not supported by an implementation, that manipulation must throw a TypeError exception when attempted.
The [[GetOwnProperty]] internal method of all objects must conform to the following invariants for each property of the object:
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 internal methods.
If a property is described as a data property and its [[Writable]] and [[Configurable]] are both false, then the SameValue (according to 9.12) must be returned for the [[Value]] attribute of the property on all calls to [[GetOwnProperty]].
If the attributes other than [[Writable]] may change over time or if the property might disappear, then the [[Configurable]] attribute must be true.
If the [[Writable]] attribute may change from false to true, then the [[Configurable]] attribute must be true.
If the result of calling an object’s [[IsExtensible]] internal method has been observed by ECMAScript code to be false, then if a call to [[GetOwnProperty]] describes a property as non-existent all subsequent calls must also describe that property as non-existent.
The [[DefineOwnProperty]] internal method of all objects must not permit the addition of a new property to an object if the [[Extensible]] internal method of that object has been observed by ECMAScript code to be false.
If the result of calling the [[IsExtensible]] internal method of an object has been observed by ECMAScript code to be false then it must not subsequently become true.
Well-known symbols are built-in exotic symbol objects (8.4.4) 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 Code Realms (10.3) and the value of their [[Private]] internal data property (forward ref) is false.
Within this specification a well-known symbol is referred to by using a notation of the form @@name, where “name” is one of the values listed in Table 10.
| Specification Name | Value and Purpose |
|---|---|
| @@create | A method used to allocate an object. Called from the [[Construct]] internal method. |
| @@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. |
| @@isRegExp | A Boolean value that if true indicates that an object may be used as a regular expression. |
| @@iterator | A method that returns the default iterator for an object. Called by the semantics of the for-of statement. |
| @@ToPrimitive | A method that converts an object to a corresponding primitive value. Called by the ToPrimitive abstract operation. |
| @@toStringTag | A string value that is used in the creation of the default string description of an object. Called by the built-in method Object.prototype.toString. |
Well-known intransics are built-in objects that are explicitly referenced by the algorithms of this specification and which usually have Code Realm specific identities. Unless otherwise specified each intrinsic object actually corresponds to a set of similar objects, one per Code Realm.
Within this specification a reference such as %name% means the intrinsic object, associated with the current Code Realm, corresponding to the name. Determine of the current Code Realmand its intransics is described in 10.3. The well-known intrincs are listed in Table 11.
| Intrinsic Name | ECMAScript Language Association |
|---|---|
| %Object% | The initial value of the global object property named "Object". |
| %ObjectPrototype% | The initial value of the "prototype" data property of the intrinsic %Object%. |
| %ObjProto_toString% | The initial value of the "toString" data property of the intrinsic %ObjectPrototype%. |
| %Function% | The initial value of the global object property named "Function". |
| %FunctionPrototype% | The initial value of the "prototype" data property of the intrinsic %Function%. |
| %Array% | The initial value of the global object property named "Array". |
| %ArrayPrototype% | The initial value of the "prototype" data property of the intrinsic %Array%. |
| %ArrayIteratorPrototype% | The prototype object used for interator objects created by the CreateArrayIterator abstract operation. |
| %Map% | The initial value of the global object property named "Map". |
| %MapPrototype% | The initial value of the "prototype" data property of the intrinsic %Map%. |
| %MapIteratorPrototype% | The prototype object used for interator objects created by the CreateMapIterator abstract operation |
| %WeakMap% | The initial value of the global object property named "WeakMap". |
| %WeakMapPrototype% | The initial value of the "prototype" data property of the intrinsic %WeakMap%. |
| %Set% | The initial value of the global object property named "Set". |
| %SetPrototype% | The initial value of the "prototype" data property of the intrinsic %Set%. |
| %SetIteratorPrototype% | The prototype object used for interator objects created by the CreateSetterator abstract operation |
| %StopIteration% | |
| %ErrorPrototype% | |
| %EvalErrorPrototype% | |
| %RangePrototype% | |
| %ReferenceErrorPrototype% | |
| %SyntaxErrorPrototype% | |
| %TypeErrorPrototype% | |
| %URIErrorPrototype% | |
| ??? |
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 are Reference, List, Completion, Property Descriptor, Lexical Environment, Environment Record, 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.
This section is a placeholder for describing the Data Block internal type. The following material is verbatium from the the Binary Data ES wiki proposal. The material has not yet been reviewed or integrated with the rest of this spec.
This spec introduces a new, spec-internal block datatype, intuitively representing a contiguously allocated block of binary data. Blocks are not ECMAScript language values and appear only in the program store (aka heap).
A block is one of:
A number-block is one of:
A uintk is an integer in the range [0, 2k). An intk is an integer in the range [-2k-1, 2k-1). A floatk is a floating-point number representable as a k-bit IEE754 value.
An array-block[t, n] is an ordered sequence of n blocks of homogeneous block type t. Each element of the array is stored at in independently addressable location in the program store, and multiple Data objects may contain references to the element.
A struct-block[t1, ..., tn] is an ordered sequence of n blocks of heterogeneous types t1 to tn, respectively. Each field of the struct is stored at in independently addressable location in the program store, and multiple Data objects may contain references to the field.
The spec also introduces a datatype of Data objects, which are ECMAScript objects that encapsulate references to block data in the program store. Every Data object has the following properties:
[[Class]] = “Data”
[[Value]] : reference[block] – a reference to a block in the program store
[[DataType]] : reference[Type] – a reference to a Type object describing this object’s data block
The List type is used to explain the evaluation of argument lists (see 11.2.4) in
new expressions, in function calls, and in other algorithms where a simple list of values is needed. Values of
the List type are simply ordered sequences of values. These sequences may be of any length.
The Record type is used to describe data aggregations within the algorithms of this specification. A Record type value consists of one or more named fields. The value of each field is either an ECMAScript value or an abstract value represented by a name associated with the Record type. Field names are always enclosed in double brackets, for example [[value]]
For notational convenience within this specification, an object literal-like syntax can be used to express a Record value. For example, {[[field1]]: 42, [[field2]]: false, [[field3]]: empty} defines a Record value that has three fields each of which is initialized to a specific value. Field name order is not significant. Any fields that are not explicitly listed are considered to be absent.
In specification text and algorithms, dot notation may be used to refer to a specific field of a Record value. For example, if R is the record shown in the previous paragraph then R.[[field2]] is shorthand for “the field of R named [[field2]]”.
Schema for commonly used Record field combinations may be named, and that name may be used as a prefix to a literal Record value to identify the specific kind of aggregations that is being described. For example: Property Descriptor {[[Value]]: 42, [[Writable]]: false, [[Configurable]]: true}.
The Completion type is a Record used to explain the runtime propagation of values and control flow such as the behaviour
of statements (break, continue, return and throw) that perform nonlocal
transfers of control.
Values of the Completion type are Record values whole fields are defined as by Table 12.
| Field Name | Value | Meaning |
|---|---|---|
| [[type]] | One of normal, break, continue, return, or throw | The type of completion that occurred. |
| [[value]] | any ECMAScript language value or empty | The value that was produced. |
| [[target]] | any ECMAScript identifier or empty | The target label for directed control transfers. |
The term “abrupt completion” refers to any completion with a [[type]] value other than normal.
The abstract operation NormalCompletion with a single argument, such as:
Is a short hand that is defined as follows:
The algorithms of this specification often implicitly return Completion Records whose [[type]] is normal. Unless it is otherwise obvious from the context, an algorithm statement that returns a value that is not a Completion Record, such as:
"Infinity".Generally means the same thing as:
"Infinity").A “return” statement without a value in an algoritm step means the same thing as:
Similarly, any reference to a Completion Record value that is in a context that does not explicitly require a complete Completion Record value is equivalent to an explicit reference to the [[value]] field of the Completion Record value unless the Completion Record is an abrupt completion.
Algorithms steps that say to throw an exception, such as
Mean the same things as:
Algorithms steps that say
mean the same things as:
NOTE The Reference type is used to explain the behaviour of such operators as
delete, typeof, the assignment operators, the super keyword and other lanauge
features. For example, the left-hand operand of an assignment is expected to produce a reference.
A Reference is a resolved name binding. A Reference consists of three components, the base value, the referenced name and the Boolean valued strict reference flag. The base value is either undefined, an Object, a Boolean, a String, a Number, or an environment record (10.2.1). A base value of undefined indicates that the Reference could not be resolved to a binding. The referenced name is a String.
A Super Reference is a Reference that is used to represents a name binding that was expressed using the super keyword. A Super Reference has an additional thisValue component and its base value will never be an environment record.
The following abstract operations are used in this specification to access the components of references:
GetBase(V). Returns the base value component of the reference V.
GetReferencedName(V). Returns the referenced name component of the reference V.
GetThisValue(V). Returns the thisValue component of the reference V.
IsStrictReference(V). Returns the strict reference flag component of the reference V.
HasPrimitiveBase(V). Returns true if the base value is a Boolean, String, or Number.
IsPropertyReference(V). Returns true if either the base value is an object or HasPrimitiveBase(V) is true; otherwise returns false.
IsUnresolvableReference(V). Returns true if the base value is undefined and false otherwise.
IsSuperReference(V). Returns true if this reference has a thisValue component.
The following abstract operations are used in this specification to operate on references:
NOTE The object that may be created in step 5.a.ii is not accessible outside of the above method. An implementation might choose to avoid the actual creation of the object.
NOTE The object that may be created in step 6.a.ii is not accessible outside of the above algorithm. An implementation might choose to avoid the actual creation of that transient object.
The Property Descriptor type is used to explain the manipulation and reification of Object property attributes. Values of the Property Descriptor type are Records composed of named fields where each field’s name is an attribute name and its value is a corresponding attribute value as specified in 8.1.6.1. In addition, any field may be present or absent.
Property Descriptor values may be further classified as data property descriptors and accessor property descriptors based upon the existence or use of certain fields. A data property descriptor is one that includes any fields named either [[Value]] or [[Writable]]. An accessor property descriptor is one that includes any fields named either [[Get]] or [[Set]]. Any property descriptor may have fields named [[Enumerable]] and [[Configurable]]. A Property Descriptor value may not be both a data property descriptor and an accessor property descriptor; however, it may be neither. A generic property descriptor is a Property Descriptor value that is neither a data property descriptor nor an accessor property descriptor. A fully populated property descriptor is one that is either an accessor property descriptor or a data property descriptor and that has all of the fields that correspond to the property attributes defined in either 8.1.6.1 Table 5 or Table 6.
A Property Descriptor may be derived from an ECMAScript object that has properties that directly correspond to the fields of a Property Descriptor. Such a derived Property Descriptor has an additional field named [[Origin]] whose value is the object from which the Property Descriptor was derived.
The following abstract operations are used in this specification to operate upon Property Descriptor values:
When the abstract operation IsAccessorDescriptor is called with property descriptor Desc, the following steps are taken:
When the abstract operation IsDataDescriptor is called with property descriptor Desc, the following steps are taken:
When the abstract operation IsGenericDescriptor is called with property descriptor Desc, the following steps are taken:
When the abstract operation FromPropertyDescriptor is called with property descriptor Desc, the following steps are taken:
The following algorithm assumes that Desc is a fully populated Property Descriptor, such as that returned from [[GetOwnProperty]] (see 8.12.1).
writable", and Property Descriptor
{[[Value]]: Desc.[[Writable]], [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]:
true}.get", and Property Descriptor
{[[Value]]: Desc.[[Set]], [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]:
true}.set", and Property Descriptor
{[[Value]]: Desc.[[Set]], [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]:
true}.enumerable", and Property Descriptor
{[[Value]]: Desc.[[Enumerable]], [[Writable]]: true, [[Enumerable]]: true,
[[Configurable]]: true}.configurable", and Property Descriptor
{[[Value]]: Desc.[[Configurable]], [[Writable]]: true, [[Enumerable]]: true,
[[Configurable]]: true}.When the abstract operation ToPropertyDescriptor is called with object Obj, the following steps are taken:
enumerable") is true, then
enumerable").configurable") is true, then
configurable").value") is true, then
value").writable") is true, then
writable").get") is true, then
get").set") is true, then
set").When the abstract operation CompletePropertyDescriptor is called with Property Descriptor Desc, the following steps are taken:
The Lexical Environment and Environment Record types are used to explain the behaviour of name resolution in nested functions and blocks. These types and the operations upon them are defined in Clause 10.
Sections 8.3-8.5 will eventually be subsectons of a new toplevel section that follow the current section 10
All ordinary objects have an internal data property called [[Prototype]]. The value of this property is either null or an object and is used for implementing inheritance. Data properties of the [[Prototype]] object are inherited (are visible as properties of the child object) for the purposes of get access, but not for set access. Accessor properties are inherited for both get access and set access.
Every ordinary ECMAScript object has a Boolean-valued [[Extensible]] internal data property that controls whether or not properties may be added to the object. If the value of the [[Extensible]] internal data property is false then additional properties may not be added to the object. In addition, if [[Extensible]] is false the value of [[Prototype]] internal data properties of the object may not be modified. Once the value of an object’s [[Extensible]] internal data property has been set to false it may not be subsequently changed to true.
In the following algorithm descriptions, assume O is an ordinary ECMAScript object, P is a property key value, V is any ECMAScript language value, Desc is a Property Description record, and B is a Boolean flag.
When the [[GetInheritance]] internal method of O is called the following steps are taken:
When the [[SetInheritance]] internal method of O is called with argument V the following steps are taken:
When the [[HasIntegrity]] internal method of O is called the following steps are taken:
nonextensible", "sealed", or "frozen".nonextensible", then
When the [[Setntegrity]] internal method of O is called the following steps are taken:
nonextensible", "sealed", or "frozen".nonextensible", then
When the [[HasOwnProperty]] internal method of O is called with property key P, the following steps are taken:
When the [[GetOwnProperty]] internal method of O is called with property key P, the following steps are taken:
When the abstract operation OrdinaryGetOwnProperty is called with Object O and with property key P, the following steps are taken:
When the [[DefineOwnProperty]] internal method of O is called with property key P and property descriptor Desc, the following steps are taken:
When the abstract operation OrdinaryDefineOwnProperty is called with Object O, property key P, and property descriptors Desc the following steps are taken:
When the abstract operation IsCompatiblePropertyDescriptor is called with Boolean value Extensible, and property descriptors Desc, and Current the following steps are taken:
When the abstract operation ValidateAndApplyPropertyDescriptor is called with Object O, property key P, Boolean value extensible, and property descriptors Desc, and current the following steps are taken:
This algorithm contains steps that test various fields of the Property Descriptor Desc for specific values. The fields that are tested in this manner need not actually exist in Desc. If a field is absent then its value is considered to be false.
NOTE If undefined is passed as the O argument only validation is performed and no object updates are preformed.
NOTE Step 8.b allows any field of Desc to be different from the corresponding field of current if current’s [[Configurable]] field is true. This even permits changing the [[Value]] of a property whose [[Writable]] attribute is false. This is allowed because a true [[Configurable]] attribute would permit an equivalent sequence of calls where [[Writable]] is first set to true, a new [[Value]] is set, and then [[Writable]] is set to false.
When the [[HasProperty]] internal method of O is called with property key P, the following steps are taken:
When the [[Get]] internal method of O is called with property key P and ECMAScipt language value Receiver the following steps are taken:
When the [[Set]] internal method of O is called with property key P, value V, and ECMAScipt language value Receiver, the following steps are taken:
When the [[Delete]] internal method of O is called with property key P the following steps are taken:
When the [[Enumerate]] internal method of O is called the following steps are taken:
Enumerated properties do not include properties whose property key is a Symbol. Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.
Enumerating the properties of an object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively; but a property of a prototype is not enumerated if it is “shadowed” because some previous object in the prototype chain has a property with the same name. The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object is shadowed by a previous object on the prototype chain.
The following is an informative algorithm that conforms to these rules
When the [[OwnPropertyKeys]] internal method of O is called the following steps are taken:
The abstract operation ObjectCreate with argument proto (an object or null) is used to specify the runtime creation of new ordinary objects. The optional argument internalDataList is a List of the names of internal data property names that should be defined as part of the object. If the list is not provided, an empty List is used. It performs the following steps:
Ordinary function objects encapsulate parameterised ECMAScript code closed over a lexical environment and support the dynamic evaluation of that code. An ordinary function object is an ordinary object and has the same internal data properties and (except as noted below) the same internal methods as other ordinary objects.
Ordinary function objects have the additional internal data properties listed in Table 13. They also have a [[BuiltinBrand]] internal data property whose value is BuiltinFunction.
Ordinary function objects provide alternative definitions for the [[Get]] and [[GetOwnProperty]] internal methods. These
alternatives prevent the value of strict mode function from being revealed as the value of a function object property named
"caller". These alternative definitions exist sole to preclude a non-standard legacy feature of some ECMAScript
implementations from revealing information about strict mode callers. If an implementation does not provide such a feature,
it need not implement these alternative internal methods for ordinary function objects.
| Internal Data Property | Type | Description |
|---|---|---|
| [[Scope]] | Lexical Environment | The Lexical Environment that the function was closed over. Is used as the outer environment when evaluating the code of the function. |
| [[FormalParameters]] | Parse Node | The root parse node of the source code that defines the function’s formal parameter list. |
| [[Code]] | Parse Node | The root parse node of the source code that defines the function’s body. |
| [[Realm]] | Realm Record | The Code Realm in which the function was created and which provides any intrinsic objects that are accessed when evaluating the function. |
| [[ThisMode]] | (lexical, strict, global) | Defines how this references are interpreted within the formal parameters and code body of the function. lexical means that this refers to the this value of a lexically enclosing function. strict means that the this value is used exactly as provided by an invocation of the function. global means that a this value of undefined is interpreted as a reference to the global object. |
| [[Strict]] | Boolean | true if this is a strict mode function, false this is not a strict mode function. |
| [[Home]] | Object | If the function uses super, this is the object whose [[GetInheritance]] provides the object where super property lookups begin. Not present for functions that don’t reference super. |
| [[MethodName]] | String or Symbol | If the function uses super, this is the property keys that is used for unqualified references to super. Not present for functions that don’t reference super. |
Ordinary function objects all have the [[Call]], [[Get]] and [[GetOwnProperty]] internal methods defined here. Oridinary functions that are also constructors in addition have the [[Construct]] internal method.
The [[Call]] internal method for an ordinary Function object F is called with parameters thisArgument and argumentsList, a List of ECMAScript language values. The following steps are taken:
NOTE Most ordinary functions use a Function Environment Record as their LexicalEnvironment. Ordinary functions that are arrow functions use a Declarative Environment Record as their LexicalEnvironment.
The [[Construct]] internal method for an ordinary Function object F is called with a single parameter argumentsList which is a possibly empty List of ECMAScript language values. The following steps are taken:
When the abstract operation OrdinaryConstruct is called with Object F and List argumentsList the following steps are taken:
"%ObjectPrototype%").When the [[Get]] internal method of ordinary function object F is called with property key P and ECMAScipt language value Receiver the following steps are taken:
"caller" and v is a strict mode Function object, return null.When the [[GetOwnProperty]] internal method of ordinary function object F is called with property key P, the following steps are taken:
"caller" and v.[[Value]] is a strict mode Function object, then
This specification defines several kinds of built-in exotic objects. These objects generally behave similar to ordinary objects except for a few specific situations. The following exotic objects use the ordinary object internal methods except where it is explicitly specified otherwise below:
A bound function is an exotic object that wrappers another function object. A bound function is callable (it has [[Call]] and [[Construct]] internal methods). Calling a bound function generally results in a call of its wrappered function.
Bound function objects do not have the internal data properties of ordinary function objects defined in Table 13. Instead they have the internal data properties defined in Table 14. They also have a [[BuiltinBrand]] internal data property whose value is BuiltinFunction.
| Internal Data Property | Type | Description |
|---|---|---|
| [[BoundTargetFunction]] | Callable Object | The wrappered function object. |
| [[BoundThis]] | Any | The value that is always passed as the this value when calling the wrappered function. |
| [[BoundArguments]] | List of Any | A list of values that whose elements are used as the first arguments to any call to the wrappered function. |
Unlike ordinary function objects, bound function objects do not use alternative definitions of the [[Get]] and [[GetOwnPropety]] internal methods. Bound function objects provide all of the essential internal methods as specified in 8.3. However, they use the following definitions for the essential internal methods of function objects.
When the [[Call]] internal method of an exotic bound function object, F, which was created using the bind function is called with parameters thisArgument and argumentsList, a List of ECMAScript language values, the following steps are taken:
When the [[Construct]] internal method of an exotic bound function object, F that was created using the bind function is called with a list of arguments ExtraArgs, the following steps are taken:
The abstract operation BoundFunctionCreate with arguments targetFunction, boundThis and boundArgs is used to specify the creation of new Object objects. It performs the following steps:
An Array object is an exotic object that gives special treatment to a certain class of property names. A property
name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P
and ToUint32(P) is not equal to 232−1. A property whose property name is an array index is also
called an element. Every Array object has a length property whose value is always a nonnegative integer
less than 232. The value of the length property is
numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is
created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property
is added whose name is an array index, the length property is changed, if necessary, to be one more than the
numeric value of that array index; and whenever the length property is changed, every property whose name is an
array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own
properties of an Array object and is unaffected by length or array index properties that may be inherited from
its prototypes.
Exotic Array objects have the same internal data properties as ordinary objects. They also have an [[ArrayInitializationState]] internal data property.
Exotic Array objects always have a non-configurable property named "length".
Exotic Array objects provide alternative definitions for the [[Set]] and [[DefineOwnProperty]] internal methods. Except for these two internal methods, exotic Array objects provide all of the other essential internal methods as specified in 8.3.
When the [[DefineOwnProperty]] internal method of an exotic Array object A is called with property P, and Property Descriptor Desc the following steps are taken:
The abstract operation ArrayCreate with argument length (a positive integer or undefined) and optional argument proto is used to specify the creation of new exotic Array objects. It performs the following steps:
"length" and Property Descriptor {[[Value]]:
length, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false}.When the abstract operation ArraySetLength is called with an exotic Array object A, and Property Descriptor Desc the following steps are taken:
A String object is an exotic object that encapsulates a String value and exposes virtual array index data properties corresponding to the individual code unit elements of the string value. Exotic String objects always have a data property named "length" whose value is the number of code unit elements in the encapsulated String value. Both the code unit data properties and the "length" property are non-writable and non-configurable.
Exotic String objects have the same internal data properties as ordinary objects. They also have a [[StringData]] internal data property.
Exotic String objects provide alternative definitions for the following internal methods. All of the other exotic String object essential internal methods that are not defined below are as specified in 8.3.
When the [[HasOwnProperty]] internal method of exotic String object O is called with property key P, the following steps are taken:
When the [[GetOwnProperty]] internal method of an an exotic String object S is called with property key P the following steps are taken:
When the [[DefineOwnProperty]] internal method of an exotic String object O is called with property P, and Property Descriptor Desc the following steps are taken:
NOTE This algorithm differs from the ordinary object OrdinaryDefineOwnProperty abstract operation algorithm only in invocation of [[GetOwnProperty]] in step 1.
When the [[Enumerate]] internal method of an exotic String object O is called the following steps are taken:
When the [[OwnPropertyKeys]] internal method of an exotic String object O is called the following steps are taken:
The abstract operation StringCreate with argument prototype (is used to specify the creation of new exotic String objects. It performs the following steps:
A Symbol object is an exotic object that may be used as a property key. Symbol exotic objects are unique in that they are always immutable and never observably reference any other object.
Exotic String objects have a single internal data properties named [[Private]] that is set when the object is created and never modified.
Exotic Symbol objects provide alternative definitions for all of the essential internal methods.
When the [[GetInheritance]] internal method of an exotic Symbol object O is called the following steps are taken:
When the [[SetInheritance]] internal method of an exotic Symbol object O is called with argument V the following steps are taken:
When the [[HasIntegrity]] internal method of an exotic Symbol object O is called the following steps are taken:
nonextensible", "sealed", or "frozen".When the [[Setntegrity]] internal method of an exotic Symbol object an exotic Symbol object O is called the following steps are taken:
nonextensible", "sealed", or "frozen".When the [[HasOwnProperty]] internal method of an exotic Symbol object O is called with property key P, the following steps are taken:
When the [[GetOwnProperty]] internal method of an exotic Symbol object O is called with property key P, the following steps are taken:
When the [[DefineOwnProperty]] internal method of an exotic Symbol object O is called with property key P and property descriptor Desc, the following steps are taken:
When the [[HasProperty]] internal method of an exotic Symbol object O is called with property key P, the following steps are taken:
When the [[Get]] internal method of an exotic Symbol object O is called with property key P and ECMAScipt language value Receiver the following steps are taken:
When the [[Set]] internal method of an exotic Symbol object O is called with property key P, value V, and ECMAScipt language value Receiver, the following steps are taken:
When the [[Delete]] internal method of an exotic Symbol object O is called with property key P the following steps are taken:
When the [[Enumerate]] internal method of an exotic Symbol object O is called the following steps are taken:
When the [[OwnPropertyKeys]] internal method of an exotic Symbol object O is called the following steps are taken:
An arguments object is an exotic object whose array index properties map to the formal parameters bindings of an invocation of a non-strict function.
Exotic arguments objects have the same internal data properties as ordinary objects. They also have a [[ParameterMap]] internal data property and a [[BuiltinBrand]] internal data property whose value is BuiltinArguments.
Exotic arguments objects provide alternative definitions for the following internal methods. All of the other exotic arguments object essential internal methods that are not defined below are as specified in 8.3.
A Indexed Delegation object is an exotic object that that delegates [[Get]] and [[Set]] handling of array index property keys to methods of the object.
Indexed Delegation objects initially have the same internal data properties as ordinary objects.
Exotic Indexed Delegation objects provide alternative definitions for the following internal methods. All of the other exotic Indexed Delegation object essential internal methods that are not defined below are as specified in 8.3.
When the [[Get]] internal method of an exotic indexed delegation object O is called with property key P and ECMAScipt language value Receiver the following steps are taken:
When the [[Set]] internal method of an an exotic indexed delegation object O is called with property key P, value V, and ECMAScipt language value Receiver, the following steps are taken:
The abstract operation IndexedDelegatorCreate with argument prototype is used to specify the creation of new exotic Indexed Delegation objects. It performs the following steps:
The function objects specified in Clause 15 may be implemented as either ordinary function objects whose behaviour is provided using ECMAScript code or as implementation provided exotic function objects whose behaviour is provide in some other manner. In either case, the effect of calling such functions must be that specified for each one in Clause 15.
If an implementation provided exotic object is used, the object must have the ordinary object behaviour specified in 8.3 except for [[Get]] and [[GetOwnProperty]] which must be as specified in 8.3.19. All such exotic function objects also have [[Prototype]] and [[Extensible]] internal data properties and a [[BuiltinBrand]] internal data property whose value is BuiltinFunction.
[[Calll]] and [[Construct]]
A proxy object is an exotic object whose essential internal methods are partially implemented using ECMAScript code. Every proxy objects has an internal data property called [[ProxyHandler]]. The value of [[ProxyHandler]] is always an object, called the proxy’s handler object. Methods of a handler object may be used to augment the implementation for one or more of the proxy object’s internal methods. Every proxy object also has an internal data property called [[ProxyTarget]] whose value is either an object or the null value. This object is called the proxy’s target object.
When a handler method is called to provide the implementation of a proxy object internal method, the handler method is passed the proxy’s target object as a parameter. A proxy’s handler object does not necessarily have a method corresponding to every essential internal method. Invoking an internal method on the proxy results in the invocation of the corresponding internal method on the proxy’s target object if the handler object does not have a method corresponding to the internal trap.
The [[ProxyHandler]] and [[ProxyTarget]] internal data properties of a proxy object are always initialized when the object is created and typically may not be modified. Some proxy objects are created in a manner that permits them to be subsequently revoked. When a proxy is revoked, its [[ProxyHander]] internal data property is set to a special revoked proxy handler object and its [[ProxyTarget]] internal data property is set to null.
Because proxy permit arbitrary ECMAScript code to be used to in the implementation of internal methods, it is possible to define a proxy object whose handler methods violates the invariants defined in 8.1.6.2. Some of the internal method invariants defined in 8.1.6.2 are essential integrity invariants. These invariants are explicitly enforced by the proxy internal methods specified in this section. An ECMAScript implementation must be robust in the presence of all possible invariant violations.
In the following algorithm descriptions, assume O is an ECMAScript proxy object, P is a property key value, V is any ECMAScript language value, Desc is a Property Description record, and B is a Boolean flag.
When the [[GetInheritance]] internal method of an exotic Proxy object O is called the following steps are taken:
getPrototypeOf").NOTE [[GetInheritance]] for proxy objects enforces the following invariant:
[[GetInheritance]] applied to the proxy object must return the same value as [[GetInheritance] applied to the proxy object’s target object.
8.5.2 [[SetInheritance]] (V)
When the [[SetInheritance]] internal method of an exotic Proxy object O is called with argument V the following steps are taken:
setPrototypeOf").NOTE [[SetInheritance]] for proxy objects enforces the following invariant:
[[SetInheritance]] may only return true if the argument value is now the valued return for [[GetInheritance] applied to the proxy object’s target object.
When the [[HasIntegrity]] internal method of an exotic Proxy object O is called the following steps are taken:
nonextensible", "sealed", or "frozen".nonextensible", then let trapName be "isExtensible".sealed ", then let trapName be "isSealed".frozen ", so let trapName be "isFrozen".NOTE [[HasIntegrity]] for proxy objects enforces the following invariant:
[[HasIntegrity]] applied to the proxy object must return the same value as [[HasIntegrity]] applied to the proxy object’s target object with the same argument.
When the [[Setntegrity]] internal method of an exotic Proxy object O is the following steps are taken:
nonextensible", "sealed", or "frozen".nonextensible", then let trapName be "preventExtensions".sealed ", then let trapName be "seal".frozen ", so let trapName be "freeze".NOTE [[SetIntegrity]] for proxy objects enforces the following invariant:
[[SetIntegrity]] applied to the proxy object must return the same value as [[HasIntegrity]] applied to the proxy object’s target object with the same argument
When the [[HasOwnProperty]] internal method of an exotic Proxy object O is called with property key P, the following steps are taken:
hasOwn").NOTE [[HasOwnProperty]] for proxy objects enforces the following invariants:
A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
A property cannot be reported as non-existent, if it exists as a own property of the target object and the target object is not extensible.
A property cannot be reported as existent, if it does not exists as a own property of the target object and the target object is not extensible.
When the [[GetOwnProperty]] internal method of an exotic Proxy object O is called with property key P, the following steps are taken:
getOwnPropertyDescriptor").NOTE [[GetOwnProperty]] for proxy objects enforces the following invariants:
The result of [[GetOwnProperty]] must be either an Object or undefined.
A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
A property cannot be reported as non-existent, if it exists as a own property of the target object and the target object is not extensible.
A property cannot be reported as existent, if it does not exists as a own property of the target object and the target object is not extensible.
A property cannot be reported as non-configurable, if it does not exists as a own property of the target object or if it exists as a configurable own property of the target object.
The result of [[GetOwnProperty]] can be applied to the target object using [[DefineOwnPropery]] and will not throw an exception.
When the [[DefineOwnProperty]] internal method of an exotic Proxy object O is called with property key P and property descriptor Desc, the following steps are taken:
defineProperty").NOTE [[GetOwnProperty]] for proxy objects enforces the following invariants:
A property cannot be added, if the target object is not extensible.
A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object.
A property may not be non-configurable, if is corresponding configurable property of the target object exists.
If a property has a corresponding target object property then apply the property descriptor of the property to the target object using [[DefineOwnPropery]] will not throw an exception.
When the [[HasProperty]] internal method of an exotic Proxy object O is called with property key P, the following steps are taken:
has").NOTE [[HasProperty] for proxy objects enforces the following invariants:
A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
A property cannot be reported as non-existent, if it exists as a own property of the target object and the target object is not extensible.
When the [[Get]] internal method of an exotic Proxy object O is called with property key P and ECMAScipt language value Receiver the following steps are taken:
get").NOTE [[GetP] for proxy objects enforces the following invariants:
The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable data property.
The value reported for a property must be undefined if the corresponding corresponding target object property is non-configurable accessor property that has undefined as its [[Get]] attribute.
When the [[Set]] internal method of an exotic Proxy object O is called with property key P, value V, and ECMAScipt language value Receiver, the following steps are taken:
set").NOTE [[Set]] for proxy objects enforces the following invariants:
Cannnot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.
Cannot set the value of a property if the corresponding corresponding target object property is a non-configurable accessor property that has undefined as its [[Set]] attribute.
When the [[Delete]] internal method of an exotic Proxy object O is called with property name P the following steps are taken:
deleteProperty").NOTE [[Delete]] for proxy objects enforces the following invariant:
A property cannot be deleted, if it exists as a non-configurable own property of the target object.
When the [[Enumerate]] internal method of an exotic Proxy object O is called the following steps are taken:
enumerate").TODO: we may need to add a lot of additional invariant checking here according to the wiki spec. But maybe it really isn’t necessary. Tomvc response: I think it may be possible to waive the extra invariant checks for [[Enumerate]]. It's not a crucial primitive. My reasoning is that [[Enumerate]] deals with both own and inherited properties, and we don't really enforce any invariants on inherited properties. So I guess it's ok if the invariants for [[Enumerate]] are weakened.
Do note that this is a bit inconsistent with the way we treat internal methods like [[HasProperty]], [[GetP]] and [[SetP]]: these also deal with own and inherited properties, but still enforce invariants on own properties.
NOTE [[Enumerate] for proxy objects enforces the following invariants:
When the [[OwnPropertyKeys]] internal method of an exotic Proxy object O is called the following steps are taken:
ownKeys").NOTE [[OwnPropertyKeys] for proxy objects enforces the following invariants:
The [[Call]] internal method of an exotic Proxy object O is called with parameters thisArgument and argumentsList, a List of ECMAScript language values. The following steps are taken:
apply").NOTE An Proxy exotic object only has a [[Call]] internal method if the initial value of its [[ProxyTarget]] internal data property is an object that has a [[Call]] internal method.
The [[Construct]] internal method of an exotic Proxy object O is called with a single parameter argumentsList which is a possibly empty List of ECMAScript language values. The following steps are taken:
construct").NOTE An Proxy exotic object only has a [[Construct]] internal method if the initial value of its [[ProxyTarget]] internal data property is an object that has a [[Construct]] internal method.
These operations are not a part of the ECMAScript language; they are defined here to solely to aid the specification of the semantics of the ECMAScript Language. Other, more specialized abstract operations are defined throughout this specification.
The ECMAScript language implicitly performs automatic type conversion as needed. To clarify the semantics of certain constructs it is useful to define a set of conversion abstract operations.. The conversion abstract operations are polymorphic; that is, they can accept a value of any ECMAScript language type, but not of specification types.
The abstract operation ToPrimitive takes an input argument and an optional argument PreferredType. The abstract operation ToPrimitive 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. Conversion occurs according to Table 15:
| Input Type | Result |
|---|---|
| Completion Record | If argument is an abrupt completion, return argument. Otherwise return ToPrimitive(argument.[[value]]) also passing the optional hint PreferredType. |
| Undefined | Return argument (no conversion). |
| Null | Return argument (no conversion). |
| Boolean | Return argument (no conversion). |
| Number | Return argument (no conversion). |
| String | Return argument (no conversion). |
| Object | Perform the steps following this table. |
When the InputType is Object, the following steps are taken:
default".string".number".default" then, let hint be "number".When the OrdinaryToPrimitive is called with arguments O and hint, the following steps are taken:
string" or
"number".string", then
toString".valueOf".valueOf".toString".NOTE When ToPrimitive is called with no hint, then it generally behaves as if the hint were Number. However, objects may over-ride this behaviour by defining a @@ToPrimitve method. Of the objects defined in this specification only Date objects (see 15.9.6) over-ride the default ToPrimitive behaviour. Date objects treat no hint as if the hint were String.
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 16:
| Argument Type | Result |
|---|---|
| Completion Record | If argument is an abrupt completion, return the argument. Otherwise return ToBoolean(argument.[[value]]) |
| Undefined | Return false |
| Null | Return false |
| Boolean | Return the input argument (no conversion). |
| Number | Return false if the argument is +0, −0, or NaN; otherwise return true. |
| String | Return false if the argument is the empty String (its length is zero); otherwise return true. |
| Object | Return true |
The abstract operation ToNumber converts its argument to a value of type Number according to Table 17:
| Argument Type | Result |
|---|---|
| Completion Record | If argument is an abrupt completion, return argument. Otherwise return ToNumber(argument.[[value]]) |
| Undefined | Return NaN |
| Null | Return +0 |
| Boolean | Return 1 if argument is true. Return +0 if argument is false. |
| Number | Return argument (no conversion). |
| String | See grammar and note below. |
| Object |
Apply the following steps:
|
ToNumber applied to Strings applies the following grammar to the input String. If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.
+ StrUnsignedDecimalLiteral- StrUnsignedDecimalLiteral. DecimalDigitsopt ExponentPartopt. DecimalDigits ExponentPartopt0 1 2 3 4 5 6 7 8 9e E+ DecimalDigits- DecimalDigits0x HexDigit0X HexDigit0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E FNOTE Some differences should be noted between the syntax of a StringNumericLiteral and a NumericLiteral (see 7.8.3):
A StringNumericLiteral may be preceded and/or followed by white space and/or line terminators.
A StringNumericLiteral that is decimal may have any number of leading 0
digits.
A StringNumericLiteral that is decimal may be preceded by + or
- to indicate its sign.
A StringNumericLiteral that is empty or contains only white space is converted to +0.
Infinity and –Infinity are recognized as a StringNumericLiteral but not as a NumericLiteral.
Runtime Semantics
The conversion of a String to a Number value is similar overall to the determination of the Number value for a numeric literal (see 7.8.3), but some of the details are different, so the process for converting a String numeric literal to a value of Number type is given here in full. This value is determined in two steps: first, a mathematical value (MV) is derived from the String numeric literal; second, this mathematical value is rounded as described below.
The MV of StringNumericLiteral ::: [empty] is 0.
The MV of StringNumericLiteral ::: StrWhiteSpace is 0.
The MV of StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt is the MV of StrNumericLiteral, no matter whether white space is present or not.
The MV of StrNumericLiteral ::: StrDecimalLiteral is the MV of StrDecimalLiteral.
The MV of StrNumericLiteral ::: HexIntegerLiteral is the MV of HexIntegerLiteral.
The MV of StrDecimalLiteral ::: StrUnsignedDecimalLiteral is the MV of StrUnsignedDecimalLiteral.
The MV of StrDecimalLiteral ::: + StrUnsignedDecimalLiteral is the MV of StrUnsignedDecimalLiteral.
The MV of StrDecimalLiteral ::: - StrUnsignedDecimalLiteral is the negative of the MV of StrUnsignedDecimalLiteral. (Note that if the MV of StrUnsignedDecimalLiteral
is 0, the negative of this MV is also 0. The rounding rule described below handles the conversion of this signless
mathematical zero to a floating-point +0 or −0 as appropriate.)
The MV of StrUnsignedDecimalLiteral ::: Infinity is 1010000 (a value so large that it will round to +∞).
The MV of StrUnsignedDecimalLiteral ::: DecimalDigits . is the MV of DecimalDigits.
The MV of StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigits is the MV of the
first DecimalDigits plus (the MV of the second DecimalDigits times
10−n), where n is the number of
characters in the second DecimalDigits.
The MV of StrUnsignedDecimalLiteral ::: DecimalDigits . ExponentPart is the MV of
DecimalDigits times 10e, where e is the MV of ExponentPart.
The MV of StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigits ExponentPart is (the MV of the first DecimalDigits plus (the MV of the second
DecimalDigits times 10−n)) times 10e, where n is the number of
characters in the second DecimalDigits and e is the MV of ExponentPart.
The MV of StrUnsignedDecimalLiteral ::: . DecimalDigits is the MV of DecimalDigits times
10−n, where n is the number of characters in DecimalDigits.
The MV of StrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPart is the MV of
DecimalDigits times 10e−n, where n is the number of characters in
DecimalDigits and e is the MV of ExponentPart.
The MV of StrUnsignedDecimalLiteral ::: DecimalDigits is the MV of DecimalDigits.
The MV of StrUnsignedDecimalLiteral ::: DecimalDigits ExponentPart is the MV of DecimalDigits times 10e, where e is the MV of ExponentPart.
The MV of DecimalDigits ::: DecimalDigit is the MV of DecimalDigit.
The MV of DecimalDigits ::: DecimalDigits DecimalDigit is (the MV of DecimalDigits times 10) plus the MV of DecimalDigit.
The MV of ExponentPart ::: ExponentIndicator SignedInteger is the MV of SignedInteger.
The MV of SignedInteger ::: DecimalDigits is the MV of DecimalDigits.
The MV of SignedInteger ::: + DecimalDigits is the MV of DecimalDigits.
The MV of SignedInteger ::: - DecimalDigits is the negative of the MV of DecimalDigits.
The MV of DecimalDigit ::: 0 or of HexDigit ::: 0 is 0.
The MV of DecimalDigit ::: 1 or of HexDigit ::: 1 is 1.
The MV of DecimalDigit ::: 2 or of HexDigit ::: 2 is 2.
The MV of DecimalDigit ::: 3 or of HexDigit ::: 3 is 3.
The MV of DecimalDigit ::: 4 or of HexDigit ::: 4 is 4.
The MV of DecimalDigit ::: 5 or of HexDigit ::: 5 is 5.
The MV of DecimalDigit ::: 6 or of HexDigit ::: 6 is 6.
The MV of DecimalDigit ::: 7 or of HexDigit ::: 7 is 7.
The MV of DecimalDigit ::: 8 or of HexDigit ::: 8 is 8.
The MV of DecimalDigit ::: 9 or of HexDigit ::: 9 is 9.
The MV of HexDigit ::: a or of HexDigit ::: A is 10.
The MV of HexDigit ::: b or of HexDigit ::: B is 11.
The MV of HexDigit ::: c or of HexDigit ::: C is 12.
The MV of HexDigit ::: d or of HexDigit ::: D is 13.
The MV of HexDigit ::: e or of HexDigit ::: E is 14.
The MV of HexDigit ::: f or of HexDigit ::: F is 15.
The MV of HexIntegerLiteral ::: 0x HexDigit is the MV of HexDigit.
The MV of HexIntegerLiteral ::: 0X HexDigit is the MV of HexDigit.
The MV of HexIntegerLiteral ::: HexIntegerLiteral HexDigit is (the MV of HexIntegerLiteral times 16) plus the MV of HexDigit.
Once the exact MV for a String numeric literal has been determined, it is then rounded to a value of the Number type.
If the MV is 0, then the rounded value is +0 unless the first non white space character in the String numeric literal is
‘-’, in which case the rounded value is −0. Otherwise, the rounded value must be the Number
value for the MV (in the sense defined in 8.5), unless the literal includes a StrUnsignedDecimalLiteral and the literal has more than 20 significant digits, in which case the Number
value may be either the Number value for the MV of a literal produced by replacing each significant digit after the 20th
with a 0 digit or the Number value for the MV of a literal produced by replacing each significant digit after the 20th
with a 0 digit and then incrementing the literal at the 20th digit position. A digit is significant if it is not
part of an ExponentPart and
The abstract operation ToInteger converts its argument to an integral numeric value. This abstract operation functions as follows:
The abstract operation ToInt32 converts its argument to one of 232 integer values in the range −231 through 231−1, inclusive. This abstract operation functions as follows:
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 equal to ToInt32(x) for all values of x. (It is to preserve this latter property that +∞ and −∞ are mapped to +0.)
ToInt32 maps −0 to +0.
The abstract operation ToUint32 converts its argument to one of 232 integer values in the range 0 through 232−1, inclusive. This abstract operation functions as follows:
NOTE Given the above definition of ToUInt32:
Step 6 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 equal to ToUint32(x) for all values of x. (It is to preserve this latter property that +∞ and −∞ are mapped to +0.)
ToUint32 maps −0 to +0.
The abstract operation ToUint16 converts its argument to one of 216 integer values in the range 0 through 216−1, inclusive. This abstract operation functions as follows:
NOTE Given the above definition of ToUint16:
The abstract operation ToString converts its argument to a value of type String according to Table 18:
| Argument Type | Result |
|---|---|
| Completion Record | If argument is an abrupt completion, return argument. Otherwise return ToString(argument.[[value]]) |
| Undefined | "undefined" |
| Null | "null" |
| Boolean |
If argument is true, then return If argument is false, then return "false". |
| Number | See 9.8.1. |
| String | Return argument (no conversion) |
| Object |
Apply the following steps: 1. Let primValue be ToPrimitive(argument, hint String). 2. Return ToString(primValue). |
The abstract operation ToString converts a Number m to String format as follows:
"NaN"."0"."-" and ToString(−m)."Infinity".0’..’, followed by the remaining
k−n digits of the decimal representation of s.0’,
followed by a decimal point ‘.’, followed by −n occurrences of the character
‘0’, followed by the k digits of the decimal representation of s.e’, followed by a plus sign ‘+’ or minus sign
‘−’ according to whether n−1 is positive or negative, followed by the
decimal representation of the integer abs(n−1) (with no leading zeroes).e’, followed by a plus sign
‘+’ or minus sign ‘−’ according to whether n−1
is positive or negative, followed by the decimal representation of the integer abs(n−1) (with no leading zeroes).NOTE 1 The following observations may be useful as guidelines for implementations, but are not part of the normative requirements of this Standard:
NOTE 2 For implementations that provide more accurate conversions than required by the rules above, it is recommended that the following alternative version of step 5 be used as a guideline:
Otherwise, let n, k, and s be integers such that k ≥ 1, 10k−1 ≤ s < 10k, the Number value for s × 10n−k is m, and k is as small as possible. If there are multiple possibilities for s, choose the value of s for which s × 10n−k is closest in value to m. If there are two such possible values of s, choose the one that is even. Note that k is the number of digits in the decimal representation of s and that s is not divisible by 10.
NOTE 3 Implementers of ECMAScript may find useful the paper and code written by David M. Gay for binary-to-decimal conversion of floating-point numbers:
Gay, David M. Correctly Rounded Binary-Decimal and Decimal-Binary Conversions. Numerical Analysis, Manuscript 90-10.
AT&T Bell Laboratories (Murray Hill, New Jersey). November 30, 1990. Available as
http://cm.bell-labs.com/cm/cs/doc/90/4-10.ps.gz. Associated
code available as
http://netlib.sandia.gov/fp/dtoa.c and as
http://netlib.sandia.gov/fp/g_fmt.c and may also be found at the various
netlib mirror sites.
The abstract operation ToObject converts its argument to a value of type Object according to Table 19:
| Argument Type | Result |
|---|---|
| Completion Record | If argument is an abrupt completion, return argument. Otherwise return ToObject(argument.[[value]]) |
| Undefined | Throw a TypeError exception. |
| Null | Throw a TypeError exception. |
| Boolean | Return a new Boolean object whose [[BooleanData]] internal data property is set to the value of argument. See 15.6 for a description of Boolean objects. |
| Number | Return a new Number object whose [[NumberData]] internal data property is set to the value of argument. See 15.7 for a description of Number objects. |
| String | Return a new String object whose [[StringData]] internal data property is set to the value of argument. See 15.5 for a description of String objects. |
| Object | Return argument (no conversion). |
The abstract operation ToPropertyKey converts its argument to a value that can be used as a property key by performing the following steps:
The abstract operation ToInteger converts its argument to an integral numeric value. This abstract operation functions as follows:
The abstract operation CheckObjectCoercible throws an error if its argument is a value that cannot be converted to an Object using ToObject. It is defined by Table 20:
| Argument Type | Result |
|---|---|
| Completion Record | If argument is an abrupt completion, return argument. Otherwise return CheckObjectCoercible(argument.[[value]]) |
| Undefined | Throw a TypeError exception. |
| Null | Throw a TypeError exception. |
| Boolean | Return argument |
| Number | Return argument |
| String | Return argument |
| Object | Return argument |
The abstract operation IsCallable determines if its argument, which must be an ECMAScript language value or a Completion Record, is a callable function Object according to Table 21:
| Argument Type | Result |
|---|---|
| Completion Record | If argument is an abrupt completion, return argument. Otherwise return IsCallable(argument.[[value]]) |
| Undefined | Return false. |
| Null | Return false. |
| Boolean | Return false. |
| Number | Return false. |
| String | Return false. |
| Object | If argument has a [[Call]] internal method, then return true, otherwise return false. |
The internal comparison abstract operation SameValue(x, y), where x and y are ECMAScript language values, produces true or false. Such a comparison is performed as follows:
The internal comparison abstract operation SameValueZero(x, y), where x and y are ECMAScript language values, produces true or false. Such a comparison is performed as follows:
NOTE SameValueZero differs from SameValue only in its treatment of +0 and -0.
The abstract operation IsConstructor determines if its argument, which must be an ECMAScript language value or a Completion Record, is a function object with a [[Construct]] internal method.
The abstract operation IsPropertyKey determine if its argument, which must be an ECMAScript language value or a Completion Record, is a value that may be used as a property key.
The abstract operation IsExtensible is used to determine whether additional properties an be added to an object. A Boolean value is return. The operation is called with argument O where O is the object. This abstract operation performs the following steps:
nonextensible".The abstract operation Get is used to retrieve the value of an specific property of an object. The operation is called with arguments O and P where O is the object and P is the property key. This abstract operation performs the following steps:
The abstract operation Put is used to set the value of a specific property of an object. The operation is called with arguments O, P, V, and Throw where O is the object, P is the property key, V is the new value for the property and Throw is a Boolean flag. This abstract operation performs the following steps:
The abstract operation CreateOwnProperty is used to create a new own property of an object. The operation is called with arguments O, P, and V where O is the object, P is the property key, and V is the new value for the property. This abstract operation performs the following steps:
nonextensible".The abstract operation DefinePropertyOrThrow is used to call the [[DefineOwnProperlty]] internal method of an object in a manner that will throw a TypeError exception if the requested property update can not be performed. The operation is called with arguments O, P, and desc where O is the object, P is the property key, and desc is the Property Descriptor for the property. This abstract operation perform, the following steps:
The abstract operation Put is used to remove a specific own property of an object. It throws an exception is the property is not configurable. The operation is called with arguments O and P where O is the object and P is the property key. This abstract operation performs the following steps:
The abstract operation HasProperty is used to determine whether an object has a property with the specified property key. The property may be either an own or inherited. A Boolean value is return. The operation is called with arguments O and P where O is the object and P is the property key. This abstract operation performs the following steps:
The abstract operation GetMethod is used to get the value of an specific property of an object when the value of the property is expected to be a function. The operation is called with arguments O and P where O is the object, P is the property key. This abstract operation performs the following steps:
The abstract operation Invoke is used to call a method property of an object. The operation is called with arguments P, O, and optionally args where P is the property key, O serves as both the lookup point for the property and the this value of the call, and args is the list of arguments values passed to the method. If args is not present, an empty List is used as its value. This abstract operation performs the following steps:
The abstract operation SetIntegrityLevel is used to fix the set of own properties of an object. This abstract operation performs the following steps:
sealed" or "frozen".sealed", then
frozen",
The abstract operation TestIntegrityLevel is used to determine if the set of own properties of an object are fixed. This abstract operation performs the following steps:
sealed" or "frozen".frozen"and writable is true, then return false.The abstract operation CreateArrayFromList is used to create an Array object whose elements are provided by an internal List. This abstract operation performs the following steps:
The abstract operation OrdinaryHasInstance implements the default algorithm for determining if an object O inherits from the inheritance path used by constructor C. This abstract operation performs the following steps:
"prototype").null, return false.The abstract operation GetPrototypeFromConstructor determines the
[[Prototype]] value that should be used to create an object corresponding to a specific constructor. The value is retrieved
from theconstructor’s prototype property, if it exists. Otherwise the supplied default is used for
[[Prototype]]. This abstract operation performs the following steps:
"prototype").NOTE If constructor does not supply a [[Prototype]] value, the default value that is used is obtained from the Code Realm of the constructor function rather than from the running execution context. This accounts for the possibility that a built-in @@create method from a different Code Realm might be installed on constructor.
The abstract operation OrdinaryCreateFromConstructor creates an
ordinary object whose [[Prototype]] value is retrieved from a constructor’s prototype property, if it
exists. Otherwise the supplied default is used for [[Prototype]]. The optional internalDataList is a List of the names of internal data property names that should be defined as part of the object. If the
list is not provided, an empty List is used. This abstract operation performs the following
steps:
There are five types of ECMAScript executable code:
Global code is source text that is treated as an ECMAScript Script. The global code of a particular Script does not include any source text that is parsed as part of a FunctionBody, ConciseBody, ClassBody, or ModuleBody.
Eval code is the source text supplied to the built-in eval function. More precisely, if the
parameter to the built-in eval function is a String, it is treated as an ECMAScript Script. The eval
code for a particular invocation of eval is the global code portion of that Script.
Function code is source text that is parsed to supply the value of the [[Code]] internal data property (see 13.6) of function and generator objects. The function code of a particular function or generator does not include any source text that is parsed as the function code of a nested FunctionBody, ConciseBody, or ClassBody..
Generator code is source text that is parsed to supply the value of the [[Code]] internal data property (see 13.5) of generator objects. The generator code of a particular generator does not include any source text that is parsed as the function code of a nested FunctionBody, ConciseBody, or ClassBody. All generator code is also considered to be function code, but only function code that is defined within a generator is generator code.
Module code is source text that is parse code that is provided as a ModuleBody. It is the code that is directly evaluated when a module is initialized. The module code of a particular module does not include any source text that is parsed as part of a nested FunctionBody, ConciseBody, ClassBody, or ModuleBody..
NOTE Function code is generally provided as the bodies of Function Definitions (13.1), Arrow Function Definditions (13.2), Method Definitions (13.3) and Generator Definitions (13.4). Function code is also derived from the last argument to the Function constructor (15.3). Generator code is provided as the bodies of Generator Definitions 13.4 and Generator Expressions (11.????).
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. When processed using strict mode the three types of ECMAScript code are referred to as strict global code, strict eval code, and strict function code. Code is interpreted as strict mode code in the following situations:
Global code is strict global code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1).
Module code is always strict code.
All code contained in a ClassBody is strict code.
Eval code is strict eval code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct call (see 15.1.2.1.1) to the eval function that is contained in strict mode code.
Function code that is part of a FunctionDeclaration, FunctionExpression, or accessor PropertyDefinition is strict function code if its FunctionDeclaration, FunctionExpression, or PropertyDefinition is contained in strict mode code or if the function code begins with a Directive Prologue that contains a Use Strict Directive.
Function code that is supplied as the last argument to the built-in Function constructor is strict function code if the last argument is a String that when processed as a FunctionBody begins with a Directive Prologue that contains a Use Strict Directive.
An ECMAScript implementation may support the evaluation of function objects whose evaluative behaviour is expressed in some implementation defined form of executable code other than via ECMAScript code. Whether a function object is an ECMAScript code function or a non-ECMAScript function is not semantically observable from the perspective of an ECMAScript code function that calls or is called by such a non-ECMAScript function.
A Lexical Environment 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. A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment. Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.
An Environment Record records the identifier bindings that are created within the scope of its associated Lexical Environment.
The outer environment reference is used to model the logical nesting of Lexical Environment values. The outer reference of a (inner) Lexical Environment is a reference to the Lexical Environment that logically surrounds the inner Lexical Environment. An outer Lexical Environment may, of course, have its own outer Lexical Environment. A Lexical Environment may serve as the outer environment for multiple inner Lexical Environments. For example, if a FunctionDeclaration contains two nested FunctionDeclarations then the Lexical Environments of each of the nested functions will have as their outer Lexical Environment the Lexical Environment of the current evaluation of the surrounding function.
A global environment is a Lexical Environment which does not have an outer environment. The global
environment’s outer environment reference is null. A global environment’s environment record may be
prepopulated with identifier bindings and includes an associated global object whose properties provide some of the global environment’s identifier bindings. This global object is the value of a global
environment’s this binding. As ECMAScript code is executed, additional properties may be added to the
global object and the initial properties may be modified.
A method environment is a Lexical Environment that corresponds to the invocation of an ECMAScript function object that
establishes a new this binding. A method environment also captures the state necessary to support
super method invocations.
Lexical Environments and Environment Record values 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.
There are two primary kinds of Environment Record values used in this specification: declarative environment records and object environment records. Declarative environment records are used to define the effect of ECMAScript language syntactic elements such as FunctionDeclarations, VariableDeclarations, and Catch clauses that directly associate identifier bindings with ECMAScript language values. Object environment records are used to define the effect of ECMAScript elements such as WithStatement that associate identifier bindings with the properties of some object. Global Environment Records and Function Environment Records are specializations that are used for specifically for Script global declarations and for top-level declarations within funtions.
For specification purposes Environment Record values 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 are a subclass of declarative environment record. The abstract class includes the abstract specification methods defined in Table 22. These abstract methods have distinct concrete algorithms for each of the concrete subclasses.
| Method | Purpose |
|---|---|
| HasBinding(N) | Determine if an environment record has a binding for an identifier. Return true if it does and false if it does not. The String value N is the text of the identifier. |
| CreateMutableBinding(N, D) | Create a new but uninitialised mutable binding in an environment record. The String value N is the text of the bound name. If the optional Boolean argument D is true the binding is may be subsequently deleted. |
| CreateImmutableBinding(N) | Create a new but uninitialised immutable binding in an environment record. The String value N is the text of the bound name. |
| InitializeBinding(N,V) | Set the value of an already existing but uninitialised 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. S is used to identify strict mode references. |
| 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 strict mode references. If S is true and the binding does not exist or is uninitialised throw a ReferenceError exception. |
| DeleteBinding(N) | Delete a binding from an environment record. The String value N is the text of the bound name If a binding for N exists, remove the binding and return true. If the binding exists but cannot be removed return false. If the binding does not exist return true. |
| HasThisBinding() | Determine if an environment record establishes a this binding. Return true if it does and false if it does not. |
| HasSuperBinding() | Determine if an environment record establishes a super method binding. Return true if it does and false if it does not. |
| WithBaseObject () | If this environment record is associated with a with statement, return the with object. Otherwise, return undefined. |
Each declarative environment record is associated with an ECMAScript program scope containing variable, constant, let, class, module, import, and/or function declarations. A declarative environment record binds the set of identifiers defined by the declarations contained within its scope.
The behaviour of the concrete specification methods for Declarative Environment Records is defined by the following algorithms.
The concrete environment record method HasBinding for declarative environment records simply determines if the argument identifier is one of the identifiers bound by the record:
The concrete Environment Record method CreateMutableBinding for declarative environment records creates a new mutable binding for the name N that is uninitialised. A binding must not already exist in this Environment Record for N. If Boolean argument D is provided and has the value true the new binding is marked as being subject to deletion.
The concrete Environment Record method CreateImmutableBinding for declarative environment records creates a new immutable binding for the name N that is uninitialised. A binding must not already exist in this environment record for N.
The concrete Environment Record method InitializeBinding for declarative environment records is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialised binding for N must already exist.
The concrete Environment Record method SetMutableBinding for declarative environment records attempts to change the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. A binding for N must already exist. If the binding is an immutable binding, a TypeError is thrown if S is true.
The concrete Environment Record method GetBindingValue for declarative environment records simply returns the value of its bound identifier whose name is the value of the argument N. The binding must already exist. If S is true and the binding is an uninitialised immutable binding throw a ReferenceError exception.
The concrete Environment Record method DeleteBinding for declarative environment records can only delete bindings that have been explicitly designated as being subject to deletion.
Regular Declarative Environment Records do not provide a this binding.
Regular Declarative Environment Records do not provide a super binding.
Declarative Environment Records always return undefined as their WithBaseObject.
Each object environment record is associated with an object called its binding object. An object environment record binds the set of identifier names that directly correspond to the property names of its binding object. Property names that are not an IdentifierName are not included in the set of bound identifiers. Both own and inherited properties are included in the set regardless of the setting of their [[Enumerable]] attribute. Because properties can be dynamically added and deleted from objects, the set of identifiers bound by an object environment record may potentially change as a side-effect of any operation that adds or deletes properties. Any bindings that are created as a result of such a side-effect are considered to be a mutable binding even if the Writable attribute of the corresponding property has the value false. Immutable bindings do not exist for object environment records.
Object environment records created for with statements (12.10) can provide their
binding object as an implicit this value for use in function calls. The capability is controlled by a
withEnvironment Boolean value that is associated with each object environment record.
By default, the value of withEnvironment is false for any object environment
record.
The behaviour of the concrete specification methods for Object Environment Records is defined by the following algorithms.
The concrete Environment Record method HasBinding for object environment records determines if its associated binding object has a property whose name is the value of the argument N:
The concrete Environment Record method CreateMutableBinding for object environment records creates in an environment record’s associated binding object a property whose name is the String value and initialises it to the value undefined. A property named N must not already exist in the binding object. If Boolean argument D is provided and has the value true the new property’s [[Configurable]] attribute is set to true, otherwise it is set to false.
The concrete Environment Record method CreateImmutableBinding is never used within this specification in association with Object environment records.
The concrete Environment Record method InitializeBinding for object environment records is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialised binding for N must already exist.
The concrete Environment Record method SetMutableBinding for object environment records attempts to set the value of the environment record’s associated binding object’s property whose name is the value of the argument N to the value of argument V. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by the value of the Boolean argument S.
The concrete Environment Record method GetBindingValue for object environment records returns the value of its associated binding object’s property whose name is the String value of the argument identifier N. The property should already exist but if it does not the result depends upon the value of the S argument:
The concrete Environment Record method DeleteBinding for object environment records can only delete bindings that correspond to properties of the environment object whose [[Configurable]] attribute have the value true.
Regular Object Environment Records do not provide a this binding.
Regular Object Environment Records do not provide a super binding.
Object Environment Records return undefined as their WithBaseObject unless their withEnvironment flag is true.
A function environment record is a declarative environment record that is used to represent
the outer most scope of a function that provides a this binding. In addition to its identifier bindings, a
function environment record contains the this value used within its scope. If such a function 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 store their this binding as the value of their thisValue. If the
associated function references super, the environment record stores in HomeObject the
object that the function is bound to as a method and in MethodName the property key used for unqualified super invocations from within the function. The default value for
HomeObject and MethodName is undefined.
Methods environment records support all of Declarative Environment Record methods listed in Table 22 and share the same specifications for all of those methods except for HasThisBinding and HasSuperBinding. In addition, declarative environment records support the methods listed in Table 23:
| Method | Purpose |
|---|---|
| GetThisBinding() | Return the value of this environment record’s this binding. |
| GetSuperBase() | Return the object that is the base for super property accesses bound in this environment record. The object is derived from this environment record’s HomeObject binding. If the value is Empty, return undefined. |
| GetMethodName() | Return the value of this environment record’s MethodName binding. |
The behaviour of the additional concrete specification methods for Function Environment Records is defined by the following algorithms:
Function Environment Records always provide a this binding.
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 (10.3). A global environment provides the bindings for built-in globals (15.1), properties of the global object, and for all declarations that are not function code and that occur within Script productions.
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. This global object is also the value of the global environment record’s thisValue. The object environment record component of a global environment record contains the bindings for all built-in globals (15.1) and all bindings introduced by a FunctionDeclaration 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 or VariableStatement declarations and binding created implicitly as properties of the global object. In order to identify which bindings were explicitly created using declarations, a global environment record maintains a list of the names bound using its CreateGlobalVarBindings and CreateGlobalFunctionBindings concrete methods.
Global environment records have the additional state components listed in Table 24 and the additional methods listed in Table 25.
| Component | Purpose |
|---|---|
| ObjectEnvironment | A Object Environment Record whose base object is the global object. Contains global built-in bindings as well as bindings for FunctionDeclaration or VariableStatement declarations in global code for the associated Realm. |
| DeclarativeEnvironment | A Declarative Environment Record that contains bindings for all declarations in global for the associated Realm code except for FunctionDeclaration and VariableStatement declarations. |
| VarNames | A List containing the string names bound by FunctionDeclaration or VariableStatement declarations in global code for the associated Realm. |
| Method | Purpose |
|---|---|
| GetThisBinding() | Return the value of this environment record’s this binding. |
| HasVarDeclaration (N) | Determines if the argument identifier has a binding in this environment record that was created using a VariableStatement or a FunctionDeclaration. |
| HasLexicalDeclaration (N) | Determines if the argument identifier has a binding in this environment record that was created using a lexical declaration such as a LexicalDeclaration or a ClassDeclaration : |
| CanDeclareGlobalVar (N) | Determines if a corresponding CreateGlobalVarBinding call would succeed if called for the same argument N. |
| CanDeclareGlobalFunction (N) | Determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N. |
| CreateGlobalVarBinding(N, D) | Used to create global var bindings in the ObjectEnvironmentComponent of the environment record. The binding will be a mutable binding. The corresponding global object property will have attribute values approate for a var. The String value N is the text of the bound name. V is the initial value of the binding If the optional Boolean argument D is true the binding is may be subsequently deleted. This is logically equivalent to CreateMutableBinding but it allows var declarations to receive special treatment. |
| CreateGlobalFunctionBinding(N, V, D) | Used to create and initialize global function bindings in the ObjectEnvironmentComponent of the environment record. The binding will be a mutable binding. The corresponding global object property will have attribute values approate for a function.The String value N is the text of the bound name. If the optional Boolean argument D is true the binding is may be subsequently deleted. This is logically equivalent to CreateMutableBinding followed by a SetMutableBinding but it allows function declarations to receive special treatment. |
The behaviour of the concrete specification methods for Global Environment Records is defined by the following algorithms.
The concrete environment record method HasBinding for global environment records simply determines if the argument identifier is one of the identifiers bound by the record:
The concrete environment record method CreateMutableBinding for global environment records creates a new mutable binding for the name N that is uninitialised. The binding is created in the associated DeclarativeEnvironment. A binding for N must not already exist in the DeclarativeEnvironment. If Boolean argument D is provided and has the value true the new binding is marked as being subject to deletion.
The concrete Environment Record method CreateImmutableBinding for declarative environment records creates a new immutable binding for the name N that is uninitialised. A binding must not already exist in this environment record for N.
The concrete Environment Record method InitializeBinding for global environment records is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialised binding for N must already exist.
The concrete Environment Record method SetMutableBinding for global environment records attempts to change the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. If the binding is an immutable binding, a TypeError is thrown if S is true. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by the value of the Boolean argument S.
The concrete Environment Record method GetBindingValue for global environment records simply returns the value of its bound identifier whose name is the value of the argument N. If S is true and the binding is an uninitialised 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 the value of the Boolean argument S.
The concrete Environment Record method DeleteBinding for global environment records can only delete bindings that have been explicitly designated as being subject to deletion.
Global Environment Records always provide a this binding whose value is the associated global
object.
Global Environment Records always return undefined as their WithBaseObject.
The concrete environment record method HasVarDeclaration for global environment records determines if the argument identifier has a binding in this record that was created using a VariableStatement or a FunctionDeclaration :
The concrete environment record method HasLexicalDeclaration for global environment records determines if the argument identifier has a binding in this record that was created using a lexical declaration such as a LexicalDeclaration or a ClassDeclaration :
The concrete environment record method CanDeclareGlobalVar for global environment records determines if a corresponding CreateGlobalVarBinding call would succeed if called for the same argument N. Redundent var declarations and var declarations for pre-existing global object properties are allowed.
The concrete environment record method CanDeclareGlobalVar for global environment records determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N.
The concrete Environment Record method CreateVarBinding for global environment records creates a mutable binding in the associated object environment record and records the bound name in the associated VarNames List. If a binding already exists, it is reused.
The concrete Environment Record method CreateFunctionBinding for global environment records creates a mutable binding in the associated object environment record and records the bound name in the associated VarNames List. If a binding already exists, it is replaced.
NOTE Global unction declarations are always represented as a own property of the global object. If possible, an existing own property is reconfigured to have a standard set of attribute values.
The following abstract operations are used in this specification to operate upon lexical environments:
The abstract operation GetIdentifierReference is called with a Lexical Environment lex, a String name, and a Boolean flag strict. The value of lex may be null. When called, the following steps are performed:
true, then
When the abstract operation NewDeclarativeEnvironment is called with either a Lexical Environment or null as argument E the following steps are performed:
When the abstract operation NewObjectEnvironment is called with an Object O and a Lexical Environment E (or null) as arguments, the following steps are performed:
When the abstract operation NewFunctionEnvironment is called with an ECMAScript function Object F and a ECMAScript value T as arguments, the following steps are performed:
Before it is evaluated, all ECMAScript code must be associated with a Realm. Conceptually, a realm consists as of an set of intrinsic objects, an ECMAScript global environment, all of the ECMAScript code that is loaded within the scope of that global environment, a Loader object that can associate new ECMAScript code with the realm, and other associated state and resources.
A Realm is specified as a Record with the fields specified in Table 26:
| Field Name | Value | Meaning |
|---|---|---|
| [[intrinsics]] | A record whose field names are intrinsic keys and whose values are objects | These are the intrinsic values used by code associated with this Realm |
| [[globalThis]] | An ECMAScript object | The global object for this Realm |
| [[globalEnv]] | A ECMAScript environment | The global environment for this Realm |
| [[loader]] | any ECMAScript identifier or empty | The Loader object that can associate ECMAScript code with this Realm |
The intrinsic objects associated with a code Realm include the well-known intrinsics listed in Table 11 and additional intrinsics specified by Table 27.
| Intrinsic Name | ECMAScript Language Association |
|---|---|
| ??? | ??? |
| ??? | ??? |
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 that is actually executing code. This is known as the running execution context. A 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 the state components listed in Table 28.
| Component | Purpose |
|---|---|
| code evaluation state | Any state needed to perform, suspend, and resume evaluation of the code associated with this execution context. |
| Realm | The Realm from which associated code accesses ECMAScript resources. |
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 latter 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.
Execution contexts for ECMAScript code have the additional state components listed in Table 29.
| Component | Purpose |
|---|---|
| LexicalEnvironment | Identifies the Lexical Environment used to resolve identifier references made by code within this execution context. |
| VariableEnvironment | Identifies the Lexical Environment whose environment record holds bindings created by VariableStatements within this execution context. |
The LexicalEnvironment and VariableEnvironment components of an execution context are always Lexical Environments. When an execution context is created its LexicalEnvironment and VariableEnvironment components initially have the same value. The value of the VariableEnvironment component never changes while the value of the LexicalEnvironment component may change during execution of code within an execution context.
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 an ECMAScript program to directly access or observe an execution context.
Identifier resolution is the process of determining the binding of an IdentifierName using the LexicalEnvironment of the running execution context. During execution of ECMAScript code, Identifier Resolution is performed using the following algorithm:
The result of evaluating an identifier is always a value of type Reference with its referenced name component equal to the Identifier String.
The abstract operation GetThisEnviroment finds the lexical environment that currently supplies the binding of the keyword this. GetThisEnviroment performs the following steps:
true, then return envRec.NOTE The loop in step 4 will always terminate because the llst of environment always end with
the global environment which has a this binding.
The abstract operation ThisResolution is the process of determining the
binding of the keyword this using the LexicalEnvironment of the running execution
context. ThisResolution performs the following steps:
The abstract operation GetGlobalObject returns the global object used by the currently running execution context. GetGlobalObject Performs the following steps:
NOTE When an execution context is established for evaluating scripts, declarations are instantiated in the current global environment. Each global binding declarated in the code is instantiated.
Global Declaration Instantiation is performed as follows using arguments script, env, and deletableBindings. script is the ScriptBody that for which the execution context is being established. env is the global environment record in which bindings are to be created. deletableBindings is true if the bindings that are created should be deletable.
NOTE Early errors specified in 14.1 prevent name conflicts between function/var declarations and let/const/class/module declarations as well as redeclaration of let/const/class/module bindings for declaration contained within a single Script. However, such conflicts and redeclarations that span more than one Script are detected as runtime errors during Global Declaration Instantiation. If any such errors are detected, no bindings are instantiated for the script.
Unlike explicit var or function declarations, properties that are directly created on the global object result in global bindings that may be shadowed by let, const, class, and module declarations.
This version reflects the concensus as of the Sept. 2012 TC39 meeting. However, it now appears that the binding semantics of formal parameters is like to change again.
NOTE When an execution context is established for evaluating function code a new Declarative Environment Record is created and bindings for each formal parameter, and each function level variable, constant, or function declarated in the function are instantiated in the environment record. Formal parameters and functions are initialized as part of this process. All other bindings are initialized during execution of the function code.
Function Declaration Instantiation is performed as follows using arguments func, argumentsList, and env. func is the function object that for which the execution context is being established. env is the declarative environment record in which bindings are to be created.
arguments", then let argumentsObjectNotNeeded be true.arguments", then let argumentsObjectNotNeeded be
true."arguments" then an
argument object is not created.arguments" as
the argument.arguments" as
the argument.arguments" is not initialized until
after parameter initialization.arguments" and ao as
arguments.NOTE When a Block or CaseBlock production is evaluated a new Declarative Environment Record is created and bindings for each block scoped variable, constant, or function declarated in the block are instantiated in the environment record.
Block Declaration Instantiation is performed as follows using arguments code and env. code is the grammar production corresponding to the body of the block. env is the declarative environment record in which bindings are to be created.
When function code is evaluated, an arguments object is created unless (as specified in 10.5) the
identifier arguments occurs as an Identifier in the function’s FormalParameterList or occurs as the BindingIdentifier of a FunctionDeclaration contained in the outermost StatementList of the function
code.
The abstract operation InstantiateArgumentsObject called with an argument args performs the following steps:
The abstract operation CompleteStrictArgumentsObject called with argument obj which must have been previous created by the abstract operation InstantiateArgumentsObject. The following steps are performed:
The abstract operation CompleteMappedArgumentsObject is called with object obj, object func, grammar production formals, and environment record env. obj must have been previous created by the abstract operation InstantiateArgumentsObject.The following steps are performed:
callee" and the Property Descriptor
{[[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true} as
arguments.The abstract operation MakeArgGetter called with String name and environment record env creates a function object that when executed returns the value bound for name in env. It performs the following steps:
return ", name, and
";".The abstract operation MakeArgSetter called with String name and environment record env creates a function object that when executed sets the value bound for name in env. It performs the following steps:
The [[Get]] internal method of an arguments object for a non-strict mode function with formal parameters when called with a property name P performs the following steps:
"caller" and v is a strict mode Function object, throw a TypeError
exception.The [[GetOwnProperty]] internal method of an arguments object for a non-strict mode function with formal parameters when called with a property name P performs the following steps:
The [[DefineOwnProperty]] internal method of an arguments object for a non-strict mode function with formal parameters when called with a property name P and Property Descriptor Desc performs the following steps:
The [[Delete]] internal method of an arguments object for a non-strict mode function with formal parameters when called with a property key P performs the following steps:
NOTE 1 For non-strict mode functions the array index (defined in 15.4) data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function’s execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object’s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.
NOTE 2 The ParameterMap object and its property values are used as a device for specifying the arguments object correspondence to argument bindings. The ParameterMap object and the objects that are the values of its properties are not directly accessible from ECMAScript code. An ECMAScript implementation does not need to actually create or use such objects to implement the specified semantics.
NOTE 3 Arguments objects for strict mode functions define non-configurable accessor properties
named "caller" and "callee" which throw a TypeError exception on access. The
"callee" property has a more specific meaning for non-strict mode functions and a "caller"
property has historically been provided as an implementation-defined extension by some ECMAScript implementations. The
strict mode definition of these properties exists to ensure that neither of them is defined in any other manner by
conforming ECMAScript implementations.
this( Expression )( )( ... Identifier )( Expression , ... Identifier )When processing the production PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList the following grammar is used to refine the interpretation of CoverParenthesizedExpressionAndArrowParameterList.
( Expression )Static Semantics
Static Semantics: CoveredParenthesizedExpression
( Expression )Static Semantics: IsValidSimpleAssignmentTarget
thisPrimaryExpression : Identifier
"eval" or "arguments", then return false.PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
Runtime Semantics: Evaluation
thisRuntime Semantics: Evaluation
NOTE: The result of evaluating an Identifier is always a value of type Reference.
Runtime Semantics
Runtime Semantics: Evaluation
falsetrue
NOTE An ArrayLiteral is an expression describing the initialisation of an Array object, using a list, of zero or more expressions each of which represents an array element, enclosed in square brackets. The elements need not be literals; they are evaluated each time the array initialiser is evaluated.
Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.
[ Elisionopt ][ ElementList ][ ElementList , Elisionopt ], Elisionopt AssignmentExpression, Elisionopt SpreadElement,,... AssignmentExpressionStatic Semantics
Static Semantics: Elision Width
Elision : ,
Elision : Elision ,
Runtime Semantics
Runtime Semantics: Array Accumulation
With parameters array and nextIndex.
ElementList : Elisionopt AssignmentExpression
ElementList : Elisionopt SpreadElement
ElementList : ElementList
, Elisionopt AssignmentExpression
ElementList : ElementList
, Elisionopt SpreadElement
SpreadElement : ... AssignmentExpression
"length").NOTE [[DefineOwnProperty]] is used to ensure that own properties are defined for the array even if the standard built-in Array prototype object has been modified in a manner that would preclude the creation of new own properties using [[Set]].
Runtime Semantics: Evaluation
ArrayLiteral : [ Elisionopt ]
"length", pad, false).ArrayLiteral : [ ElementList ]
"length", len, false).ArrayLiteral : [ ElementList , Elisionopt ]
"length", ToUint32(padding+len),
false).[Comprehension ]for ( ForBinding of AssignmentExpression )if ( AssignmentExpression )Runtime Semantics
Runtime Semantics: Binding Initialisation
With arguments value and environment.
NOTE undefined is passed for environment to indicate that a PutValue operation should be used to assign the initialisation value. This is the case for
var statements formal parameter lists of non-strict functions. In those cases a lexical binding is hosted
and preinitialized prior to evaluation of its initializer.
ForBinding : BindingPattern
Runtime Semantics: Evaluation
ToDo
NOTE An object initialiser is an expression describing the initialisation of an Object, written in a form resembling a literal. It is a list of zero or more pairs of property names and associated values, enclosed in curly braces. The values need not be literals; they are evaluated each time the object initialiser is evaluated.
{ }{ PropertyDefinitionList }{ PropertyDefinitionList , }, PropertyDefinition: AssignmentExpression= AssignmentExpressionNOTE 1 MethodDefinition is defined in 13.3.
NOTE 2 In certain contexts, ObjectLiteral is used as a cover grammar for a more restricted secondary grammar. The CoverInitialisedName production is necessary to fully cover these secondary grammars. However, use of this production results in an early Syntax Error in normal contexts where an actual ObjectLiteral is expected.
Static Semantics: Early Errors
In addition to describe an actual object initialiser the ObjectLiteral productions are used as a cover grammar for ObjectAssignmentPattern (11.13.1). When ObjectLiteral appears in a context where ObjectAssignmentPattern is required, the following Early Error rules are not applied.
ObjectLiteral : { PropertyDefinitionList }
and
ObjectLiteral : { PropertyDefinitionList , }
It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any duplicate entries, unless one of the following conditions are true for each duplicate entry:
: AssignmentExpression .get
accessor MethodDefinition and the other occurrence was obtained from a set
accessor MethodDefinition.PropertyDefinition : MethodDefinition
PropertyDefinition : IdentifierName
PropertyDefinition : CoverInitialisedName
NOTE This production exists so that ObjectLiteral can serve as a cover grammar for ObjectAssignmentPattern (11.13.1). It can not occur in an actual object initialiser.
Static Semantics: Contains
With parameter symbol.
PropertyDefinition : MethodDefinition
NOTE Static semantic rules that depend upon substructure generally do not look into function definitions.
PropertyName : IdentifierName
Static Semantics: IsValidSimpleAssignmentTarget
PrimaryExpression : Literal
Static Semantics: PropName
PropertyDefinition : IdentifierName
PropertyDefinition : PropertyName : AssignmentExpression
PropertyName : StringLiteral
PropertyName : NumericLiteral
Static Semantics: PropertyNameList
PropertyDefinitionList : PropertyDefinition
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
Runtime Semantics: Evaluation
ObjectLiteral : { }
new Object() where Object is the
standard built-in constructor with that name.{ PropertyDefinitionList }{ PropertyDefinitionList , }
Runtime Semantics: Property Definition Evaluation
With parameter object.
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
PropertyDefinition : IdentifierName
PropertyDefinition : PropertyName : AssignmentExpression
See 13.1 for PrimaryExpression : FunctionExpression .
See 13.4 for PrimaryExpression : GeneratorExpression .
See 13.5 for PrimaryExpression : ClassExpression .
( Comprehension )See 7.8.5.
Static Semantics
Static Semantics: Early Errors
It is a Syntax Error if BodyText of RegularExpressionLiteral can not be recognized using the goal symbol Pattern of the ECMAScript RegExp grammar specified in 15.10.
It is a Syntax Error if FlagText of RegularExpressionLiteral contains any character other than "g", "i",
"m", "u", or "y", or if it contains the same character more than once.
Runtime Semantics
Runtime Semantics: Evaluation
[Lexical goal InputElementTemplateTail ] TemplateSpans[Lexical goal InputElementTemplateTail ] TemplateTail[Lexical goal InputElementTemplateTail ] TemplateMiddle ExpressionStatic Semantics
Static Semantics: TemplateStrings
With parameter raw.
TemplateLiteral : NoSubstitutionTemplate
TemplateLiteral : TemplateHead Expression [Lexical goal InputElementTemplateTail] TemplateSpans
TemplateSpans : TemplateTail
TemplateSpans : TemplateMiddleList [Lexical goal InputElementTemplateTail] TemplateTail
TemplateMiddleList : TemplateMiddle Expression
TemplateMiddleList : TemplateMiddleList [Lexical goal InputElementTemplateTail] TemplateMiddle Expression
Runtime Semantics
Runtime Semantics: ArgumentListEvaluation
TemplateLiteral : NoSubstitutionTemplate
TemplateLiteral : TemplateHead Expression [Lexical goal InputElementTemplateTail] TemplateSpans
Runtime Semantics: GetTemplateCallSite Abstract Operation
The abstract operation GetTemplateCallSite is called with a grammar production, templateLiteral, as an argument. It performs the following steps:
NOTE 1 The creation of a call site object cannot result in an abrupt completion.
NOTE 2 Each TemplateLiteral in the program code is associated with a unique Template call site object that is used in the evaluation of tagged Templates (11.2.6). The same call site object is used each time a specific tagged Template is evaluated. Whether call site objects are created lazily upon first evaluation of the TemplateLiteral or eagerly prior to first evaluation is an implementation choice that is not observable to ECMAScript code.
Runtime Semantics: SubstitutionEvaluation
TemplateSpans : TemplateTail
TemplateSpans : TemplateMiddleList [Lexical goal InputElementTemplateTail] TemplateTail
TemplateMiddleList : TemplateMiddle Expression
TemplateMiddleList : TemplateMiddleList [Lexical goal InputElementTemplateTail] TemplateMiddle Expression
Runtime Semantics: Evaluation
TemplateLiteral : NoSubstitutionTemplate
TemplateLiteral : TemplateHead Expression [Lexical goal InputElementTemplateTail] TemplateSpans
TemplateSpans : TemplateTail
TemplateSpans : TemplateMiddleList [Lexical goal InputElementTemplateTail] TemplateTail
TemplateMiddleList : TemplateMiddle Expression
TemplateMiddleList : TemplateMiddleList [Lexical goal InputElementTemplateTail] TemplateMiddle Expression
Static Semantics: Early Errors
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
It is a Syntax Error if the lexical token sequence matched by CoverParenthesizedExpressionAndArrowParameterList cannot be parsed with no tokens left over using ParenthesizedExpression as the goal symbol.
All Early Errors rules for ParenthesizedExpression and its derived productions also apply to the CoveredParenthesizedExpression of CoverParenthesizedExpressionAndArrowParameterList.
Static Semantics: IsValidSimpleAssignmentTarget
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
ParenthesizedExpression : (
Expression )
Runtime Semantics: Evaluation
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
ParenthesizedExpression : (
Expression )
NOTE This algorithm does not apply GetValue to the result of
evaluating Expression. The principal motivation for this is so that operators such as delete and
typeof may be applied to parenthesised expressions.
[Lexical goal InputElementRegExp ] PrimaryExpression[ Expression ]. IdentifierNamesuper [ Expression ]super . IdentifierNamenew super Argumentsoptnew MemberExpression Argumentsnew NewExpressionsuper Arguments[ Expression ]. IdentifierName( )( ArgumentList )... AssignmentExpression, AssignmentExpression, ... AssignmentExpressionStatic Semantics
Static Semantics: Contains
With parameter symbol.
MemberExpression : MemberExpression . IdentifierName
MemberExpression : super . IdentifierName
super, return true.CallExpression : CallExpression
. IdentifierName
MemberExpression : new super
super, return true.new, return true.MemberExpression : new super Arguments
super, return true.new, return true.Static Semantics: IsValidSimpleAssignmentTarget
[ Expression ]. IdentifierName[ Expression ]. IdentifierNamesuper [ Expression ]super . IdentifierNamesuper Arguments: new NewExpressionnew super Argumentsoptnew MemberExpression ArgumentsProperties are accessed by name, using either the dot notation:
. IdentifierName. IdentifierNameor the bracket notation:
[ Expression ][ Expression ]The dot notation is explained by the following syntactic conversion:
. IdentifierNameis identical in its behaviour to
[ <identifier-name-string> ]and similarly
. IdentifierNameis identical in its behaviour to
[ <identifier-name-string> ]where <identifier-name-string> is a string literal containing the same sequence of characters after processing of Unicode escape sequences as the IdentifierName.
Runtime Semantics: Evaluation
MemberExpression : MemberExpression [ Expression ]
CallExpression : CallExpression [ Expression ]
Is evaluated in exactly the same manner as MemberExpression : MemberExpression [ Expression
] except that the contained CallExpression is evaluated in step 1.
Runtime Semantics: Evaluation
NewExpression : new NewExpression
MemberExpression : new MemberExpression Arguments
Runtime Semantics: Evaluation
CallExpression : MemberExpression Arguments
CallExpression : CallExpression Arguments
Runtime Semantics: EvaluateCall Abstract Operation
The abstract operation EvaluateCall takes as arguments a value ref, and a syntactic grammar production arguments, and a Boolean argument tailPosition. It performs the following steps:
A tail position call must either release any transient internal resources associated with the currently executing function execution context before invoking the target function or reuse those resources in support of the target function.
NOTE 1 For example, a tail position call should only grow an implementation’s activication record stack by the amount that the size of the target function’s activation record exceeds the size of the calling function’s activation record. If the target function’s activation record is smaller, then the total size of the stack should decrease.
Static Semantics
Static Semantics: Early Errors
super [ Expression ]super . IdentifierNamenew super ArgumentsoptCallExpression : super Arguments
It is a Syntax Error if the source code parsed with this production is global code that is not eval code.
It is a Syntax Error if the source code parsed with this production is eval code and the source code is not being processed by a direct call to eval that is contained in function code.
Runtime Semantics: Evaluation
MemberExpression : super [ Expression ]
MemberExpression : super . IdentifierName
MemberExpression : new super Argumentsopt
CallExpression : super Arguments
Runtime Semantics: Abstract Operation MakeSuperReference(propertyKey, strict)
The evaluation of an argument list produces a List of values (see 8.7).
Runtime Semantics: ArgumentListEvaluation
Arguments : ( )
ArgumentList : AssignmentExpression
ArgumentList : ... AssignmentExpression
"length").ArgumentList : ArgumentList
, AssignmentExpression
ArgumentList : ArgumentList
, ... AssignmentExpression
"length").Runtime Semantics: Evaluation
MemberExpression : MemberExpression TemplateLiteral
CallExpression : CallExpression TemplateLiteral
++--Static Semantics
Static Semantics: Early Errors
++--It is an early Reference Error if IsValidSimpleAssignmentTarget of LeftHandSideExpression is false.
Static Semantics: IsValidSimpleAssignmentTarget
++--Runtime Semantics: Evaluation
PostfixExpression : LeftHandSideExpression [no LineTerminator
here] ++
1 to oldValue, using the same rules as for
the + operator (see 11.6.3).Runtime Semantics: Evaluation
PostfixExpression : LeftHandSideExpression [no LineTerminator here]
--
1 from oldValue, using the same rules
as for the - operator (11.6.3).delete UnaryExpressionvoid UnaryExpressiontypeof UnaryExpression++ UnaryExpression-- UnaryExpression+ UnaryExpression- UnaryExpression~ UnaryExpression! UnaryExpressionStatic Semantics
Static Semantics: Early Errors
++ UnaryExpression-- UnaryExpressionIt is an early Reference Error if IsValidSimpleAssignmentTarget of UnaryExpression is false.
Static Semantics: IsValidSimpleAssignmentTarget
delete UnaryExpressionvoid UnaryExpressiontypeof UnaryExpression++ UnaryExpression-- UnaryExpression+ UnaryExpression- UnaryExpression~ UnaryExpression! UnaryExpressionStatic Semantics: Early Errors
UnaryExpression : delete UnaryExpression
It is a Syntax Error if the UnaryExpression is contained in strict code and the derived UnaryExpression is PrimaryExpression : Identifier.
It is a Syntax Error if the derived UnaryExpression is
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
and derives a
production that is used in place of UnaryExpression would produce a Syntax Error according to
these rules. This rule is recursively applied.
Runtime Semantics: Evaluation
UnaryExpression : delete UnaryExpression
NOTE When a delete operator occurs within strict mode
code, a SyntaxError exception is thrown if its UnaryExpression is a direct reference to
a variable, function argument, or function name. In addition, if a delete operator occurs within strict mode code and the property to be deleted has the attribute { [[Configurable]]: false
}, a TypeError exception is thrown.
Runtime Semantics: Evaluation
UnaryExpression : void UnaryExpression
NOTE GetValue must be called even though its value is not used because it may have observable side-effects.
Runtime Semantics: Evaluation
UnaryExpression : typeof UnaryExpression
"undefined".Table { SEQ Table \* ARABIC }30 — typeof Operator Results
| Type of val | Result |
|---|---|
| Undefined | "undefined" |
| Null | "object" |
| Boolean | "boolean" |
| Number | "number" |
| String | "string" |
| Object (ordinary and does not implement [[Call]]) | "object" |
| Object (implements [[Call]]) | "function" |
| Object (exotic and does not implement [[Call]]) | Implementation-defined unless explicitly specified. May not be "undefined", "boolean", "number", or "string". |
Runtime Semantics: Evaluation
UnaryExpression : ++ UnaryExpression
1 to oldValue, using the same rules as for
the + operator (see 11.6.3).Runtime Semantics: Evaluation
UnaryExpression : -- UnaryExpression
1 from oldValue, using the same rules
as for the - operator (see 11.6.3).NOTE The unary + operator converts its operand to Number type.
Runtime Semantics: Evaluation
UnaryExpression : + UnaryExpression
NOTE The unary - operator converts its operand to Number type and then negates it.
Negating +0 produces −0, and negating −0 produces +0.
Runtime Semantics: Evaluation
UnaryExpression : - UnaryExpression
Runtime Semantics: Evaluation
UnaryExpression : ~ UnaryExpression
Runtime Semantics: Evaluation
UnaryExpression : ! UnaryExpression
* UnaryExpression/ UnaryExpression% UnaryExpressionStatic Semantics: IsValidSimpleAssignmentTarget
* UnaryExpression/ UnaryExpression% UnaryExpressionRuntime Semantics: Evaluation
The production MultiplicativeExpression : MultiplicativeExpression @ UnaryExpression , where @
stands for one of the operators in the above definitions, is evaluated as follows:
The * operator performs multiplication, producing the product of its operands. Multiplication is
commutative. Multiplication is not always associative in ECMAScript, because of finite precision.
The result of a floating-point multiplication is governed by the rules of IEEE 754 binary double-precision arithmetic:
If either operand is NaN, the result is NaN.
The sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
Multiplication of an infinity by a zero results in NaN.
Multiplication of an infinity by an infinity results in an infinity. The sign is determined by the rule already stated above.
Multiplication of an infinity by a finite nonzero value results in a signed infinity. The sign is determined by the rule already stated above.
In the remaining cases, where neither an infinity or NaN is involved, the product is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode. If the magnitude is too large to represent, the result is then an infinity of appropriate sign. If the magnitude is too small to represent, the result is then a zero of appropriate sign. The ECMAScript language requires support of gradual underflow as defined by IEEE 754.
The / operator performs division, producing the quotient of its operands. The left operand is the dividend
and the right operand is the divisor. ECMAScript does not perform integer division. The operands and result of all division
operations are double-precision floating-point numbers. The result of division is determined by the specification of IEEE
754 arithmetic:
If either operand is NaN, the result is NaN.
The sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
Division of an infinity by an infinity results in NaN.
Division of an infinity by a zero results in an infinity. The sign is determined by the rule already stated above.
Division of an infinity by a nonzero finite value results in a signed infinity. The sign is determined by the rule already stated above.
Division of a finite value by an infinity results in zero. The sign is determined by the rule already stated above.
Division of a zero by a zero results in NaN; division of zero by any other finite value results in zero, with the sign determined by the rule already stated above.
Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule already stated above.
In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the quotient is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode. If the magnitude is too large to represent, the operation overflows; the result is then an infinity of appropriate sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of the appropriate sign. The ECMAScript language requires support of gradual underflow as defined by IEEE 754.
The % operator yields the remainder of its operands from an implied division; the left operand is the
dividend and the right operand is the divisor.
NOTE In C and C++, the remainder operator accepts only integral operands; in ECMAScript, it also accepts floating-point operands.
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. The IEEE 754 “remainder” operation computes the remainder
from a rounding division, not a truncating division, and so its behaviour is not analogous to that of the usual integer
remainder operator. Instead the ECMAScript language defines % on floating-point operations to behave in a
manner analogous to that of the Java integer remainder operator; this may be compared with the C library function fmod.
The result of an ECMAScript floating-point remainder operation is determined by the rules of IEEE arithmetic:
If either operand is NaN, the result is NaN.
The sign of the result equals the sign of the dividend.
If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
If the dividend is finite and the divisor is an infinity, the result equals the dividend.
If the dividend is a zero and the divisor is nonzero and finite, the result is the same as the dividend.
In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n − (d × q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d. r is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode.
+ MultiplicativeExpression- MultiplicativeExpressionStatic Semantics: IsValidSimpleAssignmentTarget
+ MultiplicativeExpression- MultiplicativeExpressionNOTE The addition operator either performs string concatenation or numeric addition.
Runtime Semantics: Evaluation
AdditiveExpression : AdditiveExpression + MultiplicativeExpression
NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6. All standard ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Exotic objects may handle the absence of a hint in some other manner.
NOTE 2 Step 7 differs from step 3 of the comparison algorithm for the relational operators (11.8.1), by using the logical-or operation instead of the logical-and operation.
Runtime Semantics: Evaluation
AdditiveExpression : AdditiveExpression - MultiplicativeExpression
The + operator performs addition when applied to two operands of numeric type, producing the sum of the
operands. The - operator performs subtraction, producing the difference of two numeric operands.
Addition is a commutative operation, but not always associative.
The result of an addition is determined using the rules of IEEE 754 binary double-precision arithmetic:
If either operand is NaN, the result is NaN.
The sum of two infinities of opposite sign is NaN.
The sum of two infinities of the same sign is the infinity of that sign.
The sum of an infinity and a finite value is equal to the infinite operand.
The sum of two negative zeroes is −0. The sum of two positive zeroes, or of two zeroes of opposite sign, is +0.
The sum of a zero and a nonzero finite value is equal to the nonzero operand.
The sum of two nonzero finite values of the same magnitude and opposite sign is +0.
In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, and the operands have the same sign or have different magnitudes, the sum is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode. If the magnitude is too large to represent, the operation overflows and the result is then an infinity of appropriate sign. The ECMAScript language requires support of gradual underflow as defined by IEEE 754.
The - operator performs subtraction when applied to two operands of numeric type, producing the difference
of its operands; the left operand is the minuend and the right operand is the subtrahend. Given numeric operands
a and b, it is always the case that a–b produces the same
result as a +(–b).
<< AdditiveExpression>> AdditiveExpression>>> AdditiveExpressionStatic Semantics: IsValidSimpleAssignmentTarget
<< AdditiveExpression>> AdditiveExpression>>> AdditiveExpressionNOTE Performs a bitwise left shift operation on the left operand by the amount specified by the right operand.
Runtime Semantics: Evaluation
ShiftExpression : ShiftExpression << AdditiveExpression
NOTE Performs a sign-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
Runtime Semantics: Evaluation
ShiftExpression : ShiftExpression >> AdditiveExpression
NOTE Performs a zero-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
Runtime Semantics: Evaluation
ShiftExpression : ShiftExpression >>> AdditiveExpression
NOTE The result of evaluating a relational operator is always of type Boolean, reflecting whether the relationship named by the operator holds between its two operands.
< ShiftExpression> ShiftExpression<= ShiftExpression>= ShiftExpressioninstanceof ShiftExpressionin ShiftExpression< ShiftExpression> ShiftExpression<= ShiftExpression>= ShiftExpressioninstanceof ShiftExpressionThe semantics of the RelationalExpressionNoIn productions are the same as the RelationalExpression productions except that the contained RelationalExpressionNoIn is used in place of the contained RelationalExpression.
NOTE The “NoIn” variants are needed to avoid confusing the in operator in a relational expression with the in operator in a for statement.
Static Semantics: IsValidSimpleAssignmentTarget
< ShiftExpression> ShiftExpression<= ShiftExpression>= ShiftExpressioninstanceof ShiftExpressionin ShiftExpressionRuntime Semantics: The Abstract Relational Comparison Algorithm
The comparison x < y, where x and y are values, produces true, false, or undefined (which indicates that at least one operand is NaN). In addition to x and y the algorithm takes a Boolean flag named LeftFirst as a parameter. The flag is used to control the order in which operations with potentially visible side-effects are performed upon x and y. It is necessary because ECMAScript specifies left to right evaluation of expressions. The default value of LeftFirst is true and indicates that the x parameter corresponds to an expression that occurs to the left of the y parameter’s corresponding expression. If LeftFirst is false, the reverse is the case and operations must be performed upon y before x. Such a comparison is performed as follows:
NOTE 1 Step 3 differs from step 7 in the algorithm for the addition operator + (11.6.1) in using and instead of or.
NOTE 2 The comparison of Strings uses a simple lexicographic ordering on sequences of code unit values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore String values that are canonically equal according to the Unicode standard could test as unequal. In effect this algorithm assumes that both Strings are already in normalised form. Also, note that for strings containing supplementary characters, lexicographic ordering on sequences of UTF-16 code unit values differs from that on sequences of code point values.
Runtime Semantics: Evaluation
RelationalExpression : RelationalExpression < ShiftExpression
RelationalExpression : RelationalExpression > ShiftExpression
RelationalExpression : RelationalExpression <= ShiftExpression
RelationalExpression : RelationalExpression >= ShiftExpression
RelationalExpression : RelationalExpression instanceof ShiftExpression
The abstract operation instanceofOperator(O, C) implements the generic algorithm for determining if an object O inherits from the inheritance path defined by constructor C. This abstract operation performs the following steps:
NOTE Steps 5 and 6 provide compatibility with previous editions of ECMAScript that did not use
a @@hasInstance method to define the instanceof operator semantics. If a function object does not define
@@hasInstance it is assumed that it implements the default instanceof semantics.
RelationalExpression : RelationalExpression in ShiftExpression
NOTE The result of evaluating an equality operator is always of type Boolean, reflecting whether the relationship named by the operator holds between its two operands.
== RelationalExpression!= RelationalExpression=== RelationalExpression!== RelationalExpression== RelationalExpressionNoIn!= RelationalExpressionNoIn=== RelationalExpressionNoIn!== RelationalExpressionNoInThe semantics of the EqualityExpressionNoIn productions are the same as the EqualityExpression productions except that the contained EqualityExpressionNoIn and RelationalExpressionNoIn are used in place of the contained EqualityExpression and RelationalExpression, respectively.
Static Semantics: IsValidSimpleAssignmentTarget
== RelationalExpression!= RelationalExpression=== RelationalExpression!== RelationalExpressionRuntime Semantics: The Abstract Equality Comparison Algorithm
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
NOTE 1 Given the above definition of equality:
"" + a == "" + b.+a == +b.!a == !b.NOTE 2 The equality operators maintain the following invariants:
A != B is equivalent to !(A == B).A == B is equivalent to B == A, except
in the order of evaluation of A and B.NOTE 3 The equality operator is not always transitive. For example, there might be two distinct
String objects, each representing the same String value; each String object would be considered equal to the String value
by the == operator, but the two String objects would not be equal to each other. For Example:
new String("a") == "a" and "a" == new
String("a")are both true.new String("a") == new String("a") is false.NOTE 4 Comparison of Strings uses a simple equality test on sequences of code unit values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore Strings values that are canonically equal according to the Unicode standard could test as unequal. In effect this algorithm assumes that both Strings are already in normalised form.
Runtime Semantics: The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
NOTE This algorithm differs from the SameValue Algorithm (9.12) in its treatment of signed zeroes and NaNs.
Runtime Semantics: Evaluation
EqualityExpression : EqualityExpression == RelationalExpression
EqualityExpression : EqualityExpression != RelationalExpression
EqualityExpression : EqualityExpression === RelationalExpression
EqualityExpression : EqualityExpression !== RelationalExpression
& EqualityExpression& EqualityExpressionNoIn^ BitwiseANDExpression^ BitwiseANDExpressionNoIn| BitwiseXORExpression| BitwiseXORExpressionNoInStatic Semantics: IsValidSimpleAssignmentTarget
& EqualityExpression^ BitwiseANDExpression| BitwiseXORExpressionRuntime Semantics: Evaluation
The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:
&& BitwiseORExpression&& BitwiseORExpressionNoIn|| LogicalANDExpression|| LogicalANDExpressionNoInThe semantics of the LogicalANDExpressionNoIn and LogicalORExpressionNoIn productions are the same manner as the LogicalANDExpression and LogicalORExpression productions except that the contained LogicalANDExpressionNoIn, BitwiseORExpressionNoIn and LogicalORExpressionNoIn are used in place of the contained LogicalANDExpression, BitwiseORExpression and LogicalORExpression, respectively.
NOTE The value produced by a && or || operator is not
necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
Static Semantics: IsValidSimpleAssignmentTarget
&& BitwiseORExpression|| LogicalANDExpressionRuntime Semantics: Evaluation
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
LogicalORExpression : LogicalORExpression || LogicalANDExpression
? AssignmentExpression : AssignmentExpression? AssignmentExpression : AssignmentExpressionNoInThe semantics of the ConditionalExpressionNoIn production is the same as the ConditionalExpression production except that the contained LogicalORExpressionNoIn, AssignmentExpression and AssignmentExpressionNoIn are used in place of the contained LogicalORExpression, first AssignmentExpression and second AssignmentExpression, respectively.
NOTE The grammar for a ConditionalExpression in ECMAScript is a little bit different from that in C and Java, which each allow the second subexpression to be an Expression but restrict the third expression to be a ConditionalExpression. The motivation for this difference in ECMAScript is to allow an assignment expression to be governed by either arm of a conditional and to eliminate the confusing and fairly useless case of a comma expression as the centre expression.
Static Semantics: IsValidSimpleAssignmentTarget
? AssignmentExpression : AssignmentExpressionRuntime Semantics: Evaluation
ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression
= AssignmentExpression= AssignmentExpressionNoIn| *= | /= | %= | += | -= | <<= | >>= | >>>= | &= | ^= | |= |
The semantics of the AssignmentExpressionNoIn productions are the same manner as the AssignmentExpression productions except that the contained ConditionalExpressionNoIn and AssignmentExpressionNoIn are used in place of the contained ConditionalExpression and AssignmentExpression, respectively.
Static Semantics: Early Errors
= AssignmentExpressionIt is a Syntax Error if LeftHandSideExpression is either an ObjectLiteral or an ArrayLiteral and if the lexical token sequence matched by LeftHandSideExpression cannot be parsed with no tokens left over using AssignmentPattern as the goal symbol.
If LeftHandSideExpression is either an ObjectLiteral or an ArrayLiteral and if the lexical token sequence matched by LeftHandSideExpression can be parsed with no tokens left over using AssignmentPattern as the goal symbol then the following rules are not applied. Instead, the Early Error rules for AssignmentPattern are used.
It is a Syntax Error if LeftHandSideExpression is an Identifier that can be statically determined to always resolve to a declarative environment record binding and the resolved binding is an immutable binding.
It is an early Reference Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and IsValidSimpleAssignmentTarget of LeftHandSideExpression is false.
It is a Syntax Error if the LeftHandSideExpression is an Identifier that can be statically determined to always resolve to a declarative environment record binding and the resolved binding is an immutable binding.
It is an early Reference Error if IsValidSimpleAssignmentTarget of LeftHandSideExpression is false.
Static Semantics: IsValidSimpleAssignmentTarget
= AssignmentExpressionRuntime Semantics: Evaluation
AssignmentExpression : LeftHandSideExpression = AssignmentExpression
AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
@ where AssignmentOperator is @=NOTE When an assignment occurs within strict mode code, it is an runtime error if lref in step 1.e of the first algorithm or step 9 of the second algorithm it is an unresolvable reference. If it is, a ReferenceError exception is thrown. The LeftHandSide also may not be a reference to a data property with the attribute value {[[Writable]]:false}, to an accessor property with the attribute value {[[Set]]:undefined}, nor to a non-existent property of an object for which the IsExtensible predicate returns the value false. In these cases a TypeError exception is thrown.
In certain circumstances when processing the production AssignmentExpression
: LeftHandSideExpression = AssignmentExpression the following grammar is used to refine the interpretation of LeftHandSideExpression.
{ }{ AssignmentPropertyList }{ AssignmentPropertyList , }[ Elisionopt AssignmentRestElementopt ][ AssignmentElementList ][ AssignmentElementList , Elisionopt AssignmentRestElementopt ], AssignmentProperty, Elisionopt AssignmentElement: AssignmentElement... DestructuringAssignmentTargetStatic Semantics: Early Errors
AssignmentProperty : Identifier Initialiseropt
It is a Syntax Error if Identifier is the Identifier
eval or the Identifier arguments.
It is a Syntax Error if Identifier does not statically resolve to a declarative environment record binding or if the resolved binding is an immutable binding.
It is a Syntax Error LeftHandSideExpression is either an ObjectLiteral or an ArrayLiteral and if the lexical token sequence matched by LeftHandSideExpression cannot be parsed with no tokens left over using AssignmentPattern as the goal symbol.
It is a Syntax Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and IsValidSimpleAssignmentTarget of LeftHandSideExpression is false.
It is a Syntax Error if the LeftHandSideExpression is an Identifier that can be statically determined to always resolve to a declarative environment record binding and the resolved binding is an immutable binding.
It is a Syntax Error if LeftHandSideExpression is the Identifier
eval or the Identifier arguments.
It is a Syntax Error if IsInvalidAssignmentPattern of LeftHandSideExpression is true.
It is a Syntax Error if the LeftHandSideExpression is CoverParenthesizedExpressionAndArrowParameterList :
( Expression ) and Expression derived a production that would produce a Syntax Error according to these rules. This
rule is recursively applied.
Runtime Semantics: Destructuring Assignment Evaluation
with parameter obj
ObjectAssignmentPattern : {
}
and
[][Elision]
AssignmentPropertyList : AssignmentPropertyList , AssignmentProperty
Let status be
AssignmentProperty : Identifier Initialiseropt
AssignmentProperty : PropertyName : AssignmentElement
ArrayAssignmentPattern : [
Elisionopt AssignmentRestElement ]
ArrayAssignmentPattern : [
AssignmentElementList ]
ArrayAssignmentPattern : [ AssignmentElementList , Elisionopt AssignmentRestElementopt ]
Runtime Semantics: Indexed Destructuring Assignment Evaluation
with parameters obj and index
AssignmentElementList : Elision opt AssignmentElement
AssignmentElementList : AssignmentElementList , Elision opt AssignmentElement
AssignmentRestElement : ...
DestructuringAssignmentTarget
"length").Runtime Semantics: Keyed Destructuring Assignment Evaluation
with parameters obj and propertyName
AssignmentElement : DestructuringAssignmentTarget Initialiseropt
, AssignmentExpression, AssignmentExpressionNoInThe semantics of the ExpressionNoIn production is the same manner as the Expression production except that the contained ExpressionNoIn and AssignmentExpressionNoIn are used in place of the contained Expression and AssignmentExpression, respectively.
Static Semantics: IsValidSimpleAssignmentTarget
, AssignmentExpressionRuntime Semantics: Evaluation
Expression : Expression , AssignmentExpression
NOTE GetValue must be called even though its value is not used because it may have observable side-effects.
Static Semantics: VarDeclaredNames
Runtime Semantics: Labelled Evaluation
With argument labelSet.
BreakableStatement : IterationStatement
BreakableStatement : SwitchStatement
NOTE A BreakableStatement is one that can be exited via an unlabelled BreakStatement.
Runtime Semantics: Evaluation
{ StatementListopt }Static Semantics: Early Errors
Block : { StatementList }
It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any duplicate entries.
It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also occurs in the VarDeclaredNames of StatementList.
Static Semantics: LexicalDeclarations
StatementList : StatementList StatementListItem
StatementListItem : Statement
StatementListItem : Declaration
Static Semantics: LexicallyDeclaredNames
Block : { }
StatementList : StatementList StatementListItem
StatementListItem : Statement
StatementListItem : Declaration
Static Semantics: TopLevelLexicallyDeclaredNames
StatementList : StatementList StatementListItem
StatementListItem : Statement
StatementListItem : Declaration
NOTE At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.
Static Semantics: TopLevelLexicallyScopedDeclarations
StatementList : StatementList StatementListItem
StatementListItem : Statement
StatementListItem : Declaration
Static Semantics: TopLevelVarDeclaredNames
StatementList : StatementList StatementListItem
StatementListItem : Declaration
StatementListItem : Statement
NOTE At the top level of a function or script, inner function declarations are treated like var declarations.
Static Semantics: TopLevelVarScopedDeclarations
StatementList : StatementList StatementListItem
StatementListItem : Statement
StatementListItem : Declaration
Static Semantics: VarDeclaredNames
Block : { }
StatementList : StatementList StatementListItem
StatementListItem : Declaration
Runtime Semantics: Evaluation
Block : { }
Block : { StatementList }
NOTE No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.
StatementList : StatementList StatementListItem
NOTE Steps 4 and 5 of the above algoritm ensure that the value of a StatementList is the value of the last value producing Statement in the StatementList. For example, the following calls to the eval function all return the value
1:
eval("1;;;;;")
eval("1;{}")
eval("1;var a;")
NOTE A let and const declarations define variables that are scoped to
the running execution context’s LexicalEnvironment. The variables are created when their
containing Lexical Environment is instantiated but may not be accessed in any way until the
variable’s LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initialiser is assigned the value of its Initialiser’s AssignmentExpression when
the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an an Initialiser
the variable is assigned the value undefined when the LexicalBinding is evaluated.
;letconst, LexicalBinding, LexicalBindingNoIn= AssignmentExpressionNoInThe semantics of the LexicalDeclarationNoIn, BindingListNoIn, LexicalBindingNoIn and InitialiserNoIn productions are the same as the LexicalDeclaration, BindingList, LexicalBinding and Initialiser productions except that the contained BindingListNoIn, LexicalBindingNoIn, InitialiserNoIn and AssignmentExpressionNoIn are used in place of the contained BindingList, LexicalBinding, Initialiser and AssignmentExpression, respectively.
Static Semantics: Early Errors
LexicalBinding : BindingIdentifier
It is a Syntax Error if IsConstantDeclaration of the LexicalDeclaration containing this production is true.
BindingIdentifier : Identifier
It is a Syntax Error if the BindingIdentifier is contained in strict
code and if the Identifier is eval or arguments.
Static Semantics: BoundNames
LexicalDeclaration : LetOrConst BindingList ;
BindingList : BindingList
, LexicalBinding
LexicalBinding : BindingIdentifier Initialiseropt
LexicalBinding : BindingPattern Initialiser
BindingIdentifier : Identifier
Static Semantics: IsConstantDeclaration
LexicalDeclaration : LetOrConst BindingList ;
LetOrConst : let
LetOrConst : const
Runtime Semantics: Binding Initialisation
With arguments value and environment.
NOTE undefined is passed for environment to indicate that a PutValue operation should be used to assign the initialisation value. This is the case for
var statements formal parameter lists of non-strict functions. In those cases a lexical binding is hosted
and preinitialized prior to evaluation of its initializer.
BindingIdentifier : Identifier
Runtime Semantics: Evaluation
LexicalDeclaration : LetOrConst BindingList ;
BindingList : BindingList
, LexicalBinding
LexicalBinding : BindingIdentifier
NOTE A static semantics rule ensures that this form of LexicalBinding
never occurs in a const declaration.
LexicalBinding : BindingIdentifier Initialiser
LexicalBinding : BindingPattern Initialiser
NOTE A var statement declares variables that are scoped to the running execution
context’s VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialised to undefined when created. Within the
scope of any VariableEnvironemnt a common Identifier may appear in more than one VariableDeclaration but those declarations collective define only one variable. A variable defined by a
VariableDeclaration with an Initialiser is assigned the value of its Initialiser’s AssignmentExpression when
the VariableDeclaration is executed, not when the variable is created.
var VariableDeclarationList ;, VariableDeclaration, VariableDeclarationNoInThe semantics of the VariableDeclarationListNoIn, VariableDeclarationNoIn and InitialiserNoIn productions are the same as the VariableDeclarationList, VariableDeclaration and Initialiser productions except that the contained VariableDeclarationListNoIn, VariableDeclarationNoIn, InitialiserNoIn and AssignmentExpressionNoIn are used in of the contained VariableDeclarationList, VariableDeclaration, Initialiser and AssignmentExpression, respectively.
Static Semantics: BoundNames
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
VariableDeclaration : BindingIdentifier Initialiseropt
VariableDeclaration : BindingPattern Initialiser
Runtime Semantics: Binding Initialisation
With arguments value and environment.
NOTE undefined is passed for environment to indicate that a PutValue operation should be used to assign the initialisation value. This is the case for
var statements formal parameter lists of non-strict functions. In those cases a lexical binding is hosted
and preinitialized prior to evaluation of its initializer.
VariableDeclaration : BindingIdentifier
VariableDeclaration : BindingIdentifier Initialiser
VariableDeclaration : BindingPattern Initialiser
Runtime Semantics: Evaluation
VariableStatement : var
VariableDeclarationList ;
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
VariableDeclaration : BindingIdentifier
VariableDeclaration : BindingIdentifier Initialiser
NOTE If a VariableDeclaration is nested within a with statement and the Identifier in the VariableDeclaration is the same as a property name of the binding object of the with statement’s object environment record, then step 3 will assign value to the property instead of to the VariableEnvironment binding of the Identifier.
VariableDeclaration : BindingPattern Initialiser
{ }{ BindingPropertyList }{ BindingPropertyList , }[ Elisionopt BindingRestElementopt ][ BindingElementList ][ BindingElementList , Elisionopt BindingRestElementopt ], BindingProperty, Elisionopt BindingElement: BindingElement... BindingIdentifierStatic Semantics: Early Errors
BindingPattern : ObjectBindingPattern
It is a Syntax Error if the BoundNames of ObjectBindingPattern contains the string
“eval” or the string “arguments”.
BindingPattern : ArrayBindingPattern
It is a Syntax Error if the BoundNames of ArrayBindingPattern contains the string
“eval” or the string “arguments”.
Static Semantics: BoundNames
ObjectBindingPattern : {
}
ArrayBindingPattern : [
Elisionopt ]
ArrayBindingPattern : [
Elisionopt BindingRestElement ]
ArrayBindingPattern : [
BindingElementList , Elisionopt ]
ArrayBindingPattern : [
BindingElementList , Elisionopt BindingRestElement ]
BindingPropertyList : BindingPropertyList , BindingProperty
BindingElementList : Elisionopt BindingElement
BindingElementList : BindingElementList , Elisionopt BindingElement
BindingProperty : PropertyName : BindingElement
SingleNameBinding : BindingIdentifier Initialiseropt
BindingElement : BindingPattern Initialiseropt
Static Semantics: HasInitialiser
BindingElement : BindingPattern
BindingElement : BindingPattern Initialiser
SingleNameBinding : BindingIdentifier
SingleNameBinding : BindingIdentifier Initialiser
Runtime Semantics: Binding Initialisation
With parameters value and environment.
NOTE When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialisation 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.
BindingPattern : ObjectBindingPattern
BindingPattern : ArrayBindingPattern
ObjectBindingPattern : {
}
BindingPropertyList : BindingPropertyList , BindingProperty
BindingProperty : SingleNameBinding
BindingProperty : PropertyName : BindingElement
Runtime Semantics: Indexed Binding Initialisation
With parameters array, nextIndex, and environment.
NOTE When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialisation value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.
ArrayBindingPattern : [
Elisionopt ]
ArrayBindingPattern : [
Elisionopt BindingRestElement ]
ArrayBindingPattern : [
BindingElementList ]
ArrayBindingPattern : [
BindingElementList , Elisionopt ]
ArrayBindingPattern : [
BindingElementList , Elisionopt BindingRestElement ]
BindingElementList : Elision opt BindingElement
BindingElementList : BindingElementList , Elision opt BindingElement
BindingElement : SingleNameBinding
BindingElement : BindingPattern Initialiseropt
BindingRestElement : ...
BindingIdentifier
"length").Runtime Semantics: Keyed Binding Initialisation
With parameters obj, environment, and propertyName.
NOTE When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialisation 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.
BindingElement : BindingPattern Initialiseropt
SingleNameBinding : BindingIdentifier Initialiseropt
;Runtime Semantics: Evaluation
EmptyStatement : ;
{, function, class}] Expression ;NOTE An ExpressionStatement cannot start with an opening curly brace
because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function or class keywords because
that would make it ambiguous with a FunctionDeclaration, a GeneratorDeclaration, or a ClassDeclaration.
Runtime Semantics: Evaluation
ExpressionStatement : [lookahead ∉ {{, function, class}] Expression ;
if ( Expression ) Statement else Statementif ( Expression ) StatementEach else for which the choice of associated if is ambiguous shall be associated with the nearest
possible if that would otherwise have no corresponding else.
Static Semantics: VarDeclaredNames
IfStatement : if ( Expression ) Statement else Statement
IfStatement : if ( Expression ) Statement
Runtime Semantics: Evaluation
IfStatement : if ( Expression ) Statement else Statement
IfStatement : if ( Expression ) Statement
do Statement while ( Expression )while ( Expression ) Statementfor ( ExpressionNoInopt ; Expressionopt ; Expressionopt ) Statementfor ( var VariableDeclarationListNoIn ; Expressionopt ; Expressionopt ) Statementfor ( LexicalDeclarationNoIn ; Expressionopt ; Expressionopt ) Statementfor ( LeftHandSideExpression in Expression ) Statementfor ( var ForBinding in Expression ) Statementfor ( ForDeclaration in Expression ) Statementfor ( LeftHandSideExpression of AssignmentExpression ) Statementfor ( var ForBinding of AssignmentExpressionExpression ) Statementfor ( ForDeclaration of AssignmentExpression ) StatementNOTE 1 ForBinding is defined in 11.1.4.2.
NOTE 2 A semicolon is not required after a do-while statement.
Runtime Semantics
Runtime Semantics: LoopContinues Abstract Operation
The abstract operation LoopContinues with arguments completion and labelSet is defined by the following step:
NOTE Within the Statement part of an IterationStatement a ContinueStatement may be used to begin a new iteration.
Static Semantics: VarDeclaredNames
IterationStatement : do Statement while ( Expression )
Runtime Semantics: Labelled Evaluation
With argument labelSet.
IterationStatement : do
Statement while ( Expression
)
Static Semantics: VarDeclaredNames
IterationStatement : while
( Expression ) Statement
Runtime Semantics: Labelled Evaluation
With argument labelSet.
IterationStatement : while
( Expression ) Statement
Static Semantics: VarDeclaredNames
IterationStatement : for
( ExpressionNoInopt ; Expressionopt ; Expressionopt ) Statement
IterationStatement : for
( var VariableDeclarationListNoIn ; Expressionopt ; Expressionopt ) Statement
IterationStatement : for
( LexicalDeclarationNoIn ; Expressionopt ; Expressionopt ) Statement
Runtime Semantics: Labelled Evaluation
With argument labelSet.
IterationStatement : for
( ExpressionNoInopt ; Expressionopt ; Expressionopt ) Statement
IterationStatement : for
( var VariableDeclarationListNoIn ; Expressionopt ; Expressionopt ) Statement
IterationStatement : for
( LexicalDeclarationNoIn ; Expressionopt ; Expressionopt ) Statement
Runtime Semantics: For Body Evaluation Abstract Operation
The abstract operation For Body Evaluation with arguments testExpr, incrementExpr, stmt, and labelSet is performed as follows: