19.2 Function Properties of the Global Object
19.2.1 eval ( x )
This function is the %eval% intrinsic object.
It performs the following steps when called:
- Return ?
PerformEval (x,false ,false ).
19.2.1.1 PerformEval ( x, strictCaller, direct )
The abstract operation PerformEval takes arguments x (an
Assert : If direct isfalse , then strictCaller is alsofalse .- If x
is not a String , return x. - Let evalRealm be
the current Realm Record . - NOTE: In the case of a
direct eval , evalRealm is therealm of both the caller ofeval
and of theeval
function itself. - Perform ?
HostEnsureCanCompileStrings (evalRealm, « », x, direct). - Let inFunction be
false . - Let inMethod be
false . - Let inDerivedConstructor be
false . - Let inClassFieldInitializer be
false . - If direct is
true , then- Let thisEnvRec be
GetThisEnvironment (). - If thisEnvRec is a
Function Environment Record , then- Let F be thisEnvRec.[[FunctionObject]].
- Set inFunction to
true . - Set inMethod to thisEnvRec.HasSuperBinding().
- If F.[[ConstructorKind]] is
derived , set inDerivedConstructor totrue . - Let classFieldInitializerName be F.[[ClassFieldInitializerName]].
- If classFieldInitializerName is not
empty , set inClassFieldInitializer totrue .
- Let thisEnvRec be
- Perform the following substeps in an
implementation-defined order, possibly interleaving parsing and error detection:- Let script be
ParseText (StringToCodePoints (x),Script ). - If script is a
List of errors, throw aSyntaxError exception. - If script
Contains ScriptBody isfalse , returnundefined . - Let body be the
ScriptBody of script. - If inFunction is
false and bodyContains NewTarget , throw aSyntaxError exception. - If inMethod is
false and bodyContains SuperProperty , throw aSyntaxError exception. - If inDerivedConstructor is
false and bodyContains SuperCall , throw aSyntaxError exception. - If inClassFieldInitializer is
true andContainsArguments of body istrue , throw aSyntaxError exception.
- Let script be
- If strictCaller is
true , let strictEval betrue . - Else, let strictEval be
IsStrict of script. - Let runningContext be the
running execution context . - NOTE: If direct is
true , runningContext will be theexecution context that performed thedirect eval . If direct isfalse , runningContext will be theexecution context for the invocation of theeval
function. - If direct is
true , then- Let lexEnv be
NewDeclarativeEnvironment (runningContext's LexicalEnvironment). - Let varEnv be runningContext's VariableEnvironment.
- Let privateEnv be runningContext's PrivateEnvironment.
- Let lexEnv be
- Else,
- Let lexEnv be
NewDeclarativeEnvironment (evalRealm.[[GlobalEnv]]). - Let varEnv be evalRealm.[[GlobalEnv]].
- Let privateEnv be
null .
- Let lexEnv be
- If strictEval is
true , set varEnv to lexEnv. - If runningContext is not already suspended, suspend runningContext.
- Let evalContext be a new
ECMAScript code execution context . - Set evalContext's Function to
null . - Set evalContext's
Realm to evalRealm. - Set evalContext's ScriptOrModule to runningContext's ScriptOrModule.
- Set evalContext's VariableEnvironment to varEnv.
- Set evalContext's LexicalEnvironment to lexEnv.
- Set evalContext's PrivateEnvironment to privateEnv.
- Push evalContext onto the
execution context stack ; evalContext is now therunning execution context . - Let result be
Completion (EvalDeclarationInstantiation (body, varEnv, lexEnv, privateEnv, strictEval)). - If result is a
normal completion , then- Set result to
Completion (Evaluation of body).
- Set result to
- If result is a
normal completion and result.[[Value]] isempty , then- Set result to
NormalCompletion (undefined ).
- Set result to
- Suspend evalContext and remove it from the
execution context stack . - Resume the context that is now on the top of the
execution context stack as therunning execution context . - Return ? result.
The eval code cannot instantiate variable or function bindings in the variable environment of the calling context that invoked the eval if either the code of the calling context or the eval code is let
, const
, or class
declarations are always instantiated in a new LexicalEnvironment.
19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm, parameterStrings, bodyString, direct )
The
parameterStrings represents the strings that, when using one of the function eval
call.
direct signifies whether the evaluation is a
The default implementation of HostEnsureCanCompileStrings is to return
19.2.1.3 EvalDeclarationInstantiation ( body, varEnv, lexEnv, privateEnv, strict )
The abstract operation EvalDeclarationInstantiation takes arguments body (a
- Let varNames be the
VarDeclaredNames of body. - Let varDeclarations be the
VarScopedDeclarations of body. - If strict is
false , then- If varEnv is a
Global Environment Record , then- For each element name of varNames, do
- If varEnv.HasLexicalDeclaration(name) is
true , throw aSyntaxError exception. - NOTE:
eval
will not create a global var declaration that would be shadowed by a global lexical declaration.
- If varEnv.HasLexicalDeclaration(name) is
- For each element name of varNames, do
- Let thisEnv be lexEnv.
Assert : The following loop will terminate.- Repeat, while thisEnv is not varEnv,
- If thisEnv
is not an Object Environment Record , then- NOTE: The environment of with statements cannot contain any lexical declaration so it doesn't need to be checked for var/let hoisting conflicts.
- For each element name of varNames, do
- If ! thisEnv.HasBinding(name) is
true , then- Throw a
SyntaxError exception. - NOTE: Annex
B.3.4 defines alternate semantics for the above step.
- Throw a
- NOTE: A
direct eval will not hoist var declaration over a like-named lexical declaration.
- If ! thisEnv.HasBinding(name) is
- Set thisEnv to thisEnv.[[OuterEnv]].
- If thisEnv
- If varEnv is a
- Let privateIdentifiers be a new empty
List . - Let pointer be privateEnv.
- Repeat, while pointer is not
null ,- For each
Private Name binding of pointer.[[Names]], do- If privateIdentifiers does not contain binding.[[Description]], append binding.[[Description]] to privateIdentifiers.
- Set pointer to pointer.[[OuterPrivateEnvironment]].
- For each
- If
AllPrivateIdentifiersValid of body with argument privateIdentifiers isfalse , throw aSyntaxError exception. - Let functionsToInitialize be a new empty
List . - Let declaredFunctionNames be a new empty
List . - For each element d of varDeclarations, in reverse
List order, do- If d is not either a
VariableDeclaration , aForBinding , or aBindingIdentifier , thenAssert : d is either aFunctionDeclaration , aGeneratorDeclaration , anAsyncFunctionDeclaration , or anAsyncGeneratorDeclaration .- NOTE: If there are multiple function declarations for the same name, the last declaration is used.
- Let fn be the sole element of the
BoundNames of d. - If declaredFunctionNames does not contain fn, then
- If varEnv is a
Global Environment Record , then- Let fnDefinable be ? varEnv.CanDeclareGlobalFunction(fn).
- If fnDefinable is
false , throw aTypeError exception.
- Append fn to declaredFunctionNames.
- Insert d as the first element of functionsToInitialize.
- If varEnv is a
- If d is not either a
- Let declaredVarNames be a new empty
List . - For each element d of varDeclarations, do
- If d is either a
VariableDeclaration , aForBinding , or aBindingIdentifier , then- For each String vn of the
BoundNames of d, do- If declaredFunctionNames does not contain vn, then
- If varEnv is a
Global Environment Record , then- Let vnDefinable be ? varEnv.CanDeclareGlobalVar(vn).
- If vnDefinable is
false , throw aTypeError exception.
- If declaredVarNames does not contain vn, then
- Append vn to declaredVarNames.
- If varEnv is a
- If declaredFunctionNames does not contain vn, then
- For each String vn of the
- If d is either a
- NOTE: Annex
B.3.2.3 adds additional steps at this point. - NOTE: No abnormal terminations occur after this algorithm step unless varEnv is a
Global Environment Record and theglobal object is aProxy exotic object . - Let lexDeclarations be the
LexicallyScopedDeclarations of body. - For each element d of lexDeclarations, do
- NOTE: Lexically declared names are only instantiated here but not initialized.
- For each element dn of the
BoundNames of d, do- If
IsConstantDeclaration of d istrue , then- Perform ? lexEnv.CreateImmutableBinding(dn,
true ).
- Perform ? lexEnv.CreateImmutableBinding(dn,
- Else,
- Perform ? lexEnv.CreateMutableBinding(dn,
false ).
- Perform ? lexEnv.CreateMutableBinding(dn,
- If
- For each
Parse Node f of functionsToInitialize, do- Let fn be the sole element of the
BoundNames of f. - Let fo be
InstantiateFunctionObject of f with arguments lexEnv and privateEnv. - If varEnv is a
Global Environment Record , then- Perform ? varEnv.CreateGlobalFunctionBinding(fn, fo,
true ).
- Perform ? varEnv.CreateGlobalFunctionBinding(fn, fo,
- Else,
- Let bindingExists be ! varEnv.HasBinding(fn).
- If bindingExists is
false , then- NOTE: The following invocation cannot return an
abrupt completion because of the validation preceding step14 . - Perform ! varEnv.CreateMutableBinding(fn,
true ). - Perform ! varEnv.InitializeBinding(fn, fo).
- NOTE: The following invocation cannot return an
- Else,
- Perform ! varEnv.SetMutableBinding(fn, fo,
false ).
- Perform ! varEnv.SetMutableBinding(fn, fo,
- Let fn be the sole element of the
- For each String vn of declaredVarNames, do
- If varEnv is a
Global Environment Record , then- Perform ? varEnv.CreateGlobalVarBinding(vn,
true ).
- Perform ? varEnv.CreateGlobalVarBinding(vn,
- Else,
- Let bindingExists be ! varEnv.HasBinding(vn).
- If bindingExists is
false , then- NOTE: The following invocation cannot return an
abrupt completion because of the validation preceding step14 . - Perform ! varEnv.CreateMutableBinding(vn,
true ). - Perform ! varEnv.InitializeBinding(vn,
undefined ).
- NOTE: The following invocation cannot return an
- If varEnv is a
- Return
unused .
An alternative version of this algorithm is described in
19.2.2 isFinite ( number )
This function is the %isFinite% intrinsic object.
It performs the following steps when called:
19.2.3 isNaN ( number )
This function is the %isNaN% intrinsic object.
It performs the following steps when called:
- Let num be ?
ToNumber (number). - If num is
NaN , returntrue . - Otherwise, return
false .
A reliable way for ECMAScript code to test if a value X
is X !== X
. The result will be X
is
19.2.4 parseFloat ( string )
This function produces a Number value dictated by interpretation of the contents of the string argument as a decimal literal.
It is the %parseFloat% intrinsic object.
It performs the following steps when called:
- Let inputString be ?
ToString (string). - Let trimmedString be !
TrimString (inputString,start ). - Let trimmed be
StringToCodePoints (trimmedString). - Let trimmedPrefix be the longest prefix of trimmed that satisfies the syntax of a
StrDecimalLiteral , which might be trimmed itself. If there is no such prefix, returnNaN . - Let parsedNumber be
ParseText (trimmedPrefix,StrDecimalLiteral ). Assert : parsedNumber is aParse Node .- Return
StringNumericValue of parsedNumber.
This function may interpret only a leading portion of string as a Number value; it ignores any code units that cannot be interpreted as part of the notation of a decimal literal, and no indication is given that any such code units were ignored.
19.2.5 parseInt ( string, radix )
This function produces an
It is the %parseInt% intrinsic object.
It performs the following steps when called:
- Let inputString be ?
ToString (string). - Let S be !
TrimString (inputString,start ). - Let sign be 1.
- If S is not empty and the first code unit of S is the code unit 0x002D (HYPHEN-MINUS), set sign to -1.
- If S is not empty and the first code unit of S is either the code unit 0x002B (PLUS SIGN) or the code unit 0x002D (HYPHEN-MINUS), set S to the
substring of S from index 1. - Let R be
ℝ (?ToInt32 (radix)). - Let stripPrefix be
true . - If R ≠ 0, then
- If R < 2 or R > 36, return
NaN . - If R ≠ 16, set stripPrefix to
false .
- If R < 2 or R > 36, return
- Else,
- Set R to 10.
- If stripPrefix is
true , then- If the length of S is at least 2 and the first two code units of S are either
"0x" or"0X" , then- Set S to the
substring of S from index 2. - Set R to 16.
- Set S to the
- If the length of S is at least 2 and the first two code units of S are either
- If S contains a code unit that is not a radix-R digit, let end be the index within S of the first such code unit; otherwise, let end be the length of S.
- Let Z be the
substring of S from 0 to end. - If Z is empty, return
NaN . - Let mathInt be the
integer value that is represented by Z in radix-R notation, using the letters A through Z and a through z for digits with values 10 through 35. (However, if R = 10 and Z contains more than 20 significant digits, every significant digit after the 20th may be replaced by a 0 digit, at the option of the implementation; and if R is not one of 2, 4, 8, 10, 16, or 32, then mathInt may be animplementation-approximated integer representing theinteger value denoted by Z in radix-R notation.) - If mathInt = 0, then
- If sign = -1, return
-0 𝔽. - Return
+0 𝔽.
- If sign = -1, return
- Return
𝔽 (sign × mathInt).
19.2.6 URI Handling Functions
Uniform Resource Identifiers, or URIs, are Strings that identify resources (e.g. web pages or files) and transport protocols by which to access them (e.g. HTTP or FTP) on the Internet. The ECMAScript language itself does not provide any support for using URIs except for functions that encode and decode URIs as described in this section. encodeURI
and decodeURI
are intended to work with complete URIs; they assume that any reserved characters are intended to have special meaning (e.g., as delimiters) and so are not encoded. encodeURIComponent
and decodeURIComponent
are intended to work with the individual components of a URI; they assume that any reserved characters represent text and must be encoded to avoid special meaning when the component is part of a complete URI.
The set of reserved characters is based upon RFC 2396 and does not reflect changes introduced by the more recent RFC 3986.
Many implementations of ECMAScript provide additional functions and methods that manipulate web pages; these functions are beyond the scope of this standard.
19.2.6.1 decodeURI ( encodedURI )
This function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by the encodeURI
function is replaced with the UTF-16 encoding of the code point that it represents. Escape sequences that could not have been introduced by encodeURI
are not replaced.
It is the %decodeURI% intrinsic object.
It performs the following steps when called:
19.2.6.2 decodeURIComponent ( encodedURIComponent )
This function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by the encodeURIComponent
function is replaced with the UTF-16 encoding of the code point that it represents.
It is the %decodeURIComponent% intrinsic object.
It performs the following steps when called:
19.2.6.3 encodeURI ( uri )
This function computes a new version of a UTF-16 encoded (
It is the %encodeURI% intrinsic object.
It performs the following steps when called:
19.2.6.4 encodeURIComponent ( uriComponent )
This function computes a new version of a UTF-16 encoded (
It is the %encodeURIComponent% intrinsic object.
It performs the following steps when called:
19.2.6.5 Encode ( string, extraUnescaped )
The abstract operation Encode takes arguments string (a String) and extraUnescaped (a String) and returns either a
- Let len be the length of string.
- Let R be the empty String.
- Let alwaysUnescaped be the
string-concatenation ofthe ASCII word characters and"-.!~*'()" . - Let unescapedSet be the
string-concatenation of alwaysUnescaped and extraUnescaped. - Let k be 0.
- Repeat, while k < len,
- Let C be the code unit at index k within string.
- If unescapedSet contains C, then
- Set k to k + 1.
- Set R to the
string-concatenation of R and C.
- Else,
- Let cp be
CodePointAt (string, k). - If cp.[[IsUnpairedSurrogate]] is
true , throw aURIError exception. - Set k to k + cp.[[CodeUnitCount]].
- Let Octets be the
List of octets resulting by applying the UTF-8 transformation to cp.[[CodePoint]]. - For each element octet of Octets, do
- Let hex be the String representation of octet, formatted as an uppercase hexadecimal number.
- Set R to the
string-concatenation of R,"%" , andStringPad (hex, 2,"0" ,start ).
- Let cp be
- Return R.
Because percent-encoding is used to represent individual octets, a single code point may be expressed as multiple consecutive escape sequences (one for each of its 8-bit UTF-8 code units).
19.2.6.6 Decode ( string, preserveEscapeSet )
The abstract operation Decode takes arguments string (a String) and preserveEscapeSet (a String) and returns either a
- Let len be the length of string.
- Let R be the empty String.
- Let k be 0.
- Repeat, while k < len,
- Let C be the code unit at index k within string.
- Let S be C.
- If C is the code unit 0x0025 (PERCENT SIGN), then
- If k + 3 > len, throw a
URIError exception. - Let escape be the
substring of string from k to k + 3. - Let B be
ParseHexOctet (string, k + 1). - If B is not an
integer , throw aURIError exception. - Set k to k + 2.
- Let n be the number of leading 1 bits in B.
- If n = 0, then
- Let asciiChar be the code unit whose numeric value is B.
- If preserveEscapeSet contains asciiChar, set S to escape. Otherwise, set S to asciiChar.
- Else,
- If n = 1 or n > 4, throw a
URIError exception. - Let Octets be « B ».
- Let j be 1.
- Repeat, while j < n,
- Set k to k + 1.
- If k + 3 > len, throw a
URIError exception. - If the code unit at index k within string is not the code unit 0x0025 (PERCENT SIGN), throw a
URIError exception. - Let continuationByte be
ParseHexOctet (string, k + 1). - If continuationByte is not an
integer , throw aURIError exception. - Append continuationByte to Octets.
- Set k to k + 2.
- Set j to j + 1.
Assert : The length of Octets is n.- If Octets does not contain a valid UTF-8 encoding of a Unicode code point, throw a
URIError exception. - Let V be the code point obtained by applying the UTF-8 transformation to Octets, that is, from a
List of octets into a 21-bit value. - Set S to
UTF16EncodeCodePoint (V).
- If n = 1 or n > 4, throw a
- If k + 3 > len, throw a
- Set R to the
string-concatenation of R and S. - Set k to k + 1.
- Return R.
RFC 3629 prohibits the decoding of invalid UTF-8 octet sequences. For example, the invalid sequence 0xC0 0x80 must not decode into the code unit 0x0000. Implementations of the Decode algorithm are required to throw a
19.2.6.7 ParseHexOctet ( string, position )
The abstract operation ParseHexOctet takes arguments string (a String) and position (a non-negative
- Let len be the length of string.
Assert : position + 2 ≤ len.- Let hexDigits be the
substring of string from position to position + 2. - Let parseResult be
ParseText (StringToCodePoints (hexDigits),HexDigits ).[~Sep] - If parseResult is not a
Parse Node , return parseResult. - Let n be the MV of parseResult.
Assert : n is in theinclusive interval from 0 to 255.- Return n.