This ECMA Standard is based on several originating technologies, the most well-known being JavaScript (Netscape Communications) and Jscript (Microsoft Corporation). 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 has approved the second edition of ECMA-262 to keep it fully aligned with ISO/IEC 16262. Changes from the first edition are editorial in nature.
The work on standardization of the language continues to support regular expressions, richer control statements and better string handling, in addition to the core language standardized in the first two editions of the ECMA Standard. These features and others, such as try/catch exception handling and better internationalization facilities, are being documented in anticipation of the third edition of the standard about the end of 1999 which will contain the second version of the language.
This Standard has been adopted as 2nd Edition of ECMA-262 by the ECMA General Assembly in August 1998.
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 described in this specification.
A conforming implementation of this International standard shall interpret characters in conformance with the Unicode Standard, Version 2.0, and ISO/IEC 10646-1 with UCS-2 as the adopted encoding form, implementation level 3. If the adopted ISO/IEC 10646-1 subset is not otherwise specified, it is presumed to be the BMP subset, collection 300.
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 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 section -- Future Reserved Word of this specification.
ISO/IEC 9899:1996 Programming Languages - C, including amendment 1 and technical corrigenda 1 and 2.
ISO/IEC 10646-1:1993 Information Technology -- Universal Multiple-Octet Coded Character Set (UCS), including amendments 1 through 9 and technical corrigendum 1.
ISO/IEC 646.IRV:1991 -- Information Processing -- ISO 7-bit Coded Character Set for Information Interchange.
Unicode Inc. (1996), The Unicode Standard™, Version 2.0. ISBN: 0-201-48345-9, Addison-Wesley Publishing Co., Menlo Park, California.
ANSI/IEEE Std 754-1985: IEEE Standard for Binary Floating-Point Arithmetic. Institute of Electrical and Electronics Engineers, New York (1985).
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 host 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, and therefore there may be a number of informalities built into the 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 can provide core scripting capabilities for a variety of host environments, and therefore the core scripting 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ä and Self, as described in:
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 an unordered collection of properties each with 0 or more attributes which determine how each property can be used--for example, when the ReadOnly attribute for a property is set to true, any attempt by executed ECMAScript code to change the value of the property has no effect. Properties are containers that hold other objects, primitive values, or methods. 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 method is a function associated with an object via a property.
ECMAScript defines a collection of built-in objects which 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, and the Date object.
ECMAScript also defines a set of built-in operators that may not be, strictly speaking, functions or methods. 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 contain proper classes such as those in C++, Smalltalk, or Java, but rather, supports constructors which create objects by executing code that allocates storage for the objects and initialises all or part of them by assigning initial values to their properties. All functions including constructors are objects, but not all objects are constructors. Each constructor has a Prototype property that is used to implement prototype-based inheritance and shared properties. Objects are created by using constructors in new expressions; for example, new String("A String") creates a new string object. Invoking a constructor without using new has consequences that depend on the constructor. For example, String("A String") produces a primitive string, not an object.
ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object's prototype) associated with its constructor. 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, and 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. The following diagram 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, as are any properties found in CFp's implicit prototype
chain which are not named q1, q2, or CFp1. Notice that there is no
implicit prototype link between CFp and CF.
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 following are informal definitions of key terms associated with ECMAScript.
A type is a set of data values.
A primitive value is a member of one of the types Undefined, Null, Boolean, Number, or String. A primitive value is a datum that is represented directly at the lowest level of the language implementation.
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.
A constructor is a function object that creates and initialises objects. Each constructor has an associated prototype object that is used to implement inheritance and shared properties.
A prototype is an object used to implement structure, state, and behaviour inheritance in ECMAScript. When a constructor creates an object, that object implicitly references the constructor's associated prototype for the purpose of resolving property references. The constructor's associated prototype 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.
A native object is any object supplied by an ECMAScript implementation independent of the host environment. Standard native objects are defined in this specification. Some native objects are built-in; others may be constructed during the course of execution of an ECMAScript program.
A built-in object is any object supplied by an ECMAScript implementation, independent of the host environment, which is present at the start of the execution of an ECMAScript program. Standard built-in objects are defined in this specification, and the ECMAScript implementation may specify and define others. Every built-in object is a native object.
A host object is any object supplied by the host environment to complete the execution environment of ECMAScript. Any object that is not native is a host object.
The undefined value is a primitive value used when a variable has not been assigned a value.
The type Undefined has exactly one value, called undefined.
The null value is a primitive value that represents the null, empty, or non-existent reference.
The type Null has exactly one value, called null.
A boolean value is a member of the type Boolean and is one of two unique values, true and false.
The type Boolean represents a logical entity and consists of exactly two unique values. One is called true and the other is called false.
A boolean object is a member of the type Object and is an instance of the built-in Boolean object. That is, a boolean object is created by using the Boolean constructor in a new expression, supplying a boolean as an argument. The resulting object has an implicit (unnamed) property that is the boolean. A boolean object can be coerced to a boolean value. A boolean object can be used anywhere a boolean value is expected.
This is an example of one of the conveniences built into ECMAScript--in this case, the purpose is to accommodate programmers of varying backgrounds. Those familiar with imperative or procedural programming languages may find boolean, string and number values more natural, while those familiar with object-oriented languages may find boolean, string and number objects more intuitive.
A string value is a member of the type String and is a finite ordered sequence of zero or more Unicode characters.
The type String is the set of all finite ordered sequences of zero or more Unicode characters.
A string object is a member of the type Object and is an instance of the built-in String object. That is, a string object is created by using the String constructor in a new expression, supplying a string as an argument. The resulting object has an implicit (unnamed) property that is the string. A string object can be coerced to a string value. A string object can be used anywhere a string value is expected.
A number value is a member of the type Number and is a direct representation of a number.
The type Number is a set of values representing numbers. In ECMAScript the set of values represent the double-precision 64-bit format IEEE 754 values including the special ``Not-a-Number'' (NaN) values, positive infinity, and negative infinity.
A number object is a member of the type Object and is an instance of the built-in Number object. That is, a number object is created by using the Number constructor in a new expression, supplying a number as an argument. The resulting object has an implicit (unnamed) property that is the number. A number object can be coerced to a number value. A number object can be used anywhere a number value is expected. Note that a number object can have shared properties by adding them to the Number prototype.
The primitive value Infinity represents the positive infinite number value.
The primitive value NaN represents the set of IEEE Standard ``Not-a-Number'' values.
This section describes the context-free grammars used in this specification to define the lexical and syntactic structure of an ECMAScript program.
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 one or more nonterminal and terminal symbols as its right-hand side. For each grammar, the terminal symbols are drawn from a specified alphabet.
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 Section 7. This grammar has as its terminal symbols the characters of the Unicode character set. It defines a set of productions, starting from the goal symbol InputElement, that describe how sequences of Unicode 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 (see section7.8). Simple white space and single-line comments are simply 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 multi-line comment 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.
Productions of the lexical grammar are distinguished by having two colons ``::'' as separating punctuation.
A second 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 the characters of the Unicode character set. This grammar appears in section 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 sections11, 12, 13, and 14. This grammar has ECMAScript tokens defined by the lexical grammar as its terminal symbols (see section 5.1.2). It defines a set of productions, starting from the goal symbol Program, that describe how sequences of tokens can form syntactically correct ECMAScript programs.
When a stream of Unicode characters is to be parsed as an ECMAScript program, 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 syntax grammar. The program is syntactically in error if the tokens in the stream of input elements cannot be parsed as a single instance of the goal nonterminal Program, 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 sections11, 12, 13, and 14 is actually not a complete account of which token sequences are accepted as correct ECMAScript programs. 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.
Terminal symbols of the lexical and string grammars, and some of the terminal symbols of the syntactic grammar, 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 program exactly as written.
Nonterminal symbols are shown in italic type. The definition of a nonterminal 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:
states that the nonterminal WithStatement represents the token with, 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:
states that an ArgumentList may represent either a single AssignmentExpression or an ArgumentList, followed by a comma, followed by an AssignmentExpression. This definition of ArgumentList is recursive, that is, it is defined in terms of itself. The result is that an ArgumentList may contain any positive number of arguments, separated by commas, where each argument expression is an AssignmentExpression. Such recursive definitions of nonterminals are common.
The subscripted suffix ``opt'', which may appear after a terminal or nonterminal, indicates an optional symbol. The alternative containing the optional symbol actually specifies two right-hand sides, one that omits the optional element and one that includes it. This means that:
is a convenient abbreviation for:
and that:
so the nonterminal IterationStatement actually has eight alternative right-hand sides.
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:
indicates that the production may not be used if a LineTerminator occurs in the program between the return 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 program.
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:
0 | 1 | 2 | 3 |
which is merely a convenient abbreviation for:
When an alternative in a production of the lexical grammar or the numeric string grammar appears to be a multicharacter 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 roman 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 clarify semantics. In practice, there may be more efficient algorithms available to implement a given feature.
When an algorithm is to produce a value as a result, the directive ``return x'' is used to indicate that the result of the algorithm is the value of x and that the algorithm should terminate. The notation Result(n) is used as shorthand for ``the result of step n''. Type(x) is used as shorthand for ``the type of x''.
Mathematical operations such as addition, subtraction, negation, multiplication, division, and the mathematical functions defined later in this section 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 notation ``x modulo y'' (y must be finite and nonzero) computes a value k of the same sign as y 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 ``generate a runtime error'', execution of the algorithm (and any calling algorithms) is terminated and no result is returned.
ECMAScript source text is represented as a sequence of characters representable using the Unicode version 2.0 character encoding.
Except within comments and string literals, every ECMAScript program shall consist of only characters from the first 128 Unicode characters (that is, the first half of row zero). Other Unicode characters may appear only within comments and string literals. In string literals, any Unicode character may also be expressed as a Unicode escape sequence consisting of six characters from the first 128 characters, namely \u plus four hexadecimal digits. Within a comment, such an escape sequence is effectively ignored as part of the comment. Within a string literal, the Unicode escape sequence contributes one character to the string value of the literal.
Although the characters in an ECMAScript program are Unicode characters, they are treated as independent 16-bit values with none of the context-dependent interpretation specified in the Unicode standard. Such values are often called ``code points''. The Unicode standard refers to code points as ``coded character data elements''. Throughout this International standard the terms ``character'' and ``code point'' are understood to mean ``coded character data element''.
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 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 character to the string value of the literal and is never interpreted as a line terminator or as a quote mark that might terminate the string literal.
The source text of an ECMAScript program is first converted into a sequence of input elements, which are either 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.
Syntax
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 may occur between any two tokens, and may occur within strings (where they are considered significant characters forming part of the literal string value), but cannot appear within any other kind of token.
The following characters are considered to be white space:
Unicode Value | Name | Formal Name |
---|---|---|
\u0009 | Tab | <TAB> |
\u000B | Vertical Tab | <VT> |
\u000C | Form Feed | <FF> |
\u0020 | Space | <SP> |
Syntax
Like whitespace characters, line terminator characters are used to improve source text readability and to separate tokens (indivisible lexical units) from each other. However, unlike whitespace 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. A line terminator cannot occur within any token, not even a string. Line terminators also affect the process of automatic semicolon insertion (see section 7.8).
The following characters are considered to be line terminators:
Unicode Value | Name | Formal Name |
---|---|---|
\u000A | Line Feed | <LF> |
\u000D | Carriage Return | <CR> |
Syntax
Description
Comments can be either single or multi-line. Multi-line comments cannot nest.
Because a single-line comment can contain any 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 section7.8.2).
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.
Syntax
Syntax
Description
Reserved words cannot be used as identifiers.
Syntax
The following tokens are ECMAScript keywords and may not be used as identifiers in ECMAScript programs.
Syntax
break | for | new | var |
continue | function | return | void |
delete | if | this | while |
else | in | typeof | 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.
Syntax
abstract | do | import | short |
boolean | double | instanceof | static |
byte | enum | int | super |
case | export | interface | switch |
catch | extends | long | synchronized |
char | final | native | throw |
class | finally | package | throws |
const | float | private | transient |
debugger | goto | protected | try |
default | implements | public | volatile |
Description
An identifier is a character sequence of unlimited length, where each character in the sequence must be a letter, a decimal digit, an underscore (_) character, or a dollar sign ($) character, and the first character may not be a decimal digit. ECMAScript identifiers are case sensitive: identifiers whose characters differ in any way, even if only in case, are considered to be distinct. The dollar sign ($) character is intended for use only in mechanically generated code.
Syntax
a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
$ | _ |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Syntax
= | > | < | == | <= | >= |
!= | , | ! | ~ | ? | : |
. | && | || | ++ | -- | + |
- | * | / | & | | | ^ |
% | << | >> | >>> | += | -= |
*= | /= | &= | |= | ^= | %= |
<<= | >>= | >>>= | ( | ) | { |
} | [ | ] | ; |
Syntax
Syntax
Semantics
The value of the null literal null is the sole value of the Null type, namely null.
Syntax
Semantics
The value of the Boolean literal true is a value of the Boolean type, namely true.
The value of the Boolean literal false is a value of the Boolean type, namely false.
Syntax
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | A | B | C | D | E | F |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
Semantics
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, if this mathematical value is not representable using the number type, it is rounded to either the nearest representable value type above the mathematical value or the nearest representable value below the mathematical value.
The rounding mechanism is unspecified, but implementations are encouraged to use IEEE 754 round-to-nearest.
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 (in the sense defined in section8.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
A string literal is zero or more characters enclosed in single or double quotes. Each character may be represented by an escape sequence.
Syntax
' | " | \ | b | f | n | r | t |
0 | 1 | 2 | 3 |
The definitions of the nonterminals HexDigit and OctalDigit are given in section 7.7.3. SourceCharacter is described in sections 2 and 6.
A string literal stands for a value of the String type. The string value (SV) of the literal is described in terms of character values (CV) contributed by the various parts of the string literal. As part of this process, some characters within the string literal are interpreted as having a mathematical value (MV), as described below or in section 7.7.3.
Escape Sequence | Unicode Value | Name | Symbol |
---|---|---|---|
\b | \u0008 | backspace | <BS> |
\t | \u0009 | horizontal tab | <HT> |
\n | \u000A | line feed (new line) | <LF> |
\f | \u000C | form feed | <FF> |
\r | \u000D | carriage return | <CR> |
\" | \u0022 | double quote | " |
\' | \u0027 | single quote | ' |
\\ | \u005C | backslash | \ |
NOTE A LineTerminator character cannot appear in a string literal, even if preceded by a backslash \. 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.
Certain ECMAScript statements (empty statement, variable statement, expression statement, continue statement, break statement, and return statement) must each be terminated with a semicolon. Such a semicolon 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.
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.
These are the only restricted productions in the grammar:
The practical effect of these restricted productions is as follows:
The resulting practical advice to ECMAScript programmers is:
The source
{ 1 2 } 3is not a valid sentence in the ECMAScript grammar, even with the automatic semicolon insertion rules. In contrast, the source
{ 1 2 } 3is 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 place where a semicolon is needed is within the header of a for statement. Automatic semicolon insertion never occurs within the header of a for statement.
The source
return a + bis 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 ++cis 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 = dis 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.
A value is an entity that takes on one of nine types. There are nine types ( Undefined, Null, Boolean, String, Number, Object, Reference, List, and Completion ). Values of type Reference, List, and Completion are used only as intermediate results of expression evaluation and cannot be stored to properties of objects.
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value is of type 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 Unicode characters (more properly referred to as code points; see section 6). Each character is regarded as occupying a position within the sequence. These positions are identified by nonnegative integers. The leftmost character (if any) is at position 0, the next character (if any) at position 1, and so on. The length of a string is the number of distinct positions within it. The empty string has length zero and therefore contains no characters.
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, assuming that the globally defined variable NaN has not been altered by program execution.) In some implementations, external code might be able to detect a difference between various Non-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, assuming that the globally defined variable Infinity has not been altered by program execution.)
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 there is a corresponding negative number 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 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
s * m * 2ewhere 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 denormalized, having the form
s * m * 2ewhere 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 sections 9.5 and 9.6, respectively.
An Object is an unordered collection of properties. Each property consists of a name, a value and a set of attributes.
A property can have zero or more attributes from the following set:
Attribute | Description |
---|---|
ReadOnly |
The property is a read-only property. Attempts by ECMAScript code to write to the property will be ignored. (Note, however, that in some cases the value of a property with the ReadOnly attribute may change over time because of actions taken by the underlying implementation; therefore ``ReadOnly'' does not mean ``constant and unchanging''!). |
DontEnum |
The property is not to be enumerated by a for-in enumeration (section 12.6.3). |
DontDelete |
Attempts to delete the property will be ignored. See the description of the delete operator in section 11.4.1. |
Internal |
Internal properties have no name and are not directly accessible via the property accessor operators. How these properties are accessed is implementation specific. How and when some of these properties are used is specified by the language specification. |
Internal properties and methods are not exposed in the language. For the purposes of this document, their names are enclosed in double square brackets [[ ]]. When an algorithm uses an internal property of an object and the object does not implement the indicated internal property, a runtime error is generated.
There are two types of access for exposed properties: get and put, corresponding to retrieval and assignment, respectively.
Native ECMAScript objects have an internal property called [[Prototype]]. The value of this property is either null or an object and is used for implementing inheritance. Properties of the [[Prototype]] object are exposed as properties of the child object for the purposes of get access, but not for put access.
The following table summarises the internal properties used by this specification. The description indicates their behaviour for native ECMAScript objects. Host objects may implement these internal methods with any implementation-dependent behaviour, or it may be that a host object implements only some internal methods and not others.
Property | Parameters | Description |
---|---|---|
[[Prototype]] | none | The prototype of this object. |
[[Class]] | none | A string value indicating the kind of this object. |
[[Value]] | none | Internal state information associated with this object. |
[[Get]] | (PropertyName) | Returns the value of the property. |
[[Put]] | (PropertyName, Value) | Sets the specified property to Value. |
[[CanPut]] | (PropertyName) | Returns a boolean value indicating whether a [[Put]] operation with the specified PropertyName will succeed. |
[HasProperty]] | (PropertyName) | Returns a boolean value indicating whether the object already has a member with the given name. |
[[Delete]] | (PropertyName) | Removes the specified property from the object. |
[[DefaultValue]] | (Hint) | Returns a default value for the object, which should be a primitive value (not an object or reference). |
[[Construct]] | a list of argument values provided by the caller | Constructs an object. Invoked via the new operator. Objects that implement this internal method are called constructors. |
[[Call]] | a list of argument values provided by the caller | Executes code associated with the object. Invoked via a function call expression. Objects that implement this internal method are called functions. |
Every object must implement the [[Class]] property and the [[Get]], [[Put]], [[HasProperty]], [[Delete]], and [[DefaultValue]] methods, even host objects. (Note, however, that the [[DefaultValue]] method may, for some objects, simply generate a runtime error.)
The value of the [[Prototype]] property must be either an object or null, and every [[Prototype]] chain must have finite length (that is, starting from any object, recursively accessing the [[Prototype]] property must eventually lead to a null value). Whether or not a native object can have a host object as its [[Prototype]] depends on the implementation.
The value of the [[Class]] property is defined by this specification for every kind of built-in object. The value of the [[Class]] property of a host object may be any value, even a value used by a built-in object for its [[Class]] property. Note that this specification does not provide any means for a program to access the value of a [[Class]] property; that value is used internally to distinguish different kinds of built-in objects.
Every native object implements the [[Get]], [[Put]], [[CanPut]], [[HasProperty]], and [[Delete]] methods in the manner described in sections 8.6.2.1, 8.6.2.2, 8.6.2.3, 8.6.3.4, and 8.6.2.5, respectively, except that Array objects have a slightly different implementation of the [[Put]] method (section 15.4.5.1). Host objects may implement these methods in any manner; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.
In the following algorithm descriptions, assume O is a native ECMAScript object and P is a string.
When the [[Get]] method of O is called with property name P, the following steps are taken:
When the [[Put]] method of O is called with property P and value V, the following steps are taken:
Note, however, that if O is an Array object, it has a more elaborate [[Put]] method (section 15.4.5.1).
The [[CanPut]] method is used only by the [[Put]] method.
When the [[CanPut]] method of O is called with property P, the following steps are taken:
When the [[Delete]] method of O is called with property name P, the following steps are taken:
When the [[DefaultValue]] method of O is called with hint String, the following steps are taken:
When the [[DefaultValue]] method of O is called with hint Number, the following steps are taken:
When the [[DefaultValue]] method of O is called with no hint, then it behaves as if the hint were Number, unless O is a Date object (see section ), in which case it behaves as if the hint were String.
The internal Reference type is not a language data type. It is defined by this specification purely for expository purposes. An implementation of ECMAScript must behave as if it produced and operated upon references in the manner described here. However, a value of type Reference is used only as an intermediate result of expression evaluation and cannot be stored as the value of a variable or property.
The Reference type is used to explain the behaviour of such operators as delete, typeof, and the assignment operators. For example, the left-hand operand of an assignment is expected to produce a reference. The behaviour of assignment could, instead, be explained entirely in terms of a case analysis on the syntactic form of the left-hand operand of an assignment operator, but for one difficulty: function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference. (Another reason not to use a syntactic case analysis is that it would be lengthy and awkward, affecting many parts of the specification.)
Another use of the Reference type is to explain the determination of the this value for a function call.
A Reference is a reference to a property of an object. A Reference consists of two components, the base object and the property name.
The following abstract operations are used in this specification to describe the behaviour of references:
The internal List type is not a language data type. It is defined by this specification purely for expository purposes. An implementation of ECMAScript must behave as if it produced and operated upon List values in the manner described here. However, a value of the List type is used only as an intermediate result of expression evaluation and cannot be stored as the value of a variable or property.
The List type is used to explain the evaluation of argument lists (section 11.2.4) in new expressions and in function calls. Values of the List type are simply ordered sequences of values. These sequences may be of any length.
The internal Completion type is not a language data type. It is defined by this specification purely for expository purposes. An implementation of ECMAScript must behave as if it produced and operated upon Completion values in the manner described here. However, a value of the Completion type is used only as an intermediate result of statement evaluation and cannot be stored as the value of a variable or property.
The Completion type is used to explain the behaviour of statements (break, continue, and return) that perform nonlocal transfers of control. Values of the Completion type have one of the following forms:
Any completion of one of the four forms that carries a value V is called a value completion. Any completion of one of the first two forms is called a normal completion; any other completion is called an abrupt completion. Any completion of a form that mentions break is called a break completion. Any completion of a form that mentions continue is called a continue completion. Any completion of a form that mentions return is called a return completion.
The ECMAScript runtime system performs automatic type conversion as needed. To clarify the semantics of certain constructs it is useful to define a set of conversion operators. These operators are not a part of the language; they are defined here to aid the specification of the semantics of the language. The conversion operators are polymorphic; that is, they can accept a value of any standard type, but not of type Reference, List, or Completion (the internal types).
The operator ToPrimitive takes a Value argument and an optional PreferredType argument. The operator ToPrimitive converts its value 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 the following table:
Input Type | Result |
---|---|
Undefined | The result equals the input argument (no conversion). |
Null | The result equals the input argument (no conversion). |
Boolean | The result equals the input argument (no conversion). |
Number | The result equals the input argument (no conversion). |
String | The result equals the input argument (no conversion). |
Object | Return a default value for the Object. The default value of an object is retrieved by calling the internal [[DefaultValue]] method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] method is defined by this specification for all native ECMAScript objects (see section 8.6.2.6). If the return value is of type Object or Reference, a runtime error is generated. |
The operator ToBoolean converts its argument to a value of type Boolean according to the following table:
Input Type | Result |
---|---|
Undefined | false |
Null | false |
Boolean | The result equals the input argument (no conversion). |
Number | The result is false if the argument is +0, -0, or NaN; otherwise the result is true. |
String | The result is false if the argument is the empty string (its length is zero); otherwise the result is true. |
Object | true |
The operator ToNumber converts its argument to a value of type Number according to the following table:
Input Type | Result |
---|---|
Undefined | NaN |
Null | +0 |
Boolean | The result is 1 if the argument is true. The result is +0 if the argument is false. |
Number | The result equals the input 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.
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
e | E |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | A | B | C | D | E | F |
Some differences should be noted between the syntax of a StringNumericLiteral and a NumericLiteral (section 7.7.3):
The conversion of a string to a number value is similar overall to the determination of the number value for a numeric literal (section 7.7.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, ideally using IEEE 754 round-to-nearest mode, to a representable value of the number type.
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-whitespace 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 section 8.5), unless the literal includes a StrDecimalLiteral 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 (either it is not 0 or (there is a nonzero digit to its left and there is a nonzero digit, not in the ExponentPart, to its right)).
The operator ToInteger converts its argument to an integral numeric value. This operator functions as follows:
The operator ToInt32 converts its argument to one of 232 integer values in the range -231 through 231-1 , inclusive. This operator functions as follows:
NOTE Given the above definition of ToInt32:The ToInt32 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 operator ToUint32 converts its argument to one of 232 integer values in the range 0 through 232-1, inclusive. This operator functions as follows:
NOTE Given the above definition of ToUInt32::Step 5 is the only difference between ToUint32 and ToInt32.
The ToUint32 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 operator ToUint16 converts its argument to one of 216 integer values in the range 0 through 216-1, inclusive. This operator functions as follows:
NOTE Given the above definition of ToUInt16::The substitution of 216 for 232 in step 4 is the only difference between ToUint32 and ToUnit16.
ToUint16 maps -0 to +0.
The operator ToString converts its argument to a value of type String according to the following table:
Input Type | Result |
---|---|
Undefined | "undefined" |
Null | "null" |
Boolean | If the argument is true, then the result is "true". |
Number | See note below. |
String | Return the input argument (no conversion) |
Object | Apply the following steps:
|
The operator ToString converts a number m to string format as follows:
NOTE The following observations may be useful as guidelines for implementations, but are not part of the normative requirements of this standard.If x is any number value other than -0, then ToNumber(ToString(x)) is exactly the same number value as x.
The least significant digit of s is not always uniquely determined by the requirements listed in step 5.
For implementations which 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 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. Note that k is the number of digits in the decimal representation of s, that s is not divisible by 10. If there are two such possible values of s, choose the one that is even.
Implementors 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://cm.bell-labs.com/netlib/fp/dtoa.c.gz and as http://cm.bell-labs.com/netlib/fp/g_fmt.c.gz and may also be found at the various netlib mirror sites.
The operator ToObject converts its argument to a value of type Object according to the following table:
Input Type | Result |
---|---|
Undefined | Generate a runtime error. |
Null | Generate a runtime error. |
Boolean | Create a new boolean object whose default value is the value of the boolean. See section 15.6 for a description of boolean objects. |
Number | Create a new number object whose default value is the value of the number. See section 15.7 for a description of number objects. |
String | Create a new string object whose default value is the value of the string. See section 15.5 for a description of string objects. |
Object | The result is the input argument (no conversion). |
When control is transferred to ECMAScript executable code, control is entering an execution context. Active execution contexts logically form a stack. The top execution context on this logical stack is the running execution context.
10.1.1 -- Function Objects
There are four types of function objects:
There are five types of executable ECMAScript source text:
Every execution context has associated with it a variable object. Variables declared in the source text are added as properties of the variable object. For global and eval code, functions defined in the source text are added as properties of the variable object. Function declarations in other types of code are not allowed by the grammar. For function, anonymous, and implementation-supplied code, parameters are added as properties of the variable object.
Which object is used as the variable object and what attributes are used for the properties depends on the type of code, but the remainder of the behaviour is generic:
Every execution context has associated with it a scope chain. This is logically a list of objects that are searched when binding an Identifier. When control enters an execution context, the scope chain is created and is populated with an initial set of objects, depending on the type of code. When control leaves the execution context, the scope chain is destroyed.
During execution, the scope chain of the execution context is affected only by WithStatement. When execution enters a with block, the object specified in the with statement is added to the front of the scope chain. When execution leaves a with block, whether normally or via a break or continue statement, the object is removed from the scope chain. The object being removed will always be the first object in the scope chain.
During execution, the syntactic production PrimaryExpression : Identifier is evaluated using the following algorithm:
The result of binding an identifier is always a value of type Reference with its member name component equal to the identifier string.
There is a unique global object, which is created before control enters any execution context. Initially the global object has the following properties:
As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.
When control enters an execution context for declared function code, anonymous code or implementation-supplied code, an object called the activation object is created and associated with the execution context. The activation object is initialised with a property with name arguments and property attributes { DontDelete }. The initial value of this property is the arguments object described below.
The activation object is then used as the variable object for the purposes of variable instantiation.
When a value is to be returned from the call to a function, its activation object is no longer needed and may be permanently decommissioned.
The activation object is purely a specification mechanism. It is impossible for an ECMAScript program to access the activation object. It can access members of the activation object, but not the activation object itself. When the call operation is applied to a Reference value whose base object is an activation object, null is used as the this value of the call.
There is a this value associated with every active execution context. The this value depends on the caller and the type of code being executed and is determined when control enters the execution context. The this value associated with an execution context is immutable.
When control enters an execution context for declared function code, anonymous code, or implementation-supplied code, an arguments object is created and initialised as follows:
When control enters an execution context, the scope chain is created and initialised, variable instantiation is performed, and the this value is determined.
The initialisation of the scope chain, variable instantiation, and the determination of the this value depend on the type of code being entered.
When control enters an execution context for eval code, the previous active execution context, referred to as the calling context, is used to determine the scope chain, the variable object, and the this value. If there is no calling context, then initialising the scope chain, variable instantiation, and determination of the this value are performed just as for global code.
Syntax
The this keyword evaluates to the this value of the execution context.
An Identifier is evaluated using the scoping rules stated in section 10.1.4. The result of an Identifier is always a value of type Reference.
A Literal is evaluated as described in section 7.7.
The production PrimaryExpression : ( Expression ) is evaluated as follows:
NOTE This algorithm does not apply GetValue to Result(1). The principal motivation for this is so that operators such as delete and typeof may be applied to parenthesised expressions.
Syntax
Properties are accessed by name, using either the dot notation:
MemberExpression . Identifieror the bracket notation:
CallExpression . Identifier
MemberExpression [ Expression ]
CallExpression [ Expression ]
The dot notation is explained by the following syntactic conversion:
MemberExpression . Identifieris identical in its behaviour to
MemberExpression [ <identifier-string> ]and similarly
CallExpression . Identifieris identical in its behaviour to
CallExpression [ <identifier-string> ]where <identifier-string> is a string literal containing the same sequence of characters as the Identifier.
The production MemberExpression : MemberExpression [ Expression ] is evaluated as follows:
The production CallExpression : CallExpression [ Expression ] is evaluated in exactly the same manner, except that the contained CallExpression is evaluated in step 1.
The production NewExpression : new NewExpression is evaluated as follows:
The production MemberExpression : new MemberExpression Arguments is evaluated as follows:
The production CallExpression : MemberExpression Arguments is evaluated as follows:
The production CallExpression : CallExpression Arguments is evaluated in exactly the same manner, except that the contained CallExpression is evaluated in step 1.
NOTE Result(8) will never be of type Reference if Result(3) is a native ECMAScript object. Whether calling a host object can return a value of type Reference is implementation-dependent.
The evaluation of an argument list produces an internal list of values (section 8).
The production Arguments : ( ) is evaluated as follows:
The production Arguments : ( ArgumentList ) is evaluated as follows:
The production ArgumentList : AssignmentExpression is evaluated as follows:
The production ArgumentList : ArgumentList , AssignmentExpression is evaluated as follows:
Syntax
The production MemberExpression : MemberExpression++ is evaluated as follows:
The production MemberExpression : MemberExpression -- is evaluated as follows:
Syntax
The production UnaryExpression : delete UnaryExpression is evaluated as follows:
The production UnaryExpression : void UnaryExpression is evaluated as follows:
The production UnaryExpression : typeof UnaryExpression is evaluated as follows:
Type | Result |
---|---|
Undefined | "undefined" |
Null | "object" |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Object (native and doesn't implement [[Call]]) | "object" |
Object (native and implements [[Call]]) | "function" |
Object (host) | Implementation-dependent |
The production UnaryExpression : ++ UnaryExpression is evaluated as follows:
The production UnaryExpression : -- UnaryExpression is evaluated as follows:
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
The unary - operator converts its operand to Number type and then negates it. Note that negating +0 produces -0, and negating -0 produces +0.
The production UnaryExpression : - UnaryExpression is evaluated as follows:
The production UnaryExpression : ~ UnaryExpression is evaluated as follows:
The production UnaryExpression : ! UnaryExpression is evaluated as follows:
Syntax
Semantics
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 double-precision arithmetic:
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:
The binary % operator is said to yield the remainder of its operands from an implied division; the left operand is the dividend and the right operand is the divisor. In C and C++, the remainder operator accepts only integral operands, but 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 a ECMAScript floating-point remainder operation is determined by the rules of IEEE arithmetic:
Syntax
The addition operator either performs string concatenation or numeric addition.
The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:
NOTE No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native 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. Host objects may handle the absence of a hint in some other manner.
The production AdditiveExpression : AdditiveExpression - MultiplicativeExpression is evaluated as follows:
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 double-precision arithmetic:
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).
Syntax
Semantics
The result of evaluating ShiftExpression is always truncated to 32 bits. If the result of evaluating ShiftExpression produces a fractional component, the fractional component is discarded. The result of evaluating an AdditiveExpresion that is the right-hand operand of a shift operator is always truncated to five bits.
Performs a bitwise left shift operation on the left operand by the amount specified by the right operand.
The production ShiftExpression : ShiftExpression << AdditiveExpression is evaluated as follows:
Performs a sign-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
The production ShiftExpression : ShiftExpression >> AdditiveExpression is evaluated as follows:
Performs a zero-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
The production ShiftExpression : ShiftExpression >>> AdditiveExpression is evaluated as follows:
Syntax
Semantics
The result of evaluating RelationalExpression is always of type Boolean, reflecting whether the relationship named by the operator holds between its two operands.
The production RelationalExpression : RelationalExpression < ShiftExpression is evaluated as follows:
The production RelationalExpression : RelationalExpression > ShiftExpression is evaluated as follows:
The production RelationalExpression : RelationalExpression <= ShiftExpression is evaluated as follows:
The production RelationalExpression : RelationalExpression >= ShiftExpression is evaluated as follows:
The comparison x < y, where x and y are values, produces true, false, or undefined (which indicates that at least one operand is NaN). Such a comparison is performed as follows:
NOTE The comparison of strings uses a simple lexicographic ordering on sequences of Unicode code point 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 2.0 specification.
Syntax
Semantics
The result of evaluating EqualityExpression is always of type Boolean, reflecting whether the relationship named by the operator holds between its two operands.
The production EqualityExpression : EqualityExpression == RelationalExpression is evaluated as follows:
The production EqualityExpression : EqualityExpression != RelationalExpression is evaluated as follows:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
NOTE Given the above definition of equality::
- String comparison can be forced by: "" + a == "" + b.
- Numeric comparison can be forced by: a - 0 == b - 0.
- Boolean comparison can be forced by: !a == !b.
- 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.
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.
Comparison of strings uses a simple equality test on sequences of Unicode code point 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 2.0 specification.
Syntax
Semantics
The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:
Syntax
Semantics
The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:
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.
Syntax
Semantics
The production ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression is evaluated as follows:
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.
Syntax
= | *= | /= | %= | += | -= | <<= | >>= | >>>= | &= | ^= | |= |
The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows:
The production AssignmentExpression : LeftHandSideExpression @= AssignmentExpression, where @ represents one of the operators indicated above, is evaluated as follows:
Syntax
Semantics
The production Expression : Expression , AssignmentExpression is evaluated as follows:
Syntax
Syntax
Semantics
The production Block : { } is evaluated as follows:
The production Block : { StatementList }is evaluated as follows:
The production StatementList : Statement is evaluated as follows:
The production StatementList : StatementList Statement is evaluated as follows:
Syntax
Description
If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in section 10.1.3. Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in section 10.1.3) using property attributes { DontDelete }. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to the undefined value when created. A variable with an Initializer is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.
Semantics
The production VariableStatement : var VariableDeclarationList ; is evaluated as follows:
The production VariableDeclarationList :VariableDeclaration is evaluated as follows:
The production VariableDeclarationList : VariableDeclarationList , VariableDeclaration is evaluated as follows:
The production VariableDeclaration : Identifier is evaluated as follows:
The production VariableDeclaration : Identifier Initializer is evaluated as follows:
The production Initializer : = AssignmentExpression is evaluated as follows:
Syntax
Semantics
The production EmptyStatement : ; is evaluated as follows:
Syntax
Semantics
The production ExpressionStatement : Expression ; is evaluated as follows:
Syntax
Each 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.
Semantics
The production IfStatement : if ( Expression ) Statement else Statement is evaluated as follows:
The production IfStatement : if ( Expression ) Statement is evaluated as follows:
An iteration statement consists of a header (which consists of a keyword and a parenthesized control construct) and a body (which consists of a Statement).
Syntax
The production IterationStatement : while ( Expression ) Statement is evaluated as follows:
The production IterationStatement : for (Expressionopt ; Expressionopt ; Expressionopt) Statement is evaluated as follows:
The production IterationStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement is evaluated as follows:
The production IterationStatement : for ( LeftHandSideExpression in Expression ) Statement is evaluated as follows:
The production IterationStatement : for ( var VariableDeclaration in Expression ) Statement is evaluated as follows:
The mechanics of enumerating the properties (step 5 in the first algorithm, step 10 in the second) is implementation-dependent. The order of enumeration is defined by the object. 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.
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.
Syntax
Semantics
An ECMAScript program is considered syntactically incorrect if it contains a continue statement that is not within a while or for statement. The continue statement is evaluated as:
Syntax
Semantics
An ECMAScript program is considered syntactically incorrect if it contains a break statement that is not within a while or for statement. The break statement is evaluated as:
Syntax
Semantics
An ECMAScript program is considered syntactically incorrect if it contains a return statement that is not within the Block of a FunctionDeclaration. It causes a function to cease execution and return a value to the caller. If Expression is omitted, the return value is the undefined value. Otherwise, the return value is the value of Expression.
The production ReturnStatement :: return [no LineTerminator here] Expressionopt ; is evaluated as:
Syntax
Description
The with statement adds a computed object to the front of the scope chain of the current execution context, then executes a statement with this augmented scope chain, then restores the scope chain.
Semantics
The production WithStatement : with ( Expression ) Statement is evaluated as follows:
NOTE No matter how control leaves the embedded Statement, whether normally or by some form of abrupt completion, the scope chain is always restored to its former state.
Syntax
Semantics
Defines a property of the global object whose name is the Identifier following the function keyword and whose value is a function object with the given parameter list and statements. If the function definition is supplied text to the eval function and the calling context has an activation object, then the declared function is added to the activation object instead of to the global object. See section 10.1.3.
The production FunctionDeclaration : function Identifier ( ) Block is processed for function declarations as follows:
The production FunctionDeclaration : function Identifier ( FormalParameterList ) Block is processed for function declarations as follows:
Syntax
Semantics
The production Program : SourceElements is evaluated as follows:
The production SourceElements : SourceElement is processed for function declarations as follows:
The production SourceElements : SourceElement is evaluated as follows:
The production SourceElements : SourceElements SourceElement is processed for function declarations as follows:
The production SourceElements : SourceElements SourceElement is evaluated as follows:
The production SourceElement : Statement is processed for function declarations by taking no action.
The production SourceElement : Statement is evaluated as follows:
The production SourceElement : FunctionDeclaration is processed for function declarations as follows:
The production SourceElement : FunctionDeclaration is evaluated as follows:
There are certain built-in objects available whenever an ECMAScript program begins execution. One, the global object, is in the scope chain of the executing program. Others are accessible as initial properties of the global object.
Many built-in objects are functions: they can be invoked with arguments. Some of them furthermore are constructors: they are functions intended for use with the new operator. For each built-in function, this specification describes the arguments required by that function and properties of the function object. For each built-in constructor, this specification furthermore describes properties of the prototype object of that constructor and properties of specific object instances returned by a new expression that invokes that constructor.
Unless otherwise specified in the description of a particular function, if a function or constructor described in this section is given fewer arguments than the function is specified to require, the function or constructor shall behave exactly as if it had been given sufficient additional arguments, each such argument being the undefined value.
Every built-in function and every built-in constructor has the Function prototype object, which is the value of the expression Function.prototype (15.3.2.1), as the value of its internal [[Prototype]] property, except the Function prototype object itself.
Every built-in prototype object has the Object prototype object, which is the value of the expression Object.prototype (15.2.3.1), as the value of its internal [[Prototype]] property, except the Object prototype object itself. Every native prototype object associated with a program-created function also has the Object prototype object as the value of its internal [[Prototype]] property.
None of the built-in functions described in this section shall implement the internal [[Construct]] method unless otherwise specified in the description of a particular function. None of the built-in functions described in this section shall initially have a prototype property unless otherwise specified in the description of a particular function. Every built-in function object described in this section -- whether as a constructor, an ordinary function, or both -- has a length property whose value is an integer. Unless otherwise specified, this value is equal to the number of named arguments shown in the section heading for the function description; for example, the function object that is the initial value of the indexOf property of the String prototype object is described under the section heading ``indexOf(searchString, position)'' which shows the two named arguments searchString and position; therefore the value of the length property of that function object is 2. Sometimes the same function object is described under more than one heading to emphasise its different behaviours when given different numbers of actual arguments; in such a case, unless otherwise specified, the length value is the largest number of arguments shown in any applicable section heading. For example, the function object that is the initial value of the Object property of the global object is described under four separate headings: as a function of one argument (section 15.2.1.1), as a function of zero arguments (section 15.2.1.2), as a constructor of one argument (15.2.2.1), and as a constructor of zero arguments (15.2.2.2). The largest number of arguments described is 1, so the value of the length property of that function object is 1.
In every case, a length property of a built-in function object described in this section has the attributes { ReadOnly, DontDelete, DontEnum } (and no others). Every other property described in this section has the attribute { DontEnum } (and no others) unless otherwise specified.
The global object does not have a [[Construct]] property; it is not possible to use the global object as a constructor with the new operator.
The global object does not have a [[Call]] property; it is not possible to invoke the global object as a function.
The value of the [[Prototype]] property of the global object is implementation-dependent.
The initial value of NaN is NaN.
The initial value of Infinity is +∞.
When the eval function is called with one argument x, the following steps are taken:
If value of the eval property is used in any way other than a direct call (that is, other than by the explicit use of its name as an Identifier which is the MemberExpression in a CallExpression), or if the eval property is assigned to, a runtime error may be generated.
The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix.
When the parseInt function is called, the following steps are taken:
Note that parseInt may interpret only a leading portion of the string as an integer value; it ignores any characters that cannot be interpreted as part of the notation of an integer, and no indication is given that any such characters were ignored.
The parseFloat function produces a number value dictated by interpretation of the contents of the string argument as a decimal literal.
When the parseFloat function is called, the following steps are taken:
Note that parseFloat may interpret only a leading portion of the string as a number value; it ignores any characters that cannot be interpreted as part of the notation of an decimal literal, and no indication is given that any such characters were ignored.
The escape function computes a new version of a string value in which certain characters have been replaced by a hexadecimal escape sequence.
For those characters being replaced whose Unicode encoding is 0xFF or less, a two-digit escape sequence of the form %xx is used. For those characters being replaced whose Unicode encoding is greater than 0xFF, a four-digit escape sequence of the form %uxxxx is used.
When the escape function is called with one argument string, the following steps are taken:
NOTE The encoding is partly based on the encoding described in RFC1738, but the entire encoding specified in this standard is described above without regard to the contents of RFC1738.
The unescape function computes a new version of a string value in which each escape sequences of the sort that might be introduced by the escape function is replaced with the character that it represents.
When the unescape function is called with one argument string, the following steps are taken:
Applies ToNumber to its argument, then returns true if the result is NaN, and otherwise returns false.
Applies ToNumber to its argument, then returns false if the result is NaN, +∞, or -∞ , and otherwise returns true.
See sections 15.2.1 and 15.2.2.
See sections 15.3.1 and 15.3.2.
See sections 15.4.1 and 15.4.2.
See sections 15.5.1 and 15.5.2.
See sections 15.6.1 and 15.6.2.
See sections 15.7.1 and 15.7.2.
See section 15.9.2 .
See section 15.8.
When Object is called as a function rather than as a constructor, it performs a type conversion.
When the Object function is called with one argument value, the following steps are taken:
When the Object function is called with no arguments, the following step is taken:
When Object is called as part of a new expression, it is a constructor that may create an object.
When the Object constructor is called with one argument value, the following steps are taken:
When the Object constructor is called with no argument, the following step is taken:
The value of the internal [[Prototype]] property of the Object constructor is the Function prototype object.
Besides the internal [[Call]] and [[Construct]] properties and the length property, the Object constructor has the following properties:
The initial value of Object.prototype is the built-in Object prototype object (15.2.4).
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The value of the internal [[Prototype]] property of the Object prototype object is null.
The initial value of Object.prototype.constructor is the built-in Object constructor.
When the toString method is called, the following steps are taken:
As a rule, the valueOf method for an object simply returns the object; but if the object is a ``wrapper'' for a host object, as may perhaps be created by the Object constructor (see section 15.2.2.1), then the contained host object should be returned.
Object instances have no special properties beyond those inherited from the Object prototype object.
When Function is called as a function rather than as a constructor, it creates and initialises a new function object. Thus the function call Function(...) is equivalent to the object creation expression new Function(...) with the same arguments.
When the Function function is called with some arguments p1, p2, . . . , pn, body (where n might be 0, that is, there are no ``p'' arguments, and where body might also not be provided), the following steps are taken:
When Function is called as part of a new expression, it is a constructor: it initialises the newly created object.
The last argument specifies the body (executable code) of a function; any preceding arguments specify formal parameters.
When the Function constructor is called with some arguments p1, p2, . . . , pn, body (where n might be 0, that is, there are no ``p'' arguments, and where body might also not be provided), the following steps are taken:
Note that it is permissible but not necessary to have one argument for each formal parameter to be specified. For example, all three of the following expressions produce the same result:
new Function("a", "b", "c", "return a+b+c") new Function("a, b, c", "return a+b+c") new Function("a,b", "c", "return a+b+c")
A prototype property is automatically created for every function, against the possibility that the function will be used as a constructor.
The initial value of Function.prototype is the built-in Function prototype object (15.3.4).
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The length property is 1. (Of course, the Function constructor accepts more than one argument, because it accepts a variable number of arguments.)
The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined.
The value of the internal [[Prototype]] property of the Function prototype object is the Object prototype object (15.3.2.1).
It is a function with an ``empty body''; if it is invoked, it merely returns undefined.
The Function prototype object does not have a valueOf property of its own; however, it inherits the valueOf property from the Object prototype object.
The initial value of Function.prototype.constructor is the built-in Function constructor.
An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of whitespace, line terminators, and semicolons within the representation string is implementation-dependent.
The toString function is not generic; it generates a runtime error if its this value is not a Function object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Every function instance has a [[Call]] property and a [[Construct]] property.
The value of the length property is usually an integer that indicates the ``typical'' number of arguments expected by the function. However, the language permits the function to be invoked with some other number of arguments. The behaviour of a function when invoked on a number of arguments other than the number specified by its length property depends on the function.
The value of the prototype property is used to initialise the internal [[Prototype]] property of a newly created object before the Function object is invoked as a constructor for that newly created object.
Array objects give 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. Every Array object has a length property whose value is always an integer with positive sign and less than 232. It is always the case that 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 properties of the Array object itself and is unaffected by length or array index properties that may be inherited from its prototype.
When Array is called as a function rather than as a constructor, it creates and initialises a new array object. Thus the function call Array (...) is equivalent to the object creation expression new Array (...) with the same arguments.
An array is created and returned as if by the expression new Array(item0, item1, . . .).
An array is created and returned as if by the expression new Array(len).
An array is created and returned as if by the expression new Array().
When Array is called as part of a new expression, it is a constructor: it initialises the newly created object.
This description applies if and only if the Array constructor is given two or more arguments.
The [[Prototype]] property of the newly constructed object is set to the original Array prototype object, the one that is the initial value of Array.prototype (15.4.3.1).
The [[Class]] property of the newly constructed object is set to "Array".
The length property of the newly constructed object is set to the number of arguments.
The 0 property of the newly constructed object is set to item0; the 1 property of the newly constructed object is set to item1; and, in general, for as many arguments as there are, the k property of the newly constructed object is set to argument k, where the first argument is considered to be argument number 0.
The [[Prototype]] property of the newly constructed object is set to the original Array prototype object, the one that is the initial value of Array.prototype (15.4.3.1). The [[Class]] property of the newly constructed object is set to "Array".
If the argument len is a number and ToUint32(len) is equal to len, then the length property of the newly constructed object is set to ToUint32(len). If the argument len is a number and ToUint32(len) is not equal to len, a runtime error is generated.
If the argument len is not a number, then the length property of the newly constructed object is set to 1 and the 0 property of the newly constructed object is set to len.
The [[Prototype]] property of the newly constructed object is set to the original Array prototype object, the one that is the initial value of Array.prototype (15.4.3.1). The [[Class]] property of the newly constructed object is set to "Array".
The length property of the newly constructed object is set to +0.
The value of the internal [[Prototype]] property of the Array constructor is the Function prototype object.
Besides the internal [[Call]] and [[Construct]] properties, the Array constructor has the following properties:
The initial value of Array.prototype is the built-in Array prototype object (15.4.4).
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The length property is 1. (Of course, the Array constructor accepts more than one argument, because it accepts a variable number of arguments.)
The value of the internal [[Prototype]] property of the Array prototype object is the Object prototype object (15.2.3.1).
Note that the Array prototype object is itself an array; it has a length property (whose initial value is +0) and the special internal [[Put]] method described in section 15.4.5.1. In following descriptions of functions that are properties of the Array prototype object, the phrase ``this object'' refers to the object that is the this value for the invocation of the function. It is permitted for this to refer to an object for which the value of the internal [[Class]] property is not "Array".
The Array prototype object does not have a valueOf property of its own; however, it inherits the valueOf property from the Object prototype object.
The initial value of Array.prototype.constructor is the built-in Array constructor.
The elements of this object are converted to strings, and these strings are then concatenated, separated by comma characters. The result is the same as if the built-in join method were invoked for this object with no argument.
The elements of the array are converted to strings, and these strings are then concatenated, separated by occurrences of the separator. If no separator is provided, a single comma is used as the separator.
When the join method is called with one argument separator, the following steps are taken:
Note that the join function is intentionally generic; it does not require that its this value be an Array object. Therefore, it can be transferred to other kinds of objects for use as a method. Whether the join function can be applied successfully to a host object is implementation-dependent.
The elements of the array are rearranged so as to reverse their order. The object is returned as the result of the call.
Note that the reverse function is intentionally generic; it does not require that its this value be an Array object. Therefore, it can be transferred to other kinds of objects for use as a method. Whether the reverse function can be applied successfully to a host object is implementation-dependent.
The elements of this array are sorted. The sort is not necessarily stable. If comparefn is supplied, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.
If comparefn is supplied and is not a consistent comparison function for the elements of this array (see below), the result is implementation-defined. Otherwise the following steps are taken:
The returned object must have the following two properties.
Here the notation old[j] is used to refer to the hypothetical result of calling the [[Get]] method of this object with argument j before this function is executed, and the notation new[j] to refer to the hypothetical result of calling the [[Get]] method of this object with argument j after this function has been executed.
A function is a consistent comparison function for a set of values if
When the SortCompare operator is called with two arguments x and y, the following steps are taken:
Note that, because undefined always compares greater than any other value, undefined and non-existent property values always sort to the end of the result. It is implementation-dependent whether or not such properties will exist or not at the end of the array when the sort is concluded.
Note that the sort function is intentionally generic; it does not require that its this value be an Array object. Therefore, it can be transferred to other kinds of objects for use as a method. Whether the sort function can be applied successfully to a host object is implementation-dependent .
Array instances inherit properties from the Array prototype object and also have the following properties.
Array objects use a variation of the [[Put]] method used for other native ECMAScript objects (section 8.6.2.2).
Assume A is an Array object and P is a string.
When the [[Put]] method of A is called with property P and value V, the following steps are taken:
The length property of this Array object is always numerically greater than the name of every property whose name is an array index.
The length property has the attributes { DontEnum, DontDelete }.
When String is called as a function rather than as a constructor, it performs a type conversion.
Returns a string value (not a string object) computed by ToString(value).
Returns the empty string "".
When String is called as part of a new expression, it is a constructor: it initialises the newly created object.
The [[Prototype]] property of the newly constructed object is set to the original String prototype object, the one that is the initial value of String.prototype (15.5.3.1).
The [[Class]] property of the newly constructed object is set to "String".
The [[Value]] property of the newly constructed object is set to ToString(value).
The [[Prototype]] property of the newly constructed object is set to the original String prototype object, the one that is the initial value of String.prototype (15.5.3.1).
The [[Class]] property of the newly constructed object is set to "String".
The [[Value]] property of the newly constructed object is set to the empty string.
The value of the internal [[Prototype]] property of the String constructor is the Function prototype object.
Besides the internal [[Call]] and [[Construct]] properties and the length property, the String constructor has the following properties:
The initial value of String.prototype is the built-in String prototype object (15.5.4).
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
Returns a string value containing as many characters as the number of arguments. Each argument specifies one character of the resulting string, with the first argument specifying the first character, and so on, from left to right. An argument is converted to a character by applying the operation ToUint16 (section 9.7) and regarding the resulting 16-bit integer as the Unicode code point encoding of a character. If no arguments are supplied, the result is the empty string.
The String prototype object is itself a string object (its [[Class]] is "String") whose value is an empty string.
The value of the internal [[Prototype]] property of the String prototype object is the Object prototype object (15.2.3.1).
The initial value of String.prototype.constructor is the built-in String constructor.
Returns this string value. (Note that, for a string object, the toString method happens to return the same thing as the valueOf method.)
The toString function is not generic; it generates a runtime error if its this value is not a string object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Returns this string value.
The valueOf function is not generic; it generates a runtime error if its this value is not a string object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Returns a string containing the character at position pos in the string resulting from converting this object to a string. If there is no character at that position, the result is the empty string. The result is a string value, not a string object.
If pos is a value of Number type that is an integer, then the result of x.charAt(pos) is equal to the result of x.substring(pos, pos+1).
When the charAt method is called with one argument pos, the following steps are taken:
NOTE The charAt function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
Returns a number (a nonnegative integer less than 216) representing the Unicode code point encoding of the character at position pos in the string resulting from converting this object to a string. If there is no character at that position, the result is NaN.
When the charCodeAt method is called with one argument pos, the following steps are taken:
NOTE The charCodeAt function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
If the given searchString appears as a substring of the result of converting this object to a string, at one or more positions that are at or to the right of the specified position, then the index of the leftmost such position is returned; otherwise, -1 is returned. If position is undefined or not supplied, 0 is assumed, so as to search all of the string.
When the indexOf method is called with two arguments searchString and position, the following steps are taken:
NOTE The indexOf function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
If the given searchString appears as a substring of the result of converting this object to a string, at one or more positions that are at or to the left of the specified position, then the index of the rightmost such position is returned; otherwise, -1 is returned. If position is undefined or not supplied, the length of the string value is assumed, so as to search all of the string.
When the lastIndexOf method is called with two arguments searchString and position, the following steps are taken:
NOTE The lastIndexOf function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
Returns an Array object into which substrings of the result of converting this object to a string have been stored. The substrings are determined by searching from left to right for occurrences of the given separator; these occurrences are not part of any substring in the returned array, but serve to divide up the string value. The separator may be a string of any length.
As a special case, if the separator is the empty string, the string is split up into individual characters; the length of the result array equals the length of the string, and each substring contains one character.
If the separator is not supplied, then the result array contains just one string, which is the string.
When the split method is called with one argument separator, the following steps are taken:
NOTE The split function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
Returns a substring of the result of converting this object to a string, starting from character position start and running to the end of the string. The result is a string value, not a string object.
If the argument is NaN or negative, it is replaced with zero; if the argument is larger than the length of the string, it is replaced with the length of the string.
When the substring method is called with one argument start, the following steps are taken:
Returns a substring of the result of converting this object to a string, starting from character position start and running to, but not including, character position end of the string. The result is a string value, not a string object.
If either argument is NaN or negative, it is replaced with zero; if either argument is larger than the length of the string, it is replaced with the length of the string.
If start is larger than end, they are swapped.
When the substring method is called with two arguments start and end, the following steps are taken:
NOTE The substring function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
Returns a string equal in length to the length of the result of converting this object to a string. The result is a string value, not a string object.
Every character of the result is equal to the corresponding character of the string, unless that character has a Unicode 2.0 lowercase equivalent, in which case the lowercase equivalent is used instead. (The canonical Unicode 2.0 case mapping shall be used, which does not depend on implementation or locale.)
Note that the toLowerCase function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
Returns a string equal in length to the length of the result of converting this object to a string. The result is a string value, not a string object.
Every character of the result is equal to the corresponding character of the string, unless that character has a Unicode 2.0 uppercase equivalent, in which case the uppercase equivalent is used instead. (The canonical Unicode 2.0 case mapping shall be used, which does not depend on implementation or locale.)
Note that the toUpperCase function is intentionally generic; it does not require that its this value be a string object. Therefore, it can be transferred to other kinds of objects for use as a method.
String instances inherit properties from the String prototype object and also have a [[Value]] property and a length property.
The [[Value]] property is the string value represented by this string object.
The number of characters in the String value represented by this string object.
Once a string object is created, this property is unchanging. It has the attributes { DontEnum, DontDelete, ReadOnly }.
When Boolean is called as a function rather than as a constructor, it performs a type conversion.
Returns a Boolean value (not a boolean object) computed by ToBoolean(value).
Returns false.
When Boolean is called as part of a new expression, it is a constructor: it initialises the newly created object.
The [[Prototype]] property of the newly constructed object is set to the original Boolean prototype object, the one that is the initial value of Boolean.prototype (15.6.3.1).
The [[Class]] property of the newly constructed boolean object is set to "Boolean".
The [[Value]] property of the newly constructed boolean object is set to ToBoolean(value).
The [[Prototype]] property of the newly constructed object is set to the original Boolean prototype object, the one that is the initial value of Boolean.prototype (15.6.3.1).
The [[Class]] property of the newly constructed boolean object is set to "Boolean".
The [[Value]] property of the newly constructed boolean object is set to false.
The value of the internal [[Prototype]] property of the Boolean constructor is the Function prototype object.
Besides the internal [[Call]] and [[Construct]] properties and the length property, the Boolean constructor has the following property:
The initial value of Boolean.prototype is the built-in Boolean prototype object (15.6.4).
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The Boolean prototype object is itself a boolean object (its [[Class]] is "Boolean") whose value is false.
The value of the internal [[Prototype]] property of the Boolean prototype object is the Object prototype object (15.2.3.1).
In following descriptions of functions that are properties of the Boolean prototype object, the phrase ``this boolean object'' refers to the object that is the this value for the invocation of the function; it is a runtime error if this does not refer to an object for which the value of the internal [[Class]] property is "Boolean". Also, the phrase ``this boolean value'' refers to the boolean value represented by this boolean object, that is, the value of the internal [[Value]] property of this boolean object.
The initial value of Boolean.prototype.constructor is the built-in Boolean constructor.
If this boolean value is true, then the string "true" is returned. Otherwise, this boolean value must be false, and the string "false" is returned.
The toString function is not generic; it generates a runtime error if its this value is not a boolean object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Returns this boolean value.
The valueOf function is not generic; it generates a runtime error if its this value is not a boolean object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Boolean instances have no special properties beyond those inherited from the Boolean prototype object.
When Number is called as a function rather than as a constructor, it performs a type conversion.
Returns a number value (not a Number object) computed by ToNumber(value).
Returns +0.
When Number is called as part of a new expression, it is a constructor: it initialises the newly created object.
The [[Prototype]] property of the newly constructed object is set to the original Number prototype object, the one that is the initial value of Number.prototype (15.7.3.1).
The [[Class]] property of the newly constructed object is set to "Number".
The [[Value]] property of the newly constructed object is set to ToNumber(value).
The [[Prototype]] property of the newly constructed object is set to the original Number prototype object, the one that is the initial value of Number.prototype (15.7.3.1).
The [[Class]] property of the newly constructed object is set to "Number".
The [[Value]] property of the newly constructed object is set to +0.
The value of the internal [[Prototype]] property of the Number constructor is the Function prototype object.
Besides the internal [[Call]] and [[Construct]] properties and the length property, the Number constructor has the following property:
The initial value of Number.prototype is the built-in Number prototype object.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The value of Number.MAX_VALUE is the largest positive finite value of the number type, which is approximately 1.7976931348623157e308.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The value of Number.MIN_VALUE is the smallest positive nonzero value of the number type, which is approximately 5e-324.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The value of Number.NaN is NaN.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The value of Number.NEGATIVE_INFINITY is -∞ .
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The value of Number.POSITIVE_INFINITY is +∞.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The Number prototype object is itself a Number object (its [[Class]] is "Number") whose value is +0.
The value of the internal [[Prototype]] property of the Number prototype object is the Object prototype object (15.2.3.1).
In following descriptions of functions that are properties of the Number prototype object, the phrase ``this Number object'' refers to the object that is the this value for the invocation of the function; it is a runtime error if this does not refer to an object for which the value of the internal [[Class]] property is "Number". Also, the phrase ``this number value'' refers to the number value represented by this Number object, that is, the value of the internal [[Value]] property of this Number object.
The initial value of Number.prototype.constructor is the built-in Number constructor.
If the radix is the number 10 or not supplied, then this number value is given as an argument to the ToString operator; the resulting string value is returned.
If the radix is supplied and is an integer from 2 to 36, but not 10, the result is a string, the choice of which is implementation-dependent.
The toString function is not generic; it generates a runtime error if its this value is not a Number object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Returns this number value.
The valueOf function is not generic; it generates a runtime error if its this value is not a Number object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Number instances have no special properties beyond those inherited from the Number prototype object.
The Math object is merely a single object that has some named properties, some of which are functions.
The value of the internal [[Prototype]] property of the Math object is the Object prototype object (15.2.3.1).
The Math object does not have a [[Construct]] property; it is not possible to use the Math object as a constructor with the new operator.
The Math object does not have a [[Call]] property; it is not possible to invoke the Math object as a function.
NOTE In this specification, the phrase ``the number value for x'' has a technical meaning defined in section 8.5.
The number value for e, the base of the natural logarithms, which is approximately 2.7182818284590452354.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The number value for the natural logarithm of 10, which is approximately 2.302585092994046.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The number value for the natural logarithm of 2, which is approximately 0.6931471805599453.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The number value for the base-2 logarithm of e, the base of the natural logarithms; this value is approximately 1.4426950408889634. (Note that the value of Math.LOG2E is approximately the reciprocal of the value of Math.LN2.)
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The number value for the base-10 logarithm of e, the base of the natural logarithms; this value is approximately 0.4342944819032518. (Note that the value of Math.LOG10E is approximately the reciprocal of the value of Math.LN10.)
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The number value for π, the ratio of the circumference of a circle to its diameter, which is approximately 3.14159265358979323846.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The number value for the square root of 1/2, which is approximately 0.7071067811865476. (Note that the value of Math.SQRT1_2 is approximately the reciprocal of the value of Math.SQRT2.)
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The number value for the square root of 2, which is approximately 1.4142135623730951.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
Every function listed in this section applies the ToNumber operator to each of its arguments (in left-to-right order if there is more than one) and then performs a computation on the resulting number value(s).
The behaviour of the functions acos, asin, atan, atan2, cos, exp, log, pow, sin, and sqrt is not precisely specified here except to require specific results for certain argument values that represent boundary cases of interest.. For other argument values, these functions are intended to compute approximations to the results of familiar mathematical functions, but some latitude is allowed in the choice of approximation algorithms. The general intent is that an implementor should be able to use the same mathematical library for ECMAScript on a given hardware platform that is available to C programmers on that platform.
Although the choice of algorithms is left to the implementation, it is recommended (but not specified by this standard) that implementations use the approximation algorithms for IEEE 754 arithmetic contained in fdlibm, the freely distributable mathematical library from Sun Microsystems (fdlibm-comment@sunpro.eng.1.com).
Returns the absolute value of its argument; in general, the result has the same magnitude as the argument but has positive sign.
Returns an implementation-dependent approximation to the arc cosine of the argument. The result is expressed in radians and ranges from +0 to +π.
Returns an implementation-dependent approximation to the arc sine of the argument. The result is expressed in radians and ranges from -π/2 to +π/2.
Returns an implementation-dependent approximation to the arc tangent of the argument. The result is expressed in radians and ranges from -π/2 to +π/2.
Returns an implementation-dependent approximation to the arc tangent of the quotient y/x of the arguments y and x, where the signs of the arguments are used to determine the quadrant of the result. Note that it is intentional and traditional for the two-argument arc tangent function that the argument named y be first and the argument named x be second. The result is expressed in radians and ranges from -π to +π .
Returns the smallest (closest to -∞) number value that is not less than the argument and is equal to a mathematical integer. If the argument is already an integer, the result is the argument itself.
The value of Math.ceil(x) is the same as the value of -Math.floor(-x).
Returns an implementation-dependent approximation to the cosine of the argument. The argument is expressed in radians.
Returns an implementation-dependent approximation to the exponential function of the argument (e raised to the power of the argument, where e is the base of the natural logarithms).
Returns the greatest (closest to +∞) number value that is not greater than the argument and is equal to a mathematical integer. If the argument is already an integer, the result is the argument itself.
NOTE The value of Math.floor(x) is the same as the value of -Math.ceil(-x).
Returns an implementation-dependent approximation to natural logarithm of the argument.
Returns the larger of the two arguments.
Returns the smaller of the two arguments.
Returns an implementation-dependent approximation to the result of raising x to the power y.
Returns a number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.
Returns the number value that is closest to the argument and is equal to a mathematical integer. If two integer number values are equally close to the argument, then the result is the number value that is closer to +∞. If the argument is already an integer, the result is the argument itself.
NOTE Math.round(3.5) returns 4, but Math.round(-3.5) returns -3.
The value of Math.round(x) is the same as the value of Math.floor(x+0.5), except when x is -0 or is less than 0 but greater than or equal to -0.5; for these cases Math.round(x) returns -0, but Math.floor(x+0.5) returns +0.
Returns an implementation-dependent approximation to the sine of the argument. The argument is expressed in radians.
Returns an implementation-dependent approximation to the square root of the argument.
Returns an implementation-dependent approximation to the tangent of the argument. The argument is expressed in radians.
A Date object contains a number indicating a particular instant in time to within a millisecond. The number may also be NaN, indicating that the Date object does not represent a specific instant of time.
The following sections define a number of functions for operating on time values. Note that, in every case, if any argument to such a function is NaN, the result will be NaN.
Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. Leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript number values can represent all integers from -9,007,199,254,740,991 to 9,007,199,254,740,991; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly -100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.
A given time value t belongs to day number
Day(t) = floor(t / msPerDay)where the number of milliseconds per day is
msPerDay = 86400000The remainder is called the time within the day:
TimeWithinDay(t) = t modulo msPerDay
ECMAScript uses an extrapolated Gregorian system to map a day number to a year number and to determine the month and date within that year. In this system, leap years are precisely those which are (divisible by 4) and ((not divisible by 100) or (divisible by 400)). The number of days in year number y is therefore defined by
All non-leap years have 365 days with the usual number of days per month and leap years have an extra day in February. The day number of the first day of year y is given by:
The time value of the start of a year is:
A time value determines a year by:
The leap-year function is 1 for a time within a leap year and otherwise is zero:
Months are identified by an integer in the range 0 to 11, inclusive. The mapping MonthFromTime(t) from a time value t to a month number is defined by:
MonthFromTime(t) | = 0 | if 0 | ≤ DayWithinYear(t) < 31 |
= 1 | if 31 | ≤ DayWithinYear(t) < 59+InLeapYear(t) | |
= 2 | if 59+InLeapYear(t) | ≤ DayWithinYear (t) < 90+InLeapYear(t) | |
= 3 | if 90+InLeapYear(t) | ≤ DayWithinYear (t) < 120+InLeapYear(t) | |
= 4 | if 120+InLeapYear(t) | ≤ DayWithinYear (t) < 151+InLeapYear(t) | |
= 5 | if 151+InLeapYear(t) | ≤ DayWithinYear (t) < 181+InLeapYear(t) | |
= 6 | if 181+InLeapYear(t) | ≤ DayWithinYear (t) < 212+InLeapYear(t) | |
= 7 | if 212+InLeapYear(t) | ≤ DayWithinYear (t) < 243+InLeapYear(t) | |
= 8 | if 243+InLeapYear(t) | ≤ DayWithinYear (t) < 273+InLeapYear(t) | |
= 9 | if 273+InLeapYear(t) | ≤ DayWithinYear (t) < 304+InLeapYear(t) | |
= 10 | if 304+InLeapYear(t) | ≤ DayWithinYear (t) < 334+InLeapYear(t) | |
= 11 | if 334+InLeapYear(t) | ≤ DayWithinYear (t) < 365+InLeapYear(t) |
A month value of
Note that MonthFromTime(0) = 0, corresponding to Thursday, 01 January, 1970.
A date number is identified by an integer in the range 1 through 31, inclusive. The mapping DateFromTime(t) from a time value t to a month number is defined by:
DateFromTime(t) | = DayWithinYear(t)+1 | if MonthFromTime(t)=0 |
= DayWithinYear(t)-30 | if MonthFromTime(t)=1 | |
= DayWithinYear(t)-58-InLeapYear(t) | if MonthFromTime(t)=2 | |
= DayWithinYear(t)-89-InLeapYear(t) | if MonthFromTime(t)=3 | |
= DayWithinYear(t)-119-InLeapYear(t) | if MonthFromTime(t)=4 | |
= DayWithinYear(t)-150-InLeapYear(t) | if MonthFromTime(t)=5 | |
= DayWithinYear(t)-180-InLeapYear(t) | if MonthFromTime(t)=6 | |
= DayWithinYear(t)-211-InLeapYear(t) | if MonthFromTime(t)=7 | |
= DayWithinYear(t)-242-InLeapYear(t) | if MonthFromTime(t)=8 | |
= DayWithinYear(t)-272-InLeapYear(t) | if MonthFromTime(t)=9 | |
= DayWithinYear(t)-303-InLeapYear(t) | if MonthFromTime(t)=10 | |
= DayWithinYear(t)-333-InLeapYear(t) | if MonthFromTime(t)=11 |
The weekday for a particular time value t is defined as
A weekday value of
An implementation of ECMAScript is expected to determine the local time zone adjustment. The local time zone adjustment is a value LocalTZA measured in milliseconds which when added to UTC represents the local standard time. Daylight saving time is not reflected by LocalTZA. The value LocalTZA does not vary with time but depends only on the geographic location.
An implementation of ECMAScript is expected to determine the daylight saving time algorithm. The algorithm to determine the daylight saving time adjustment DaylightSavingTA(t), measured in milliseconds, must depend only on four things:
The implementation of ECMAScript should not try to determine whether the exact time was subject to daylight saving time, but just whether daylight saving time would have been in effect if the current daylight saving time algorithm had been used at the time. This avoids complications such as taking into account the years that the locale observed daylight saving time year round.
If the underlying operating system provides functionality for determining daylight saving time, the implementation of ECMAScript is free to map the year in question to an equivalent year (same leap-year-ness and same starting week day for the year) for which the operating system provides daylight saving time information. The only restriction is that all equivalent years should produce the same result.
Conversion from UTC to local time is defined by
Conversion from local time to UTC is defined by
Note that UTC(LocalTime(t)) is not necessarily always equal to t.
The following functions are useful in decomposing time values:
The operator MakeTime calculates a number of milliseconds from its four arguments, which must be ECMAScript number values. This operator functions as follows:
The operator MakeDay calculates a number of days from its three arguments, which must be ECMAScript number values. This operator functions as follows:
The operator MakeDate calculates a number of milliseconds from its two arguments, which must be ECMAScript number values. This operator functions as follows:
The operator TimeClip calculates a number of milliseconds from its argument, which must be an ECMAScript number value. This operator functions as follows:
NOTE The point of step 3 is that an implementation is permitted a choice of internal representations of time values, for example as a 64-bit signed integer or as a 64-bit floating-point value. Depending on the implementation, this internal representation may or may not distinguish -0 and +0.
When Date is called as a function rather than as a constructor, it returns a string representing the current time (UTC). Note that the function call Date (...) is not equivalent to the object creation expression new Date(...) with the same arguments.
The arguments are accepted but are completely ignored. A string is created and returned as if by the expression (new Date ()).toString().
The arguments are accepted but are completely ignored. A string is created and returned as if by the expression (new Date ()).toString().
The arguments are accepted but are completely ignored. A string is created and returned as if by the expression (new Date ()).toString().
The arguments are accepted but are completely ignored. A string is created and returned as if by the expression (new Date ()).toString().
The arguments are accepted but are completely ignored. A string is created and returned as if by the expression (new Date ()).toString().
The arguments are accepted but are completely ignored. A string is created and returned as if by the expression (new Date ()).toString().
The argument is accepted but is completely ignored. A string is created and returned as if by the expression (new Date ()).toString().
A string is created and returned as if by the expression (new Date ()).toString().
When Date is called as part of a new expression, it is a constructor: it initialises the newly created object.
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype.
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set as follows:
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype .
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set as follows:
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype .
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set as follows:
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype .
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set as follows:
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype .
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set as follows:
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype .
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set as follows:
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype .
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set as follows:
The [[Prototype]] property of the newly constructed object is set to the original Date prototype object, the one that is the initial value of Date.prototype .
The [[Class]] property of the newly constructed object is set to "Date".
The [[Value]] property of the newly constructed object is set to the current time (UTC).
The value of the internal [[Prototype]] property of the Date constructor is the Function prototype object.
Besides the internal [[Call]] and [[Construct]] properties and the length property (whose value is 7), the Date constructor has the following properties:
The initial value of Date.prototype is the built-in Date prototype object.
This property shall have the attributes { DontEnum, DontDelete, ReadOnly }.
The parse function applies the ToString operator to its argument and interprets the resulting string as a date; it returns a number, the UTC time value corresponding to the date. The string may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the string.
If x is any Date object whose milliseconds amount is zero within a particular implementation of ECMAScript, then all of the following expressions should produce the same numeric value in that implementation, if all the properties referenced have their initial values:
x.valueOf() Date.parse(x.toString()) Date.parse(x.toGMTString())However, the expression
Date.parse(x.toLocaleString())is not required to produce the same number value as the preceding three expressions and, in general, the value produced by Date.parse is implementation-dependent when given any string value that could not be produced in that implementation by the toString or toGMTString method.
When the UTC function is called with seven arguments, the following steps are taken:
NOTE The UTC function differs from the Date constructor in two ways: it returns a time value as a number, rather than creating a Date object, and it interprets the arguments in UTC rather than as local time.
When the UTC function is called with six arguments, the following steps are taken:
NOTE The UTC function differs from the Date constructor in two ways: it returns a time value as a number, rather than creating a Date object, and it interprets the arguments in UTC rather than as local time.
When the UTC function is called with five arguments, the following steps are taken:
NOTE The UTC function differs from the Date constructor in two ways: it returns a time value as a number, rather than creating a Date object, and it interprets the arguments in UTC rather than as local time.
When the UTC function is called with four arguments, the following steps are taken:
NOTE The UTC function differs from the Date constructor in two ways: it returns a time value as a number, rather than creating a Date object, and it interprets the arguments in UTC rather than as local time.
When the UTC function is called with three arguments, the following steps are taken:
NOTE The UTC function differs from the Date constructor in two ways: it returns a time value as a number, rather than creating a Date object, and it interprets the arguments in UTC rather than as local time.
The behaviour of the UTC function with two arguments is implementation-dependent.
The behaviour of the UTC function with one argument is implementation-dependent.
The behaviour of the UTC function with no arguments is implementation-dependent.
The Date prototype object is itself a Date object (its [[Class]] is "Date") whose value is NaN.
The value of the internal [[Prototype]] property of the Date prototype object is the Object prototype object (15.2.3.1).
In following descriptions of functions that are properties of the Date prototype object, the phrase ``this Date object'' refers to the object that is the this value for the invocation of the function; it is a runtime error if this does not refer to an object for which the value of the internal [[Class]] property is "Date". Also, the phrase ``this time value'' refers to the number value for the time represented by this Date object, that is, the value of the internal [[Value]] property of this Date object.
The initial value of Date.prototype.constructor is the built-in Date constructor.
This function returns a string value. The contents of the string are implementation-dependent, but are intended to represent the Date in a convenient, human-readable form in the current time zone.
The toString function is not generic; it generates a runtime error if its this value is not a Date object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
The valueOf function returns a number, which is this time value.
The valueOf function is not generic; it generates a runtime error if its this value is not a Date object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
NOTE This function is not part of this specification. The function getFullYear is much to be preferred for nearly all purposes, because it avoids the ``year 2000 problem.'' If implemented, getYear may follow the following rules:
- Let t be this time value.
- If t is NaN, return NaN.
- Return YearFromTime(LocalTime(t)) -1900.
Returns the difference between local time and UTC time in minutes.
If ms is not specified, this behaves as if ms were specified with the value getMilliseconds( ).
If ms is not specified, this behaves as if ms were specified with the value getUTCMilliseconds( ).
If sec is not specified, this behaves as if sec were specified with the value getSeconds ( ).
If ms is not specified, this behaves as if ms were specified with the value getMilliseconds( ).
If sec is not specified, this behaves as if sec were specified with the value getUTCSeconds ( ).
If ms is not specified, this behaves as if ms were specified with the value getUTCMilliseconds( ).
If min is not specified, this behaves as if min were specified with the value getMinutes( ).
If sec is not specified, this behaves as if sec were specified with the value getSeconds ( ).
If ms is not specified, this behaves as if ms were specified with the value getMilliseconds( ).
If min is not specified, this behaves as if min were specified with the value getUTCMinutes( ).
If sec is not specified, this behaves as if sec were specified with the value getUTCSeconds ( ).
If ms is not specified, this behaves as if ms were specified with the value getUTCMilliseconds( ).
If date is not specified, this behaves as if date were specified with the value getDate( ).
If date is not specified, this behaves as if date were specified with the value getUTCDate( ).
If mon is not specified, this behaves as if mon were specified with the value getMonth( ).
If date is not specified, this behaves as if date were specified with the value getDate( ).
If mon is not specified, this behaves as if mon were specified with the value getUTCMonth( ).
If date is not specified, this behaves as if date were specified with the value getUTCDate( ).
NOTE This function is not part of this specification. The function setFullYear is much to be preferred for nearly all purposes, because it avoids the ``year 2000 problem.'' If implemented, setYear may follow the following rules:
- Let t be the result of LocalTime(this time value); but if this time value is NaN, let t be +0.
- Call ToNumber(year).
- If Result(2) is NaN, set the [[Value]] property of the this value to NaN and return NaN.
- If Result(2) is not NaN and 0 = ToInteger(Result(2)) = 99 then Result(4) is ToInteger(Result(2)) + 1900. Otherwise, Result(4) is Result(2).
- Compute MakeDay(Result(4), MonthFromTime(t), DateFromTime(t)).
- Compute UTC(MakeDate(Result(5), TimeWithinDay(t))).
- Set the [[Value]] property of the this value to TimeClip(Result(6)).
- Return the value of the [[Value]] property of the this value.
This function returns a string value. The contents of the string are implementation-dependent, but are intended to represent the Date in a convenient, human-readable form appropriate to the geographic or cultural locale.
This function returns a string value. The contents of the string are implementation-dependent, but are intended to represent the Date in a convenient, human-readable form in UTC.
The function object that is the initial value of Date.prototype.toGMTString is the same function object that is the initial value of Date.prototype.toUTCString. The toGMTString property is provided principally for compatibility with old code. It is recommended that the toUTCString property be used in new ECMAScript code.
Date instances have no special properties beyond those inherited from the Date prototype object.
This specification specifies the last possible moment an error occurs. A given implementation may generate errors sooner (e.g., at compile-time). Doing so may cause differences in behaviour among implementations. Notably, if runtime errors become catchable in future versions, a given error would not be catchable if an implementation generates the error at compile-time rather than runtime.
An ECMAScript compiler should detect errors at compile time in all code presented to it, even code that detailed analysis might prove to be ``dead'' (never executed). A programmer should not rely on the trick of placing code within an if (false) statement, for example, to try to suppress compile-time error detection.
In general, if a compiler can prove that a construct cannot execute without error under any circumstances, then it may issue a compile-time error even though the construct might never be executed at all.
Printed copies can be ordered from:
Fax: -- +41 22 849.60.01
Internet: -- documents@ecma.ch
Files can be downloaded from our FTP site, ftp.ecma.ch. This Standard is available from library ECMA-ST as a compacted, self-expanding file in MSWord 6.0 format (file E262-DOC.EXE) and as an Acrobat PDF file (file E262-PDF.PDF). File E262-EXP.TXT gives a short presentation of the Standard.
Our web site, http://www.ecma.ch, gives full information on ECMA, ECMA activities, ECMA Standards and Technical Reports.
ECMA
114 Rue du Rhône
CH-1204 Geneva
Switzerland
This Standard ECMA-262 is available free of charge in printed form and as a file.
See inside cover page for instructions