You are on page 1of 586

ECMA-262

7th Edition / June 2016

ECMAScript 2016
Language Specification

Reference number
ECMA-123:2009

Ecma International 2009


Ecma International
Rue du Rhone 114
CH-1204 Geneva
Tel: +41 22 849 6000
Fax: +41 22 849 6001
Web: http://www.ecma-international.org

COPYRIGHT PROTECTED DOCUMENT

Ecma International 2016


COPYRIGHT NOTICE
2016 Ecma International
This document may be copied, published and distributed to others, and certain derivative works of it
may be prepared, copied, published, and distributed, in whole or in part, provided that the above
copyright notice and this Copyright License and Disclaimer are included on al l such copies and
derivative works. The only derivative works that are permissible under this Copyright License and
Disclaimer are:
(i) works which incorporate all or portion of this document for the purpose of providing commentary or
explanation (such as an annotated version of the document),
(ii) works which incorporate all or portion of this document for the purpose of incorporating features
that provide accessibility,
(iii) translations of this document into languages other than English and into differ ent formats and
(iv) works by making use of this specification in standard conformant products by implementing (e.g.
by copy and paste wholly or partly) the functionality therein.
However, the content of this document itself may not be modified in any way, including by removing the
copyright notice or references to Ecma International, except as required to translate it into languages
other than English or into a different format.
The official version of an Ecma International document is the English language version on the Ecma
International website. In the event of discrepancies between a translated version and the official
version, the official version shall govern.
The limited permissions granted above are perpetual and will not be revoked by Ecma Internat ional or
its successors or assigns.
This document and the information contained herein is provided on an "AS IS" basis and ECMA
INTERNATIONAL DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE
ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
A PARTICULAR PURPOSE."

Software License
All Software contained in this document ("Software)" is protected by copyright and is being made available under the "BSD
License", included below. This Software may be subject to third party rights (rights from parties other than Ecma
International), including patent rights, and no licenses under such third party rights are granted under this license even if
the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT
MATTERS AVAILABLE AT http://www.ecma-international.org/memento/codeofconduct.htm FOR INFORMATION
REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL
STANDARDS*.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Ecma International 2016 i


ii Ecma International 2016
ECMA262
7Edition

ECMAScript2016LanguageSpeciication

TableofContents
Introduction
1Scope
2Conformance
3NormativeReferences
4Overview
4.1WebScripting
4.2ECMAScriptOverview
4.2.1Objects
4.2.2TheStrictVariantofECMAScript
4.3TermsandDeinitions
4.3.1type
4.3.2primitivevalue
4.3.3object
4.3.4constructor
4.3.5prototype
4.3.6ordinaryobject
4.3.7exoticobject
4.3.8standardobject
4.3.9builtinobject
4.3.10undeinedvalue
4.3.11Undeinedtype
4.3.12nullvalue
4.3.13Nulltype
4.3.14Booleanvalue
4.3.15Booleantype
4.3.16Booleanobject
4.3.17Stringvalue
4.3.18Stringtype
4.3.19Stringobject
4.3.20Numbervalue
4.3.21Numbertype
4.3.22Numberobject
4.3.23Ininity
4.3.24NaN
4.3.25Symbolvalue
4.3.26Symboltype
4.3.27Symbolobject
4.3.28function
4.3.29builtinfunction
4.3.30property
4.3.31method
4.3.32builtinmethod
4.3.33attribute
4.3.34ownproperty
4.3.35inheritedproperty
4.4OrganizationofThisSpeciication
5NotationalConventions
5.1SyntacticandLexicalGrammars
5.1.1ContextFreeGrammars
5.1.2TheLexicalandRegExpGrammars
5.1.3TheNumericStringGrammar
5.1.4TheSyntacticGrammar
5.1.5GrammarNotation
5.2AlgorithmConventions
5.3StaticSemanticRules
6ECMAScriptDataTypesandValues
6.1ECMAScriptLanguageTypes
6.1.1TheUndeinedType
6.1.2TheNullType
6.1.3TheBooleanType
6.1.4TheStringType
6.1.5TheSymbolType
6.1.5.1WellKnownSymbols
6.1.6TheNumberType
6.1.7TheObjectType
6.1.7.1PropertyAttributes
6.1.7.2ObjectInternalMethodsandInternalSlots
6.1.7.3InvariantsoftheEssentialInternalMethods
6.1.7.4WellKnownIntrinsicObjects
6.2ECMAScriptSpeciicationTypes
6.2.1TheListandRecordSpeciicationTypes
6.2.2TheCompletionRecordSpeciicationType
6.2.2.1NormalCompletion
6.2.2.2ImplicitCompletionValues
6.2.2.3ThrowanException
6.2.2.4ReturnIfAbrupt
6.2.2.5UpdateEmpty(completionRecord,value)
6.2.3TheReferenceSpeciicationType
6.2.3.1GetValue(V)
6.2.3.2PutValue(V,W)
6.2.3.3GetThisValue(V)
6.2.3.4InitializeReferencedBinding(V,W)
6.2.4ThePropertyDescriptorSpeciicationType
6.2.4.1IsAccessorDescriptor(Desc)
6.2.4.2IsDataDescriptor(Desc)
6.2.4.3IsGenericDescriptor(Desc)
6.2.4.4FromPropertyDescriptor(Desc)
6.2.4.5ToPropertyDescriptor(Obj)
6.2.4.6CompletePropertyDescriptor(Desc)
6.2.5TheLexicalEnvironmentandEnvironmentRecordSpeciicationTypes
6.2.6DataBlocks
6.2.6.1CreateByteDataBlock(size)
6.2.6.2CopyDataBlockBytes(toBlock,toIndex,fromBlock,fromIndex,count)
7AbstractOperations
7.1TypeConversion
7.1.1ToPrimitive(input[,PreferredType])
7.1.2ToBoolean(argument)
7.1.3ToNumber(argument)
7.1.3.1ToNumberAppliedtotheStringType
7.1.3.1.1RS:MV's
7.1.4ToInteger(argument)
7.1.5ToInt32(argument)
7.1.6ToUint32(argument)
7.1.7ToInt16(argument)
7.1.8ToUint16(argument)
7.1.9ToInt8(argument)
7.1.10ToUint8(argument)
7.1.11ToUint8Clamp(argument)
7.1.12ToString(argument)
7.1.12.1ToStringAppliedtotheNumberType
7.1.13ToObject(argument)
7.1.14ToPropertyKey(argument)
7.1.15ToLength(argument)
7.1.16CanonicalNumericIndexString(argument)
7.2TestingandComparisonOperations
7.2.1RequireObjectCoercible(argument)
7.2.2IsArray(argument)
7.2.3IsCallable(argument)
7.2.4IsConstructor(argument)
7.2.5IsExtensible(O)
7.2.6IsInteger(argument)
7.2.7IsPropertyKey(argument)
7.2.8IsRegExp(argument)
7.2.9SameValue(x,y)
7.2.10SameValueZero(x,y)
7.2.11SameValueNonNumber(x,y)
7.2.12AbstractRelationalComparison
7.2.13AbstractEqualityComparison
7.2.14StrictEqualityComparison
7.3OperationsonObjects
7.3.1Get(O,P)
7.3.2GetV(V,P)
7.3.3Set(O,P,V,Throw)
7.3.4CreateDataProperty(O,P,V)
7.3.5CreateMethodProperty(O,P,V)
7.3.6CreateDataPropertyOrThrow(O,P,V)
7.3.7DeinePropertyOrThrow(O,P,desc)
7.3.8DeletePropertyOrThrow(O,P)
7.3.9GetMethod(V,P)
7.3.10HasProperty(O,P)
7.3.11HasOwnProperty(O,P)
7.3.12Call(F,V[,argumentsList])
7.3.13Construct(F[,argumentsList[,newTarget]])
7.3.14SetIntegrityLevel(O,level)
7.3.15TestIntegrityLevel(O,level)
7.3.16CreateArrayFromList(elements)
7.3.17CreateListFromArrayLike(obj[,elementTypes])
7.3.18Invoke(V,P[,argumentsList])
7.3.19OrdinaryHasInstance(C,O)
7.3.20SpeciesConstructor(O,defaultConstructor)
7.3.21EnumerableOwnNames(O)
7.3.22GetFunctionRealm(obj)
7.4OperationsonIteratorObjects
7.4.1GetIterator(obj[,method])
7.4.2IteratorNext(iterator[,value])
7.4.3IteratorComplete(iterResult)
7.4.4IteratorValue(iterResult)
7.4.5IteratorStep(iterator)
7.4.6IteratorClose(iterator,completion)
7.4.7CreateIterResultObject(value,done)
7.4.8CreateListIterator(list)
7.4.8.1ListIteratornext()
8ExecutableCodeandExecutionContexts
8.1LexicalEnvironments
8.1.1EnvironmentRecords
8.1.1.1DeclarativeEnvironmentRecords
8.1.1.1.1HasBinding(N)
8.1.1.1.2CreateMutableBinding(N,D)
8.1.1.1.3CreateImmutableBinding(N,S)
8.1.1.1.4InitializeBinding(N,V)
8.1.1.1.5SetMutableBinding(N,V,S)
8.1.1.1.6GetBindingValue(N,S)
8.1.1.1.7DeleteBinding(N)
8.1.1.1.8HasThisBinding()
8.1.1.1.9HasSuperBinding()
8.1.1.1.10WithBaseObject()
8.1.1.2ObjectEnvironmentRecords
8.1.1.2.1HasBinding(N)
8.1.1.2.2CreateMutableBinding(N,D)
8.1.1.2.3CreateImmutableBinding(N,S)
8.1.1.2.4InitializeBinding(N,V)
8.1.1.2.5SetMutableBinding(N,V,S)
8.1.1.2.6GetBindingValue(N,S)
8.1.1.2.7DeleteBinding(N)
8.1.1.2.8HasThisBinding()
8.1.1.2.9HasSuperBinding()
8.1.1.2.10WithBaseObject()
8.1.1.3FunctionEnvironmentRecords
8.1.1.3.1BindThisValue(V)
8.1.1.3.2HasThisBinding()
8.1.1.3.3HasSuperBinding()
8.1.1.3.4GetThisBinding()
8.1.1.3.5GetSuperBase()
8.1.1.4GlobalEnvironmentRecords
8.1.1.4.1HasBinding(N)
8.1.1.4.2CreateMutableBinding(N,D)
8.1.1.4.3CreateImmutableBinding(N,S)
8.1.1.4.4InitializeBinding(N,V)
8.1.1.4.5SetMutableBinding(N,V,S)
8.1.1.4.6GetBindingValue(N,S)
8.1.1.4.7DeleteBinding(N)
8.1.1.4.8HasThisBinding()
8.1.1.4.9HasSuperBinding()
8.1.1.4.10WithBaseObject()
8.1.1.4.11GetThisBinding()
8.1.1.4.12HasVarDeclaration(N)
8.1.1.4.13HasLexicalDeclaration(N)
8.1.1.4.14HasRestrictedGlobalProperty(N)
8.1.1.4.15CanDeclareGlobalVar(N)
8.1.1.4.16CanDeclareGlobalFunction(N)
8.1.1.4.17CreateGlobalVarBinding(N,D)
8.1.1.4.18CreateGlobalFunctionBinding(N,V,D)
8.1.1.5ModuleEnvironmentRecords
8.1.1.5.1GetBindingValue(N,S)
8.1.1.5.2DeleteBinding(N)
8.1.1.5.3HasThisBinding()
8.1.1.5.4GetThisBinding()
8.1.1.5.5CreateImportBinding(N,M,N2)
8.1.2LexicalEnvironmentOperations
8.1.2.1GetIdentiierReference(lex,name,strict)
8.1.2.2NewDeclarativeEnvironment(E)
8.1.2.3NewObjectEnvironment(O,E)
8.1.2.4NewFunctionEnvironment(F,newTarget)
8.1.2.5NewGlobalEnvironment(G,thisValue)
8.1.2.6NewModuleEnvironment(E)
8.2Realms
8.2.1CreateRealm()
8.2.2CreateIntrinsics(realmRec)
8.2.3SetRealmGlobalObject(realmRec,globalObj,thisValue)
8.2.4SetDefaultGlobalBindings(realmRec)
8.3ExecutionContexts
8.3.1GetActiveScriptOrModule()
8.3.2ResolveBinding(name[,env])
8.3.3GetThisEnvironment()
8.3.4ResolveThisBinding()
8.3.5GetNewTarget()
8.3.6GetGlobalObject()
8.4JobsandJobQueues
8.4.1EnqueueJob(queueName,job,arguments)
8.4.2NextJob
8.5InitializeHostDeinedRealm()
9OrdinaryandExoticObjectsBehaviours
9.1OrdinaryObjectInternalMethodsandInternalSlots
9.1.1[[GetPrototypeOf]]()
9.1.1.1OrdinaryGetPrototypeOf(O)
9.1.2[[SetPrototypeOf]](V)
9.1.2.1OrdinarySetPrototypeOf(O,V)
9.1.3[[IsExtensible]]()
9.1.3.1OrdinaryIsExtensible(O)
9.1.4[[PreventExtensions]]()
9.1.4.1OrdinaryPreventExtensions(O)
9.1.5[[GetOwnProperty]](P)
9.1.5.1OrdinaryGetOwnProperty(O,P)
9.1.6[[DeineOwnProperty]](P,Desc)
9.1.6.1OrdinaryDeineOwnProperty(O,P,Desc)
9.1.6.2IsCompatiblePropertyDescriptor(Extensible,Desc,Current)
9.1.6.3ValidateAndApplyPropertyDescriptor(O,P,extensible,Desc,current)
9.1.7[[HasProperty]](P)
9.1.7.1OrdinaryHasProperty(O,P)
9.1.8[[Get]](P,Receiver)
9.1.8.1OrdinaryGet(O,P,Receiver)
9.1.9[[Set]](P,V,Receiver)
9.1.9.1OrdinarySet(O,P,V,Receiver)
9.1.10[[Delete]](P)
9.1.10.1OrdinaryDelete(O,P)
9.1.11[[OwnPropertyKeys]]()
9.1.11.1OrdinaryOwnPropertyKeys(O)
9.1.12ObjectCreate(proto[,internalSlotsList])
9.1.13OrdinaryCreateFromConstructor(constructor,intrinsicDefaultProto[,internalSlotsList])
9.1.14GetPrototypeFromConstructor(constructor,intrinsicDefaultProto)
9.2ECMAScriptFunctionObjects
9.2.1[[Call]](thisArgument,argumentsList)
9.2.1.1PrepareForOrdinaryCall(F,newTarget)
9.2.1.2OrdinaryCallBindThis(F,calleeContext,thisArgument)
9.2.1.3OrdinaryCallEvaluateBody(F,argumentsList)
9.2.2[[Construct]](argumentsList,newTarget)
9.2.3FunctionAllocate(functionPrototype,strict,functionKind)
9.2.4FunctionInitialize(F,kind,ParameterList,Body,Scope)
9.2.5FunctionCreate(kind,ParameterList,Body,Scope,Strict[,prototype])
9.2.6GeneratorFunctionCreate(kind,ParameterList,Body,Scope,Strict)
9.2.7AddRestrictedFunctionProperties(F,realm)
9.2.7.1%ThrowTypeError%()
9.2.8MakeConstructor(F[,writablePrototype,prototype])
9.2.9MakeClassConstructor(F)
9.2.10MakeMethod(F,homeObject)
9.2.11SetFunctionName(F,name[,preix])
9.2.12FunctionDeclarationInstantiation(func,argumentsList)
9.3BuiltinFunctionObjects
9.3.1[[Call]](thisArgument,argumentsList)
9.3.2[[Construct]](argumentsList,newTarget)
9.3.3CreateBuiltinFunction(realm,steps,prototype[,internalSlotsList])
9.4BuiltinExoticObjectInternalMethodsandSlots
9.4.1BoundFunctionExoticObjects
9.4.1.1[[Call]](thisArgument,argumentsList)
9.4.1.2[[Construct]](argumentsList,newTarget)
9.4.1.3BoundFunctionCreate(targetFunction,boundThis,boundArgs)
9.4.2ArrayExoticObjects
9.4.2.1[[DeineOwnProperty]](P,Desc)
9.4.2.2ArrayCreate(length[,proto])
9.4.2.3ArraySpeciesCreate(originalArray,length)
9.4.2.4ArraySetLength(A,Desc)
9.4.3StringExoticObjects
9.4.3.1[[GetOwnProperty]](P)
9.4.3.2[[OwnPropertyKeys]]()
9.4.3.3StringCreate(value,prototype)
9.4.4ArgumentsExoticObjects
9.4.4.1[[GetOwnProperty]](P)
9.4.4.2[[DeineOwnProperty]](P,Desc)
9.4.4.3[[Get]](P,Receiver)
9.4.4.4[[Set]](P,V,Receiver)
9.4.4.5[[HasProperty]](P)
9.4.4.6[[Delete]](P)
9.4.4.7CreateUnmappedArgumentsObject(argumentsList)
9.4.4.8CreateMappedArgumentsObject(func,formals,argumentsList,env)
9.4.4.8.1MakeArgGetter(name,env)
9.4.4.8.2MakeArgSetter(name,env)
9.4.5IntegerIndexedExoticObjects
9.4.5.1[[GetOwnProperty]](P)
9.4.5.2[[HasProperty]](P)
9.4.5.3[[DeineOwnProperty]](P,Desc)
9.4.5.4[[Get]](P,Receiver)
9.4.5.5[[Set]](P,V,Receiver)
9.4.5.6[[OwnPropertyKeys]]()
9.4.5.7IntegerIndexedObjectCreate(prototype,internalSlotsList)
9.4.5.8IntegerIndexedElementGet(O,index)
9.4.5.9IntegerIndexedElementSet(O,index,value)
9.4.6ModuleNamespaceExoticObjects
9.4.6.1[[GetPrototypeOf]]()
9.4.6.2[[SetPrototypeOf]](V)
9.4.6.3[[IsExtensible]]()
9.4.6.4[[PreventExtensions]]()
9.4.6.5[[GetOwnProperty]](P)
9.4.6.6[[DeineOwnProperty]](P,Desc)
9.4.6.7[[HasProperty]](P)
9.4.6.8[[Get]](P,Receiver)
9.4.6.9[[Set]](P,V,Receiver)
9.4.6.10[[Delete]](P)
9.4.6.11[[OwnPropertyKeys]]()
9.4.6.12ModuleNamespaceCreate(module,exports)
9.4.7ImmutablePrototypeExoticObjects
9.4.7.1[[SetPrototypeOf]](V)
9.5ProxyObjectInternalMethodsandInternalSlots
9.5.1[[GetPrototypeOf]]()
9.5.2[[SetPrototypeOf]](V)
9.5.3[[IsExtensible]]()
9.5.4[[PreventExtensions]]()
9.5.5[[GetOwnProperty]](P)
9.5.6[[DeineOwnProperty]](P,Desc)
9.5.7[[HasProperty]](P)
9.5.8[[Get]](P,Receiver)
9.5.9[[Set]](P,V,Receiver)
9.5.10[[Delete]](P)
9.5.11[[OwnPropertyKeys]]()
9.5.12[[Call]](thisArgument,argumentsList)
9.5.13[[Construct]](argumentsList,newTarget)
9.5.14ProxyCreate(target,handler)
10ECMAScriptLanguage:SourceCode
10.1SourceText
10.1.1SS:UTF16Encoding(cp)
10.1.2SS:UTF16Decode(lead,trail)
10.2TypesofSourceCode
10.2.1StrictModeCode
10.2.2NonECMAScriptFunctions
11ECMAScriptLanguage:LexicalGrammar
11.1UnicodeFormatControlCharacters
11.2WhiteSpace
11.3LineTerminators
11.4Comments
11.5Tokens
11.6NamesandKeywords
11.6.1IdentiierNames
11.6.1.1SS:EarlyErrors
11.6.1.2SS:StringValue
11.6.2ReservedWords
11.6.2.1Keywords
11.6.2.2FutureReservedWords
11.7Punctuators
11.8Literals
11.8.1NullLiterals
11.8.2BooleanLiterals
11.8.3NumericLiterals
11.8.3.1SS:MV
11.8.4StringLiterals
11.8.4.1SS:EarlyErrors
11.8.4.2SS:StringValue
11.8.4.3SS:SV
11.8.5RegularExpressionLiterals
11.8.5.1SS:EarlyErrors
11.8.5.2SS:BodyText
11.8.5.3SS:FlagText
11.8.6TemplateLiteralLexicalComponents
11.8.6.1SS:TVandTRV
11.9AutomaticSemicolonInsertion
11.9.1RulesofAutomaticSemicolonInsertion
11.9.2ExamplesofAutomaticSemicolonInsertion
12ECMAScriptLanguage:Expressions
12.1Identiiers
12.1.1SS:EarlyErrors
12.1.2SS:BoundNames
12.1.3SS:IsValidSimpleAssignmentTarget
12.1.4SS:StringValue
12.1.5RS:BindingInitialization
12.1.5.1RS:InitializeBoundName(name,value,environment)
12.1.6RS:Evaluation
12.2PrimaryExpression
12.2.1Semantics
12.2.1.1SS:CoveredParenthesizedExpression
12.2.1.2SS:HasName
12.2.1.3SS:IsFunctionDeinition
12.2.1.4SS:IsIdentiierRef
12.2.1.5SS:IsValidSimpleAssignmentTarget
12.2.2ThethisKeyword
12.2.2.1RS:Evaluation
12.2.3IdentiierReference
12.2.4Literals
12.2.4.1RS:Evaluation
12.2.5ArrayInitializer
12.2.5.1SS:ElisionWidth
12.2.5.2RS:ArrayAccumulation
12.2.5.3RS:Evaluation
12.2.6ObjectInitializer
12.2.6.1SS:EarlyErrors
12.2.6.2SS:ComputedPropertyContains
12.2.6.3SS:Contains
12.2.6.4SS:HasComputedPropertyKey
12.2.6.5SS:IsComputedPropertyKey
12.2.6.6SS:PropName
12.2.6.7SS:PropertyNameList
12.2.6.8RS:Evaluation
12.2.6.9RS:PropertyDeinitionEvaluation
12.2.7FunctionDeiningExpressions
12.2.8RegularExpressionLiterals
12.2.8.1SS:EarlyErrors
12.2.8.2RS:Evaluation
12.2.9TemplateLiterals
12.2.9.1SS:TemplateStrings
12.2.9.2RS:ArgumentListEvaluation
12.2.9.3RS:GetTemplateObject(templateLiteral)
12.2.9.4RS:SubstitutionEvaluation
12.2.9.5RS:Evaluation
12.2.10TheGroupingOperator
12.2.10.1SS:EarlyErrors
12.2.10.2SS:IsFunctionDeinition
12.2.10.3SS:IsValidSimpleAssignmentTarget
12.2.10.4RS:Evaluation
12.3LeftHandSideExpressions
12.3.1StaticSemantics
12.3.1.1SS:Contains
12.3.1.2SS:IsFunctionDeinition
12.3.1.3SS:IsDestructuring
12.3.1.4SS:IsIdentiierRef
12.3.1.5SS:IsValidSimpleAssignmentTarget
12.3.2PropertyAccessors
12.3.2.1RS:Evaluation
12.3.3ThenewOperator
12.3.3.1RS:Evaluation
12.3.3.1.1RS:EvaluateNew(constructProduction,arguments)
12.3.4FunctionCalls
12.3.4.1RS:Evaluation
12.3.4.2RS:EvaluateCall(ref,arguments,tailPosition)
12.3.4.3RS:EvaluateDirectCall(func,thisValue,arguments,tailPosition)
12.3.5ThesuperKeyword
12.3.5.1RS:Evaluation
12.3.5.2RS:GetSuperConstructor()
12.3.5.3RS:MakeSuperPropertyReference(propertyKey,strict)
12.3.6ArgumentLists
12.3.6.1RS:ArgumentListEvaluation
12.3.7TaggedTemplates
12.3.7.1RS:Evaluation
12.3.8MetaProperties
12.3.8.1RS:Evaluation
12.4UpdateExpressions
12.4.1SS:EarlyErrors
12.4.2SS:IsFunctionDeinition
12.4.3SS:IsValidSimpleAssignmentTarget
12.4.4PostixIncrementOperator
12.4.4.1RS:Evaluation
12.4.5PostixDecrementOperator
12.4.5.1RS:Evaluation
12.4.6PreixIncrementOperator
12.4.6.1RS:Evaluation
12.4.7PreixDecrementOperator
12.4.7.1RS:Evaluation
12.5UnaryOperators
12.5.1SS:IsFunctionDeinition
12.5.2SS:IsValidSimpleAssignmentTarget
12.5.3ThedeleteOperator
12.5.3.1SS:EarlyErrors
12.5.3.2RS:Evaluation
12.5.4ThevoidOperator
12.5.4.1RS:Evaluation
12.5.5ThetypeofOperator
12.5.5.1RS:Evaluation
12.5.6Unary+Operator
12.5.6.1RS:Evaluation
12.5.7UnaryOperator
12.5.7.1RS:Evaluation
12.5.8BitwiseNOTOperator(~)
12.5.8.1RS:Evaluation
12.5.9LogicalNOTOperator(!)
12.5.9.1RS:Evaluation
12.6ExponentiationOperator
12.6.1SS:IsFunctionDeinition
12.6.2SS:IsValidSimpleAssignmentTarget
12.6.3RS:Evaluation
12.7MultiplicativeOperators
12.7.1SS:IsFunctionDeinition
12.7.2SS:IsValidSimpleAssignmentTarget
12.7.3RS:Evaluation
12.7.3.1Applyingthe*Operator
12.7.3.2Applyingthe/Operator
12.7.3.3Applyingthe%Operator
12.7.3.4Applyingthe**Operator
12.8AdditiveOperators
12.8.1SS:IsFunctionDeinition
12.8.2SS:IsValidSimpleAssignmentTarget
12.8.3TheAdditionOperator(+)
12.8.3.1RS:Evaluation
12.8.4TheSubtractionOperator()
12.8.4.1RS:Evaluation
12.8.5ApplyingtheAdditiveOperatorstoNumbers
12.9BitwiseShiftOperators
12.9.1SS:IsFunctionDeinition
12.9.2SS:IsValidSimpleAssignmentTarget
12.9.3TheLeftShiftOperator(<<)
12.9.3.1RS:Evaluation
12.9.4TheSignedRightShiftOperator(>>)
12.9.4.1RS:Evaluation
12.9.5TheUnsignedRightShiftOperator(>>>)
12.9.5.1RS:Evaluation
12.10RelationalOperators
12.10.1SS:IsFunctionDeinition
12.10.2SS:IsValidSimpleAssignmentTarget
12.10.3RS:Evaluation
12.10.4RS:InstanceofOperator(O,C)
12.11EqualityOperators
12.11.1SS:IsFunctionDeinition
12.11.2SS:IsValidSimpleAssignmentTarget
12.11.3RS:Evaluation
12.12BinaryBitwiseOperators
12.12.1SS:IsFunctionDeinition
12.12.2SS:IsValidSimpleAssignmentTarget
12.12.3RS:Evaluation
12.13BinaryLogicalOperators
12.13.1SS:IsFunctionDeinition
12.13.2SS:IsValidSimpleAssignmentTarget
12.13.3RS:Evaluation
12.14ConditionalOperator(?:)
12.14.1SS:IsFunctionDeinition
12.14.2SS:IsValidSimpleAssignmentTarget
12.14.3RS:Evaluation
12.15AssignmentOperators
12.15.1SS:EarlyErrors
12.15.2SS:IsFunctionDeinition
12.15.3SS:IsValidSimpleAssignmentTarget
12.15.4RS:Evaluation
12.15.5DestructuringAssignment
12.15.5.1SS:EarlyErrors
12.15.5.2RS:DestructuringAssignmentEvaluation
12.15.5.3RS:IteratorDestructuringAssignmentEvaluation
12.15.5.4RS:KeyedDestructuringAssignmentEvaluation
12.16CommaOperator(,)
12.16.1SS:IsFunctionDeinition
12.16.2SS:IsValidSimpleAssignmentTarget
12.16.3RS:Evaluation
13ECMAScriptLanguage:StatementsandDeclarations
13.1StatementSemantics
13.1.1SS:ContainsDuplicateLabels
13.1.2SS:ContainsUndeinedBreakTarget
13.1.3SS:ContainsUndeinedContinueTarget
13.1.4SS:DeclarationPart
13.1.5SS:VarDeclaredNames
13.1.6SS:VarScopedDeclarations
13.1.7RS:LabelledEvaluation
13.1.8RS:Evaluation
13.2Block
13.2.1SS:EarlyErrors
13.2.2SS:ContainsDuplicateLabels
13.2.3SS:ContainsUndeinedBreakTarget
13.2.4SS:ContainsUndeinedContinueTarget
13.2.5SS:LexicallyDeclaredNames
13.2.6SS:LexicallyScopedDeclarations
13.2.7SS:TopLevelLexicallyDeclaredNames
13.2.8SS:TopLevelLexicallyScopedDeclarations
13.2.9SS:TopLevelVarDeclaredNames
13.2.10SS:TopLevelVarScopedDeclarations
13.2.11SS:VarDeclaredNames
13.2.12SS:VarScopedDeclarations
13.2.13RS:Evaluation
13.2.14RS:BlockDeclarationInstantiation(code,env)
13.3DeclarationsandtheVariableStatement
13.3.1LetandConstDeclarations
13.3.1.1SS:EarlyErrors
13.3.1.2SS:BoundNames
13.3.1.3SS:IsConstantDeclaration
13.3.1.4RS:Evaluation
13.3.2VariableStatement
13.3.2.1SS:BoundNames
13.3.2.2SS:VarDeclaredNames
13.3.2.3SS:VarScopedDeclarations
13.3.2.4RS:Evaluation
13.3.3DestructuringBindingPatterns
13.3.3.1SS:BoundNames
13.3.3.2SS:ContainsExpression
13.3.3.3SS:HasInitializer
13.3.3.4SS:IsSimpleParameterList
13.3.3.5RS:BindingInitialization
13.3.3.6RS:IteratorBindingInitialization
13.3.3.7RS:KeyedBindingInitialization
13.4EmptyStatement
13.4.1RS:Evaluation
13.5ExpressionStatement
13.5.1RS:Evaluation
13.6TheifStatement
13.6.1SS:EarlyErrors
13.6.2SS:ContainsDuplicateLabels
13.6.3SS:ContainsUndeinedBreakTarget
13.6.4SS:ContainsUndeinedContinueTarget
13.6.5SS:VarDeclaredNames
13.6.6SS:VarScopedDeclarations
13.6.7RS:Evaluation
13.7IterationStatements
13.7.1Semantics
13.7.1.1SS:EarlyErrors
13.7.1.2RS:LoopContinues(completion,labelSet)
13.7.2ThedowhileStatement
13.7.2.1SS:ContainsDuplicateLabels
13.7.2.2SS:ContainsUndeinedBreakTarget
13.7.2.3SS:ContainsUndeinedContinueTarget
13.7.2.4SS:VarDeclaredNames
13.7.2.5SS:VarScopedDeclarations
13.7.2.6RS:LabelledEvaluation
13.7.3ThewhileStatement
13.7.3.1SS:ContainsDuplicateLabels
13.7.3.2SS:ContainsUndeinedBreakTarget
13.7.3.3SS:ContainsUndeinedContinueTarget
13.7.3.4SS:VarDeclaredNames
13.7.3.5SS:VarScopedDeclarations
13.7.3.6RS:LabelledEvaluation
13.7.4TheforStatement
13.7.4.1SS:EarlyErrors
13.7.4.2SS:ContainsDuplicateLabels
13.7.4.3SS:ContainsUndeinedBreakTarget
13.7.4.4SS:ContainsUndeinedContinueTarget
13.7.4.5SS:VarDeclaredNames
13.7.4.6SS:VarScopedDeclarations
13.7.4.7RS:LabelledEvaluation
13.7.4.8RS:ForBodyEvaluation(test,increment,stmt,perIterationBindings,labelSet)
13.7.4.9RS:CreatePerIterationEnvironment(perIterationBindings)
13.7.5TheforinandforofStatements
13.7.5.1SS:EarlyErrors
13.7.5.2SS:BoundNames
13.7.5.3SS:ContainsDuplicateLabels
13.7.5.4SS:ContainsUndeinedBreakTarget
13.7.5.5SS:ContainsUndeinedContinueTarget
13.7.5.6SS:IsDestructuring
13.7.5.7SS:VarDeclaredNames
13.7.5.8SS:VarScopedDeclarations
13.7.5.9RS:BindingInitialization
13.7.5.10RS:BindingInstantiation
13.7.5.11RS:LabelledEvaluation
13.7.5.12RS:ForIn/OfHeadEvaluation(TDZnames,expr,iterationKind)
13.7.5.13RS:ForIn/OfBodyEvaluation(lhs,stmt,iterator,lhsKind,labelSet)
13.7.5.14RS:Evaluation
13.7.5.15EnumerateObjectProperties(O)
13.8ThecontinueStatement
13.8.1SS:EarlyErrors
13.8.2SS:ContainsUndeinedContinueTarget
13.8.3RS:Evaluation
13.9ThebreakStatement
13.9.1SS:EarlyErrors
13.9.2SS:ContainsUndeinedBreakTarget
13.9.3RS:Evaluation
13.10ThereturnStatement
13.10.1RS:Evaluation
13.11ThewithStatement
13.11.1SS:EarlyErrors
13.11.2SS:ContainsDuplicateLabels
13.11.3SS:ContainsUndeinedBreakTarget
13.11.4SS:ContainsUndeinedContinueTarget
13.11.5SS:VarDeclaredNames
13.11.6SS:VarScopedDeclarations
13.11.7RS:Evaluation
13.12TheswitchStatement
13.12.1SS:EarlyErrors
13.12.2SS:ContainsDuplicateLabels
13.12.3SS:ContainsUndeinedBreakTarget
13.12.4SS:ContainsUndeinedContinueTarget
13.12.5SS:LexicallyDeclaredNames
13.12.6SS:LexicallyScopedDeclarations
13.12.7SS:VarDeclaredNames
13.12.8SS:VarScopedDeclarations
13.12.9RS:CaseBlockEvaluation
13.12.10RS:CaseSelectorEvaluation
13.12.11RS:Evaluation
13.13LabelledStatements
13.13.1SS:EarlyErrors
13.13.2SS:ContainsDuplicateLabels
13.13.3SS:ContainsUndeinedBreakTarget
13.13.4SS:ContainsUndeinedContinueTarget
13.13.5SS:IsLabelledFunction(stmt)
13.13.6SS:LexicallyDeclaredNames
13.13.7SS:LexicallyScopedDeclarations
13.13.8SS:TopLevelLexicallyDeclaredNames
13.13.9SS:TopLevelLexicallyScopedDeclarations
13.13.10SS:TopLevelVarDeclaredNames
13.13.11SS:TopLevelVarScopedDeclarations
13.13.12SS:VarDeclaredNames
13.13.13SS:VarScopedDeclarations
13.13.14RS:LabelledEvaluation
13.13.15RS:Evaluation
13.14ThethrowStatement
13.14.1RS:Evaluation
13.15ThetryStatement
13.15.1SS:EarlyErrors
13.15.2SS:ContainsDuplicateLabels
13.15.3SS:ContainsUndeinedBreakTarget
13.15.4SS:ContainsUndeinedContinueTarget
13.15.5SS:VarDeclaredNames
13.15.6SS:VarScopedDeclarations
13.15.7RS:CatchClauseEvaluation
13.15.8RS:Evaluation
13.16ThedebuggerStatement
13.16.1RS:Evaluation
14ECMAScriptLanguage:FunctionsandClasses
14.1FunctionDeinitions
14.1.1DirectiveProloguesandtheUseStrictDirective
14.1.2SS:EarlyErrors
14.1.3SS:BoundNames
14.1.4SS:Contains
14.1.5SS:ContainsExpression
14.1.6SS:ContainsUseStrict
14.1.7SS:ExpectedArgumentCount
14.1.8SS:HasInitializer
14.1.9SS:HasName
14.1.10SS:IsAnonymousFunctionDeinition(production)
14.1.11SS:IsConstantDeclaration
14.1.12SS:IsFunctionDeinition
14.1.13SS:IsSimpleParameterList
14.1.14SS:LexicallyDeclaredNames
14.1.15SS:LexicallyScopedDeclarations
14.1.16SS:VarDeclaredNames
14.1.17SS:VarScopedDeclarations
14.1.18RS:EvaluateBody
14.1.19RS:IteratorBindingInitialization
14.1.20RS:InstantiateFunctionObject
14.1.21RS:Evaluation
14.2ArrowFunctionDeinitions
14.2.1SS:EarlyErrors
14.2.2SS:BoundNames
14.2.3SS:Contains
14.2.4SS:ContainsExpression
14.2.5SS:ContainsUseStrict
14.2.6SS:ExpectedArgumentCount
14.2.7SS:HasName
14.2.8SS:IsSimpleParameterList
14.2.9SS:CoveredFormalsList
14.2.10SS:LexicallyDeclaredNames
14.2.11SS:LexicallyScopedDeclarations
14.2.12SS:VarDeclaredNames
14.2.13SS:VarScopedDeclarations
14.2.14RS:IteratorBindingInitialization
14.2.15RS:EvaluateBody
14.2.16RS:Evaluation
14.3MethodDeinitions
14.3.1SS:EarlyErrors
14.3.2SS:ComputedPropertyContains
14.3.3SS:ExpectedArgumentCount
14.3.4SS:HasComputedPropertyKey
14.3.5SS:HasDirectSuper
14.3.6SS:PropName
14.3.7SS:SpecialMethod
14.3.8RS:DeineMethod
14.3.9RS:PropertyDeinitionEvaluation
14.4GeneratorFunctionDeinitions
14.4.1SS:EarlyErrors
14.4.2SS:BoundNames
14.4.3SS:ComputedPropertyContains
14.4.4SS:Contains
14.4.5SS:HasComputedPropertyKey
14.4.6SS:HasDirectSuper
14.4.7SS:HasName
14.4.8SS:IsConstantDeclaration
14.4.9SS:IsFunctionDeinition
14.4.10SS:PropName
14.4.11RS:EvaluateBody
14.4.12RS:InstantiateFunctionObject
14.4.13RS:PropertyDeinitionEvaluation
14.4.14RS:Evaluation
14.5ClassDeinitions
14.5.1SS:EarlyErrors
14.5.2SS:BoundNames
14.5.3SS:ConstructorMethod
14.5.4SS:Contains
14.5.5SS:ComputedPropertyContains
14.5.6SS:HasName
14.5.7SS:IsConstantDeclaration
14.5.8SS:IsFunctionDeinition
14.5.9SS:IsStatic
14.5.10SS:NonConstructorMethodDeinitions
14.5.11SS:PrototypePropertyNameList
14.5.12SS:PropName
14.5.13SS:StaticPropertyNameList
14.5.14RS:ClassDeinitionEvaluation
14.5.15RS:BindingClassDeclarationEvaluation
14.5.16RS:Evaluation
14.6TailPositionCalls
14.6.1SS:IsInTailPosition(nonterminal)
14.6.2SS:HasProductionInTailPosition
14.6.2.1StatementRules
14.6.2.2ExpressionRules
14.6.3RS:PrepareForTailCall()
15ECMAScriptLanguage:ScriptsandModules
15.1Scripts
15.1.1SS:EarlyErrors
15.1.2SS:IsStrict
15.1.3SS:LexicallyDeclaredNames
15.1.4SS:LexicallyScopedDeclarations
15.1.5SS:VarDeclaredNames
15.1.6SS:VarScopedDeclarations
15.1.7RS:Evaluation
15.1.8ScriptRecords
15.1.9ParseScript(sourceText,realm,hostDeined)
15.1.10ScriptEvaluation(scriptRecord)
15.1.11RS:GlobalDeclarationInstantiation(script,env)
15.1.12RS:ScriptEvaluationJob(sourceText,hostDeined)
15.2Modules
15.2.1ModuleSemantics
15.2.1.1SS:EarlyErrors
15.2.1.2SS:ContainsDuplicateLabels
15.2.1.3SS:ContainsUndeinedBreakTarget
15.2.1.4SS:ContainsUndeinedContinueTarget
15.2.1.5SS:ExportedBindings
15.2.1.6SS:ExportedNames
15.2.1.7SS:ExportEntries
15.2.1.8SS:ImportEntries
15.2.1.9SS:ImportedLocalNames(importEntries)
15.2.1.10SS:ModuleRequests
15.2.1.11SS:LexicallyDeclaredNames
15.2.1.12SS:LexicallyScopedDeclarations
15.2.1.13SS:VarDeclaredNames
15.2.1.14SS:VarScopedDeclarations
15.2.1.15AbstractModuleRecords
15.2.1.16SourceTextModuleRecords
15.2.1.16.1ParseModule(sourceText,realm,hostDeined)
15.2.1.16.2GetExportedNames(exportStarSet)ConcreteMethod
15.2.1.16.3ResolveExport(exportName,resolveSet,exportStarSet)ConcreteMethod
15.2.1.16.4ModuleDeclarationInstantiation()ConcreteMethod
15.2.1.16.5ModuleEvaluation()ConcreteMethod
15.2.1.17RS:HostResolveImportedModule(referencingModule,speciier)
15.2.1.18RS:GetModuleNamespace(module)
15.2.1.19RS:TopLevelModuleEvaluationJob(sourceText,hostDeined)
15.2.1.20RS:Evaluation
15.2.2Imports
15.2.2.1SS:EarlyErrors
15.2.2.2SS:BoundNames
15.2.2.3SS:ImportEntries
15.2.2.4SS:ImportEntriesForModule
15.2.2.5SS:ModuleRequests
15.2.3Exports
15.2.3.1SS:EarlyErrors
15.2.3.2SS:BoundNames
15.2.3.3SS:ExportedBindings
15.2.3.4SS:ExportedNames
15.2.3.5SS:ExportEntries
15.2.3.6SS:ExportEntriesForModule
15.2.3.7SS:IsConstantDeclaration
15.2.3.8SS:LexicallyScopedDeclarations
15.2.3.9SS:ModuleRequests
15.2.3.10SS:ReferencedBindings
15.2.3.11RS:Evaluation
16ErrorHandlingandLanguageExtensions
16.1HostReportErrors(errorList)
16.2ForbiddenExtensions
17ECMAScriptStandardBuiltinObjects
18TheGlobalObject
18.1ValuePropertiesoftheGlobalObject
18.1.1Ininity
18.1.2NaN
18.1.3undeined
18.2FunctionPropertiesoftheGlobalObject
18.2.1eval(x)
18.2.1.1RS:PerformEval(x,evalRealm,strictCaller,direct)
18.2.1.2RS:EvalDeclarationInstantiation(body,varEnv,lexEnv,strict)
18.2.2isFinite(number)
18.2.3isNaN(number)
18.2.4parseFloat(string)
18.2.5parseInt(string,radix)
18.2.6URIHandlingFunctions
18.2.6.1URISyntaxandSemantics
18.2.6.1.1RS:Encode(string,unescapedSet)
18.2.6.1.2RS:Decode(string,reservedSet)
18.2.6.2decodeURI(encodedURI)
18.2.6.3decodeURIComponent(encodedURIComponent)
18.2.6.4encodeURI(uri)
18.2.6.5encodeURIComponent(uriComponent)
18.3ConstructorPropertiesoftheGlobalObject
18.3.1Array(...)
18.3.2ArrayBuffer(...)
18.3.3Boolean(...)
18.3.4DataView(...)
18.3.5Date(...)
18.3.6Error(...)
18.3.7EvalError(...)
18.3.8Float32Array(...)
18.3.9Float64Array(...)
18.3.10Function(...)
18.3.11Int8Array(...)
18.3.12Int16Array(...)
18.3.13Int32Array(...)
18.3.14Map(...)
18.3.15Number(...)
18.3.16Object(...)
18.3.17Proxy(...)
18.3.18Promise(...)
18.3.19RangeError(...)
18.3.20ReferenceError(...)
18.3.21RegExp(...)
18.3.22Set(...)
18.3.23String(...)
18.3.24Symbol(...)
18.3.25SyntaxError(...)
18.3.26TypeError(...)
18.3.27Uint8Array(...)
18.3.28Uint8ClampedArray(...)
18.3.29Uint16Array(...)
18.3.30Uint32Array(...)
18.3.31URIError(...)
18.3.32WeakMap(...)
18.3.33WeakSet(...)
18.4OtherPropertiesoftheGlobalObject
18.4.1JSON
18.4.2Math
18.4.3Relect
19FundamentalObjects
19.1ObjectObjects
19.1.1TheObjectConstructor
19.1.1.1Object([value])
19.1.2PropertiesoftheObjectConstructor
19.1.2.1Object.assign(target,...sources)
19.1.2.2Object.create(O,Properties)
19.1.2.3Object.deineProperties(O,Properties)
19.1.2.3.1RS:ObjectDeineProperties(O,Properties)
19.1.2.4Object.deineProperty(O,P,Attributes)
19.1.2.5Object.freeze(O)
19.1.2.6Object.getOwnPropertyDescriptor(O,P)
19.1.2.7Object.getOwnPropertyNames(O)
19.1.2.8Object.getOwnPropertySymbols(O)
19.1.2.8.1RS:GetOwnPropertyKeys(O,Type)
19.1.2.9Object.getPrototypeOf(O)
19.1.2.10Object.is(value1,value2)
19.1.2.11Object.isExtensible(O)
19.1.2.12Object.isFrozen(O)
19.1.2.13Object.isSealed(O)
19.1.2.14Object.keys(O)
19.1.2.15Object.preventExtensions(O)
19.1.2.16Object.prototype
19.1.2.17Object.seal(O)
19.1.2.18Object.setPrototypeOf(O,proto)
19.1.3PropertiesoftheObjectPrototypeObject
19.1.3.1Object.prototype.constructor
19.1.3.2Object.prototype.hasOwnProperty(V)
19.1.3.3Object.prototype.isPrototypeOf(V)
19.1.3.4Object.prototype.propertyIsEnumerable(V)
19.1.3.5Object.prototype.toLocaleString([reserved1[,reserved2]])
19.1.3.6Object.prototype.toString()
19.1.3.7Object.prototype.valueOf()
19.1.4PropertiesofObjectInstances
19.2FunctionObjects
19.2.1TheFunctionConstructor
19.2.1.1Function(p1,p2,,pn,body)
19.2.1.1.1RS:CreateDynamicFunction(constructor,newTarget,kind,args)
19.2.2PropertiesoftheFunctionConstructor
19.2.2.1Function.length
19.2.2.2Function.prototype
19.2.3PropertiesoftheFunctionPrototypeObject
19.2.3.1Function.prototype.apply(thisArg,argArray)
19.2.3.2Function.prototype.bind(thisArg,...args)
19.2.3.3Function.prototype.call(thisArg,...args)
19.2.3.4Function.prototype.constructor
19.2.3.5Function.prototype.toString()
19.2.3.6Function.prototype[@@hasInstance](V)
19.2.4FunctionInstances
19.2.4.1length
19.2.4.2name
19.2.4.3prototype
19.3BooleanObjects
19.3.1TheBooleanConstructor
19.3.1.1Boolean(value)
19.3.2PropertiesoftheBooleanConstructor
19.3.2.1Boolean.prototype
19.3.3PropertiesoftheBooleanPrototypeObject
19.3.3.1thisBooleanValue(value)
19.3.3.2Boolean.prototype.constructor
19.3.3.3Boolean.prototype.toString()
19.3.3.4Boolean.prototype.valueOf()
19.3.4PropertiesofBooleanInstances
19.4SymbolObjects
19.4.1TheSymbolConstructor
19.4.1.1Symbol([description])
19.4.2PropertiesoftheSymbolConstructor
19.4.2.1Symbol.for(key)
19.4.2.2Symbol.hasInstance
19.4.2.3Symbol.isConcatSpreadable
19.4.2.4Symbol.iterator
19.4.2.5Symbol.keyFor(sym)
19.4.2.6Symbol.match
19.4.2.7Symbol.prototype
19.4.2.8Symbol.replace
19.4.2.9Symbol.search
19.4.2.10Symbol.species
19.4.2.11Symbol.split
19.4.2.12Symbol.toPrimitive
19.4.2.13Symbol.toStringTag
19.4.2.14Symbol.unscopables
19.4.3PropertiesoftheSymbolPrototypeObject
19.4.3.1Symbol.prototype.constructor
19.4.3.2Symbol.prototype.toString()
19.4.3.2.1RS:SymbolDescriptiveString(sym)
19.4.3.3Symbol.prototype.valueOf()
19.4.3.4Symbol.prototype[@@toPrimitive](hint)
19.4.3.5Symbol.prototype[@@toStringTag]
19.4.4PropertiesofSymbolInstances
19.5ErrorObjects
19.5.1TheErrorConstructor
19.5.1.1Error(message)
19.5.2PropertiesoftheErrorConstructor
19.5.2.1Error.prototype
19.5.3PropertiesoftheErrorPrototypeObject
19.5.3.1Error.prototype.constructor
19.5.3.2Error.prototype.message
19.5.3.3Error.prototype.name
19.5.3.4Error.prototype.toString()
19.5.4PropertiesofErrorInstances
19.5.5NativeErrorTypesUsedinThisStandard
19.5.5.1EvalError
19.5.5.2RangeError
19.5.5.3ReferenceError
19.5.5.4SyntaxError
19.5.5.5TypeError
19.5.5.6URIError
19.5.6NativeErrorObjectStructure
19.5.6.1NativeErrorConstructors
19.5.6.1.1NativeError(message)
19.5.6.2PropertiesoftheNativeErrorConstructors
19.5.6.2.1NativeError.prototype
19.5.6.3PropertiesoftheNativeErrorPrototypeObjects
19.5.6.3.1NativeError.prototype.constructor
19.5.6.3.2NativeError.prototype.message
19.5.6.3.3NativeError.prototype.name
19.5.6.4PropertiesofNativeErrorInstances
20NumbersandDates
20.1NumberObjects
20.1.1TheNumberConstructor
20.1.1.1Number(value)
20.1.2PropertiesoftheNumberConstructor
20.1.2.1Number.EPSILON
20.1.2.2Number.isFinite(number)
20.1.2.3Number.isInteger(number)
20.1.2.4Number.isNaN(number)
20.1.2.5Number.isSafeInteger(number)
20.1.2.6Number.MAX_SAFE_INTEGER
20.1.2.7Number.MAX_VALUE
20.1.2.8Number.MIN_SAFE_INTEGER
20.1.2.9Number.MIN_VALUE
20.1.2.10Number.NaN
20.1.2.11Number.NEGATIVE_INFINITY
20.1.2.12Number.parseFloat(string)
20.1.2.13Number.parseInt(string,radix)
20.1.2.14Number.POSITIVE_INFINITY
20.1.2.15Number.prototype
20.1.3PropertiesoftheNumberPrototypeObject
20.1.3.1Number.prototype.constructor
20.1.3.2Number.prototype.toExponential(fractionDigits)
20.1.3.3Number.prototype.toFixed(fractionDigits)
20.1.3.4Number.prototype.toLocaleString([reserved1[,reserved2]])
20.1.3.5Number.prototype.toPrecision(precision)
20.1.3.6Number.prototype.toString([radix])
20.1.3.7Number.prototype.valueOf()
20.1.4PropertiesofNumberInstances
20.2TheMathObject
20.2.1ValuePropertiesoftheMathObject
20.2.1.1Math.E
20.2.1.2Math.LN10
20.2.1.3Math.LN2
20.2.1.4Math.LOG10E
20.2.1.5Math.LOG2E
20.2.1.6Math.PI
20.2.1.7Math.SQRT1_2
20.2.1.8Math.SQRT2
20.2.1.9Math[@@toStringTag]
20.2.2FunctionPropertiesoftheMathObject
20.2.2.1Math.abs(x)
20.2.2.2Math.acos(x)
20.2.2.3Math.acosh(x)
20.2.2.4Math.asin(x)
20.2.2.5Math.asinh(x)
20.2.2.6Math.atan(x)
20.2.2.7Math.atanh(x)
20.2.2.8Math.atan2(y,x)
20.2.2.9Math.cbrt(x)
20.2.2.10Math.ceil(x)
20.2.2.11Math.clz32(x)
20.2.2.12Math.cos(x)
20.2.2.13Math.cosh(x)
20.2.2.14Math.exp(x)
20.2.2.15Math.expm1(x)
20.2.2.16Math.loor(x)
20.2.2.17Math.fround(x)
20.2.2.18Math.hypot(value1,value2,...values)
20.2.2.19Math.imul(x,y)
20.2.2.20Math.log(x)
20.2.2.21Math.log1p(x)
20.2.2.22Math.log10(x)
20.2.2.23Math.log2(x)
20.2.2.24Math.max(value1,value2,...values)
20.2.2.25Math.min(value1,value2,...values)
20.2.2.26Math.pow(base,exponent)
20.2.2.27Math.random()
20.2.2.28Math.round(x)
20.2.2.29Math.sign(x)
20.2.2.30Math.sin(x)
20.2.2.31Math.sinh(x)
20.2.2.32Math.sqrt(x)
20.2.2.33Math.tan(x)
20.2.2.34Math.tanh(x)
20.2.2.35Math.trunc(x)
20.3DateObjects
20.3.1OverviewofDateObjectsandDeinitionsofAbstractOperations
20.3.1.1TimeValuesandTimeRange
20.3.1.2DayNumberandTimewithinDay
20.3.1.3YearNumber
20.3.1.4MonthNumber
20.3.1.5DateNumber
20.3.1.6WeekDay
20.3.1.7LocalTimeZoneAdjustment
20.3.1.8DaylightSavingTimeAdjustment
20.3.1.9LocalTime(t)
20.3.1.10UTC(t)
20.3.1.11Hours,Minutes,Second,andMilliseconds
20.3.1.12MakeTime(hour,min,sec,ms)
20.3.1.13MakeDay(year,month,date)
20.3.1.14MakeDate(day,time)
20.3.1.15TimeClip(time)
20.3.1.16DateTimeStringFormat
20.3.1.16.1ExtendedYears
20.3.2TheDateConstructor
20.3.2.1Date(year,month[,date[,hours[,minutes[,seconds[,ms]]]]])
20.3.2.2Date(value)
20.3.2.3Date()
20.3.3PropertiesoftheDateConstructor
20.3.3.1Date.now()
20.3.3.2Date.parse(string)
20.3.3.3Date.prototype
20.3.3.4Date.UTC(year,month[,date[,hours[,minutes[,seconds[,ms]]]]])
20.3.4PropertiesoftheDatePrototypeObject
20.3.4.1Date.prototype.constructor
20.3.4.2Date.prototype.getDate()
20.3.4.3Date.prototype.getDay()
20.3.4.4Date.prototype.getFullYear()
20.3.4.5Date.prototype.getHours()
20.3.4.6Date.prototype.getMilliseconds()
20.3.4.7Date.prototype.getMinutes()
20.3.4.8Date.prototype.getMonth()
20.3.4.9Date.prototype.getSeconds()
20.3.4.10Date.prototype.getTime()
20.3.4.11Date.prototype.getTimezoneOffset()
20.3.4.12Date.prototype.getUTCDate()
20.3.4.13Date.prototype.getUTCDay()
20.3.4.14Date.prototype.getUTCFullYear()
20.3.4.15Date.prototype.getUTCHours()
20.3.4.16Date.prototype.getUTCMilliseconds()
20.3.4.17Date.prototype.getUTCMinutes()
20.3.4.18Date.prototype.getUTCMonth()
20.3.4.19Date.prototype.getUTCSeconds()
20.3.4.20Date.prototype.setDate(date)
20.3.4.21Date.prototype.setFullYear(year[,month[,date]])
20.3.4.22Date.prototype.setHours(hour[,min[,sec[,ms]]])
20.3.4.23Date.prototype.setMilliseconds(ms)
20.3.4.24Date.prototype.setMinutes(min[,sec[,ms]])
20.3.4.25Date.prototype.setMonth(month[,date])
20.3.4.26Date.prototype.setSeconds(sec[,ms])
20.3.4.27Date.prototype.setTime(time)
20.3.4.28Date.prototype.setUTCDate(date)
20.3.4.29Date.prototype.setUTCFullYear(year[,month[,date]])
20.3.4.30Date.prototype.setUTCHours(hour[,min[,sec[,ms]]])
20.3.4.31Date.prototype.setUTCMilliseconds(ms)
20.3.4.32Date.prototype.setUTCMinutes(min[,sec[,ms]])
20.3.4.33Date.prototype.setUTCMonth(month[,date])
20.3.4.34Date.prototype.setUTCSeconds(sec[,ms])
20.3.4.35Date.prototype.toDateString()
20.3.4.36Date.prototype.toISOString()
20.3.4.37Date.prototype.toJSON(key)
20.3.4.38Date.prototype.toLocaleDateString([reserved1[,reserved2]])
20.3.4.39Date.prototype.toLocaleString([reserved1[,reserved2]])
20.3.4.40Date.prototype.toLocaleTimeString([reserved1[,reserved2]])
20.3.4.41Date.prototype.toString()
20.3.4.41.1RS:ToDateString(tv)
20.3.4.42Date.prototype.toTimeString()
20.3.4.43Date.prototype.toUTCString()
20.3.4.44Date.prototype.valueOf()
20.3.4.45Date.prototype[@@toPrimitive](hint)
20.3.5PropertiesofDateInstances
21TextProcessing
21.1StringObjects
21.1.1TheStringConstructor
21.1.1.1String(value)
21.1.2PropertiesoftheStringConstructor
21.1.2.1String.fromCharCode(...codeUnits)
21.1.2.2String.fromCodePoint(...codePoints)
21.1.2.3String.prototype
21.1.2.4String.raw(template,...substitutions)
21.1.3PropertiesoftheStringPrototypeObject
21.1.3.1String.prototype.charAt(pos)
21.1.3.2String.prototype.charCodeAt(pos)
21.1.3.3String.prototype.codePointAt(pos)
21.1.3.4String.prototype.concat(...args)
21.1.3.5String.prototype.constructor
21.1.3.6String.prototype.endsWith(searchString[,endPosition])
21.1.3.7String.prototype.includes(searchString[,position])
21.1.3.8String.prototype.indexOf(searchString[,position])
21.1.3.9String.prototype.lastIndexOf(searchString[,position])
21.1.3.10String.prototype.localeCompare(that[,reserved1[,reserved2]])
21.1.3.11String.prototype.match(regexp)
21.1.3.12String.prototype.normalize([form])
21.1.3.13String.prototype.repeat(count)
21.1.3.14String.prototype.replace(searchValue,replaceValue)
21.1.3.14.1RS:GetSubstitution(matched,str,position,captures,replacement)
21.1.3.15String.prototype.search(regexp)
21.1.3.16String.prototype.slice(start,end)
21.1.3.17String.prototype.split(separator,limit)
21.1.3.17.1RS:SplitMatch(S,q,R)
21.1.3.18String.prototype.startsWith(searchString[,position])
21.1.3.19String.prototype.substring(start,end)
21.1.3.20String.prototype.toLocaleLowerCase([reserved1[,reserved2]])
21.1.3.21String.prototype.toLocaleUpperCase([reserved1[,reserved2]])
21.1.3.22String.prototype.toLowerCase()
21.1.3.23String.prototype.toString()
21.1.3.24String.prototype.toUpperCase()
21.1.3.25String.prototype.trim()
21.1.3.26String.prototype.valueOf()
21.1.3.27String.prototype[@@iterator]()
21.1.4PropertiesofStringInstances
21.1.4.1length
21.1.5StringIteratorObjects
21.1.5.1CreateStringIteratorAbstractOperation
21.1.5.2The%StringIteratorPrototype%Object
21.1.5.2.1%StringIteratorPrototype%.next()
21.1.5.2.2%StringIteratorPrototype%[@@toStringTag]
21.1.5.3PropertiesofStringIteratorInstances
21.2RegExp(RegularExpression)Objects
21.2.1Patterns
21.2.1.1SS:EarlyErrors
21.2.2PatternSemantics
21.2.2.1Notation
21.2.2.2Pattern
21.2.2.3Disjunction
21.2.2.4Alternative
21.2.2.5Term
21.2.2.5.1RS:RepeatMatcherAbstractOperation
21.2.2.6Assertion
21.2.2.6.1RS:IsWordCharAbstractOperation
21.2.2.7Quantiier
21.2.2.8Atom
21.2.2.8.1RS:CharacterSetMatcherAbstractOperation
21.2.2.8.2RS:Canonicalize(ch)
21.2.2.9AtomEscape
21.2.2.10CharacterEscape
21.2.2.11DecimalEscape
21.2.2.12CharacterClassEscape
21.2.2.13CharacterClass
21.2.2.14ClassRanges
21.2.2.15NonemptyClassRanges
21.2.2.15.1RS:CharacterRangeAbstractOperation
21.2.2.16NonemptyClassRangesNoDash
21.2.2.17ClassAtom
21.2.2.18ClassAtomNoDash
21.2.2.19ClassEscape
21.2.3TheRegExpConstructor
21.2.3.1RegExp(pattern,lags)
21.2.3.2AbstractOperationsfortheRegExpConstructor
21.2.3.2.1RS:RegExpAlloc(newTarget)
21.2.3.2.2RS:RegExpInitialize(obj,pattern,lags)
21.2.3.2.3RS:RegExpCreate(P,F)
21.2.3.2.4RS:EscapeRegExpPattern(P,F)
21.2.4PropertiesoftheRegExpConstructor
21.2.4.1RegExp.prototype
21.2.4.2getRegExp[@@species]
21.2.5PropertiesoftheRegExpPrototypeObject
21.2.5.1RegExp.prototype.constructor
21.2.5.2RegExp.prototype.exec(string)
21.2.5.2.1RS:RegExpExec(R,S)
21.2.5.2.2RS:RegExpBuiltinExec(R,S)
21.2.5.2.3AdvanceStringIndex(S,index,unicode)
21.2.5.3getRegExp.prototype.lags
21.2.5.4getRegExp.prototype.global
21.2.5.5getRegExp.prototype.ignoreCase
21.2.5.6RegExp.prototype[@@match](string)
21.2.5.7getRegExp.prototype.multiline
21.2.5.8RegExp.prototype[@@replace](string,replaceValue)
21.2.5.9RegExp.prototype[@@search](string)
21.2.5.10getRegExp.prototype.source
21.2.5.11RegExp.prototype[@@split](string,limit)
21.2.5.12getRegExp.prototype.sticky
21.2.5.13RegExp.prototype.test(S)
21.2.5.14RegExp.prototype.toString()
21.2.5.15getRegExp.prototype.unicode
21.2.6PropertiesofRegExpInstances
21.2.6.1lastIndex
22IndexedCollections
22.1ArrayObjects
22.1.1TheArrayConstructor
22.1.1.1Array()
22.1.1.2Array(len)
22.1.1.3Array(...items)
22.1.2PropertiesoftheArrayConstructor
22.1.2.1Array.from(items[,mapfn[,thisArg]])
22.1.2.2Array.isArray(arg)
22.1.2.3Array.of(...items)
22.1.2.4Array.prototype
22.1.2.5getArray[@@species]
22.1.3PropertiesoftheArrayPrototypeObject
22.1.3.1Array.prototype.concat(...arguments)
22.1.3.1.1RS:IsConcatSpreadable(O)
22.1.3.2Array.prototype.constructor
22.1.3.3Array.prototype.copyWithin(target,start[,end])
22.1.3.4Array.prototype.entries()
22.1.3.5Array.prototype.every(callbackfn[,thisArg])
22.1.3.6Array.prototype.ill(value[,start[,end]])
22.1.3.7Array.prototype.ilter(callbackfn[,thisArg])
22.1.3.8Array.prototype.ind(predicate[,thisArg])
22.1.3.9Array.prototype.indIndex(predicate[,thisArg])
22.1.3.10Array.prototype.forEach(callbackfn[,thisArg])
22.1.3.11Array.prototype.includes(searchElement[,fromIndex])
22.1.3.12Array.prototype.indexOf(searchElement[,fromIndex])
22.1.3.13Array.prototype.join(separator)
22.1.3.14Array.prototype.keys()
22.1.3.15Array.prototype.lastIndexOf(searchElement[,fromIndex])
22.1.3.16Array.prototype.map(callbackfn[,thisArg])
22.1.3.17Array.prototype.pop()
22.1.3.18Array.prototype.push(...items)
22.1.3.19Array.prototype.reduce(callbackfn[,initialValue])
22.1.3.20Array.prototype.reduceRight(callbackfn[,initialValue])
22.1.3.21Array.prototype.reverse()
22.1.3.22Array.prototype.shift()
22.1.3.23Array.prototype.slice(start,end)
22.1.3.24Array.prototype.some(callbackfn[,thisArg])
22.1.3.25Array.prototype.sort(comparefn)
22.1.3.25.1RS:SortCompare(x,y)
22.1.3.26Array.prototype.splice(start,deleteCount,...items)
22.1.3.27Array.prototype.toLocaleString([reserved1[,reserved2]])
22.1.3.28Array.prototype.toString()
22.1.3.29Array.prototype.unshift(...items)
22.1.3.30Array.prototype.values()
22.1.3.31Array.prototype[@@iterator]()
22.1.3.32Array.prototype[@@unscopables]
22.1.4PropertiesofArrayInstances
22.1.4.1length
22.1.5ArrayIteratorObjects
22.1.5.1CreateArrayIteratorAbstractOperation
22.1.5.2The%ArrayIteratorPrototype%Object
22.1.5.2.1%ArrayIteratorPrototype%.next()
22.1.5.2.2%ArrayIteratorPrototype%[@@toStringTag]
22.1.5.3PropertiesofArrayIteratorInstances
22.2TypedArrayObjects
22.2.1The%TypedArray%IntrinsicObject
22.2.1.1%TypedArray%()
22.2.2Propertiesofthe%TypedArray%IntrinsicObject
22.2.2.1%TypedArray%.from(source[,mapfn[,thisArg]])
22.2.2.1.1RS:IterableToArrayLike(items)
22.2.2.2%TypedArray%.of(...items)
22.2.2.3%TypedArray%.prototype
22.2.2.4get%TypedArray%[@@species]
22.2.3Propertiesofthe%TypedArrayPrototype%Object
22.2.3.1get%TypedArray%.prototype.buffer
22.2.3.2get%TypedArray%.prototype.byteLength
22.2.3.3get%TypedArray%.prototype.byteOffset
22.2.3.4%TypedArray%.prototype.constructor
22.2.3.5%TypedArray%.prototype.copyWithin(target,start[,end])
22.2.3.5.1RS:ValidateTypedArray(O)
22.2.3.6%TypedArray%.prototype.entries()
22.2.3.7%TypedArray%.prototype.every(callbackfn[,thisArg])
22.2.3.8%TypedArray%.prototype.ill(value[,start[,end]])
22.2.3.9%TypedArray%.prototype.ilter(callbackfn[,thisArg])
22.2.3.10%TypedArray%.prototype.ind(predicate[,thisArg])
22.2.3.11%TypedArray%.prototype.indIndex(predicate[,thisArg])
22.2.3.12%TypedArray%.prototype.forEach(callbackfn[,thisArg])
22.2.3.13%TypedArray%.prototype.indexOf(searchElement[,fromIndex])
22.2.3.14%TypedArray%.prototype.includes(searchElement[,fromIndex])
22.2.3.15%TypedArray%.prototype.join(separator)
22.2.3.16%TypedArray%.prototype.keys()
22.2.3.17%TypedArray%.prototype.lastIndexOf(searchElement[,fromIndex])
22.2.3.18get%TypedArray%.prototype.length
22.2.3.19%TypedArray%.prototype.map(callbackfn[,thisArg])
22.2.3.20%TypedArray%.prototype.reduce(callbackfn[,initialValue])
22.2.3.21%TypedArray%.prototype.reduceRight(callbackfn[,initialValue])
22.2.3.22%TypedArray%.prototype.reverse()
22.2.3.23%TypedArray%.prototype.set(overloaded[,offset])
22.2.3.23.1%TypedArray%.prototype.set(array[,offset])
22.2.3.23.2%TypedArray%.prototype.set(typedArray[,offset])
22.2.3.24%TypedArray%.prototype.slice(start,end)
22.2.3.25%TypedArray%.prototype.some(callbackfn[,thisArg])
22.2.3.26%TypedArray%.prototype.sort(comparefn)
22.2.3.27%TypedArray%.prototype.subarray(begin,end)
22.2.3.28%TypedArray%.prototype.toLocaleString([reserved1[,reserved2]])
22.2.3.29%TypedArray%.prototype.toString()
22.2.3.30%TypedArray%.prototype.values()
22.2.3.31%TypedArray%.prototype[@@iterator]()
22.2.3.32get%TypedArray%.prototype[@@toStringTag]
22.2.4TheTypedArrayConstructors
22.2.4.1TypedArray()
22.2.4.2TypedArray(length)
22.2.4.2.1RS:AllocateTypedArray(constructorName,newTarget,defaultProto[,length])
22.2.4.2.2RS:AllocateTypedArrayBuffer(O,length)
22.2.4.3TypedArray(typedArray)
22.2.4.4TypedArray(object)
22.2.4.5TypedArray(buffer[,byteOffset[,length]])
22.2.4.6TypedArrayCreate(constructor,argumentList)
22.2.4.7TypedArraySpeciesCreate(exemplar,argumentList)
22.2.5PropertiesoftheTypedArrayConstructors
22.2.5.1TypedArray.BYTES_PER_ELEMENT
22.2.5.2TypedArray.prototype
22.2.6PropertiesofTypedArrayPrototypeObjects
22.2.6.1TypedArray.prototype.BYTES_PER_ELEMENT
22.2.6.2TypedArray.prototype.constructor
22.2.7PropertiesofTypedArrayInstances
23KeyedCollection
23.1MapObjects
23.1.1TheMapConstructor
23.1.1.1Map([iterable])
23.1.2PropertiesoftheMapConstructor
23.1.2.1Map.prototype
23.1.2.2getMap[@@species]
23.1.3PropertiesoftheMapPrototypeObject
23.1.3.1Map.prototype.clear()
23.1.3.2Map.prototype.constructor
23.1.3.3Map.prototype.delete(key)
23.1.3.4Map.prototype.entries()
23.1.3.5Map.prototype.forEach(callbackfn[,thisArg])
23.1.3.6Map.prototype.get(key)
23.1.3.7Map.prototype.has(key)
23.1.3.8Map.prototype.keys()
23.1.3.9Map.prototype.set(key,value)
23.1.3.10getMap.prototype.size
23.1.3.11Map.prototype.values()
23.1.3.12Map.prototype[@@iterator]()
23.1.3.13Map.prototype[@@toStringTag]
23.1.4PropertiesofMapInstances
23.1.5MapIteratorObjects
23.1.5.1CreateMapIteratorAbstractOperation
23.1.5.2The%MapIteratorPrototype%Object
23.1.5.2.1%MapIteratorPrototype%.next()
23.1.5.2.2%MapIteratorPrototype%[@@toStringTag]
23.1.5.3PropertiesofMapIteratorInstances
23.2SetObjects
23.2.1TheSetConstructor
23.2.1.1Set([iterable])
23.2.2PropertiesoftheSetConstructor
23.2.2.1Set.prototype
23.2.2.2getSet[@@species]
23.2.3PropertiesoftheSetPrototypeObject
23.2.3.1Set.prototype.add(value)
23.2.3.2Set.prototype.clear()
23.2.3.3Set.prototype.constructor
23.2.3.4Set.prototype.delete(value)
23.2.3.5Set.prototype.entries()
23.2.3.6Set.prototype.forEach(callbackfn[,thisArg])
23.2.3.7Set.prototype.has(value)
23.2.3.8Set.prototype.keys()
23.2.3.9getSet.prototype.size
23.2.3.10Set.prototype.values()
23.2.3.11Set.prototype[@@iterator]()
23.2.3.12Set.prototype[@@toStringTag]
23.2.4PropertiesofSetInstances
23.2.5SetIteratorObjects
23.2.5.1CreateSetIteratorAbstractOperation
23.2.5.2The%SetIteratorPrototype%Object
23.2.5.2.1%SetIteratorPrototype%.next()
23.2.5.2.2%SetIteratorPrototype%[@@toStringTag]
23.2.5.3PropertiesofSetIteratorInstances
23.3WeakMapObjects
23.3.1TheWeakMapConstructor
23.3.1.1WeakMap([iterable])
23.3.2PropertiesoftheWeakMapConstructor
23.3.2.1WeakMap.prototype
23.3.3PropertiesoftheWeakMapPrototypeObject
23.3.3.1WeakMap.prototype.constructor
23.3.3.2WeakMap.prototype.delete(key)
23.3.3.3WeakMap.prototype.get(key)
23.3.3.4WeakMap.prototype.has(key)
23.3.3.5WeakMap.prototype.set(key,value)
23.3.3.6WeakMap.prototype[@@toStringTag]
23.3.4PropertiesofWeakMapInstances
23.4WeakSetObjects
23.4.1TheWeakSetConstructor
23.4.1.1WeakSet([iterable])
23.4.2PropertiesoftheWeakSetConstructor
23.4.2.1WeakSet.prototype
23.4.3PropertiesoftheWeakSetPrototypeObject
23.4.3.1WeakSet.prototype.add(value)
23.4.3.2WeakSet.prototype.constructor
23.4.3.3WeakSet.prototype.delete(value)
23.4.3.4WeakSet.prototype.has(value)
23.4.3.5WeakSet.prototype[@@toStringTag]
23.4.4PropertiesofWeakSetInstances
24StructuredData
24.1ArrayBufferObjects
24.1.1AbstractOperationsForArrayBufferObjects
24.1.1.1AllocateArrayBuffer(constructor,byteLength)
24.1.1.2IsDetachedBuffer(arrayBuffer)
24.1.1.3DetachArrayBuffer(arrayBuffer)
24.1.1.4CloneArrayBuffer(srcBuffer,srcByteOffset[,cloneConstructor])
24.1.1.5GetValueFromBuffer(arrayBuffer,byteIndex,type[,isLittleEndian])
24.1.1.6SetValueInBuffer(arrayBuffer,byteIndex,type,value[,isLittleEndian])
24.1.2TheArrayBufferConstructor
24.1.2.1ArrayBuffer(length)
24.1.3PropertiesoftheArrayBufferConstructor
24.1.3.1ArrayBuffer.isView(arg)
24.1.3.2ArrayBuffer.prototype
24.1.3.3getArrayBuffer[@@species]
24.1.4PropertiesoftheArrayBufferPrototypeObject
24.1.4.1getArrayBuffer.prototype.byteLength
24.1.4.2ArrayBuffer.prototype.constructor
24.1.4.3ArrayBuffer.prototype.slice(start,end)
24.1.4.4ArrayBuffer.prototype[@@toStringTag]
24.1.5PropertiesoftheArrayBufferInstances
24.2DataViewObjects
24.2.1AbstractOperationsForDataViewObjects
24.2.1.1GetViewValue(view,requestIndex,isLittleEndian,type)
24.2.1.2SetViewValue(view,requestIndex,isLittleEndian,type,value)
24.2.2TheDataViewConstructor
24.2.2.1DataView(buffer,byteOffset,byteLength)
24.2.3PropertiesoftheDataViewConstructor
24.2.3.1DataView.prototype
24.2.4PropertiesoftheDataViewPrototypeObject
24.2.4.1getDataView.prototype.buffer
24.2.4.2getDataView.prototype.byteLength
24.2.4.3getDataView.prototype.byteOffset
24.2.4.4DataView.prototype.constructor
24.2.4.5DataView.prototype.getFloat32(byteOffset[,littleEndian])
24.2.4.6DataView.prototype.getFloat64(byteOffset[,littleEndian])
24.2.4.7DataView.prototype.getInt8(byteOffset)
24.2.4.8DataView.prototype.getInt16(byteOffset[,littleEndian])
24.2.4.9DataView.prototype.getInt32(byteOffset[,littleEndian])
24.2.4.10DataView.prototype.getUint8(byteOffset)
24.2.4.11DataView.prototype.getUint16(byteOffset[,littleEndian])
24.2.4.12DataView.prototype.getUint32(byteOffset[,littleEndian])
24.2.4.13DataView.prototype.setFloat32(byteOffset,value[,littleEndian])
24.2.4.14DataView.prototype.setFloat64(byteOffset,value[,littleEndian])
24.2.4.15DataView.prototype.setInt8(byteOffset,value)
24.2.4.16DataView.prototype.setInt16(byteOffset,value[,littleEndian])
24.2.4.17DataView.prototype.setInt32(byteOffset,value[,littleEndian])
24.2.4.18DataView.prototype.setUint8(byteOffset,value)
24.2.4.19DataView.prototype.setUint16(byteOffset,value[,littleEndian])
24.2.4.20DataView.prototype.setUint32(byteOffset,value[,littleEndian])
24.2.4.21DataView.prototype[@@toStringTag]
24.2.5PropertiesofDataViewInstances
24.3TheJSONObject
24.3.1JSON.parse(text[,reviver])
24.3.1.1RS:InternalizeJSONProperty(holder,name)
24.3.2JSON.stringify(value[,replacer[,space]])
24.3.2.1RS:SerializeJSONProperty(key,holder)
24.3.2.2RS:QuoteJSONString(value)
24.3.2.3RS:SerializeJSONObject(value)
24.3.2.4RS:SerializeJSONArray(value)
24.3.3JSON[@@toStringTag]
25ControlAbstractionObjects
25.1Iteration
25.1.1CommonIterationInterfaces
25.1.1.1TheIterableInterface
25.1.1.2TheIteratorInterface
25.1.1.3TheIteratorResultInterface
25.1.2The%IteratorPrototype%Object
25.1.2.1%IteratorPrototype%[@@iterator]()
25.2GeneratorFunctionObjects
25.2.1TheGeneratorFunctionConstructor
25.2.1.1GeneratorFunction(p1,p2,,pn,body)
25.2.2PropertiesoftheGeneratorFunctionConstructor
25.2.2.1GeneratorFunction.length
25.2.2.2GeneratorFunction.prototype
25.2.3PropertiesoftheGeneratorFunctionPrototypeObject
25.2.3.1GeneratorFunction.prototype.constructor
25.2.3.2GeneratorFunction.prototype.prototype
25.2.3.3GeneratorFunction.prototype[@@toStringTag]
25.2.4GeneratorFunctionInstances
25.2.4.1length
25.2.4.2name
25.2.4.3prototype
25.3GeneratorObjects
25.3.1PropertiesofGeneratorPrototype
25.3.1.1Generator.prototype.constructor
25.3.1.2Generator.prototype.next(value)
25.3.1.3Generator.prototype.return(value)
25.3.1.4Generator.prototype.throw(exception)
25.3.1.5Generator.prototype[@@toStringTag]
25.3.2PropertiesofGeneratorInstances
25.3.3GeneratorAbstractOperations
25.3.3.1GeneratorStart(generator,generatorBody)
25.3.3.2GeneratorValidate(generator)
25.3.3.3GeneratorResume(generator,value)
25.3.3.4GeneratorResumeAbrupt(generator,abruptCompletion)
25.3.3.5GeneratorYield(iterNextObj)
25.4PromiseObjects
25.4.1PromiseAbstractOperations
25.4.1.1PromiseCapabilityRecords
25.4.1.1.1IfAbruptRejectPromise(value,capability)
25.4.1.2PromiseReactionRecords
25.4.1.3CreateResolvingFunctions(promise)
25.4.1.3.1PromiseRejectFunctions
25.4.1.3.2PromiseResolveFunctions
25.4.1.4FulillPromise(promise,value)
25.4.1.5NewPromiseCapability(C)
25.4.1.5.1GetCapabilitiesExecutorFunctions
25.4.1.6IsPromise(x)
25.4.1.7RejectPromise(promise,reason)
25.4.1.8TriggerPromiseReactions(reactions,argument)
25.4.1.9HostPromiseRejectionTracker(promise,operation)
25.4.2PromiseJobs
25.4.2.1PromiseReactionJob(reaction,argument)
25.4.2.2PromiseResolveThenableJob(promiseToResolve,thenable,then)
25.4.3ThePromiseConstructor
25.4.3.1Promise(executor)
25.4.4PropertiesofthePromiseConstructor
25.4.4.1Promise.all(iterable)
25.4.4.1.1RS:PerformPromiseAll(iteratorRecord,constructor,resultCapability)
25.4.4.1.2Promise.allResolveElementFunctions
25.4.4.2Promise.prototype
25.4.4.3Promise.race(iterable)
25.4.4.3.1RS:PerformPromiseRace(iteratorRecord,promiseCapability,C)
25.4.4.4Promise.reject(r)
25.4.4.5Promise.resolve(x)
25.4.4.6getPromise[@@species]
25.4.5PropertiesofthePromisePrototypeObject
25.4.5.1Promise.prototype.catch(onRejected)
25.4.5.2Promise.prototype.constructor
25.4.5.3Promise.prototype.then(onFulilled,onRejected)
25.4.5.3.1PerformPromiseThen(promise,onFulilled,onRejected,resultCapability)
25.4.5.4Promise.prototype[@@toStringTag]
25.4.6PropertiesofPromiseInstances
26Relection
26.1TheRelectObject
26.1.1Relect.apply(target,thisArgument,argumentsList)
26.1.2Relect.construct(target,argumentsList[,newTarget])
26.1.3Relect.deineProperty(target,propertyKey,attributes)
26.1.4Relect.deleteProperty(target,propertyKey)
26.1.5Relect.get(target,propertyKey[,receiver])
26.1.6Relect.getOwnPropertyDescriptor(target,propertyKey)
26.1.7Relect.getPrototypeOf(target)
26.1.8Relect.has(target,propertyKey)
26.1.9Relect.isExtensible(target)
26.1.10Relect.ownKeys(target)
26.1.11Relect.preventExtensions(target)
26.1.12Relect.set(target,propertyKey,V[,receiver])
26.1.13Relect.setPrototypeOf(target,proto)
26.2ProxyObjects
26.2.1TheProxyConstructor
26.2.1.1Proxy(target,handler)
26.2.2PropertiesoftheProxyConstructor
26.2.2.1Proxy.revocable(target,handler)
26.2.2.1.1ProxyRevocationFunctions
26.3ModuleNamespaceObjects
26.3.1@@toStringTag
26.3.2[@@iterator]()
AGrammarSummary
A.1LexicalGrammar
A.2Expressions
A.3Statements
A.4FunctionsandClasses
A.5ScriptsandModules
A.6NumberConversions
A.7UniversalResourceIdentiierCharacterClasses
A.8RegularExpressions
BAdditionalECMAScriptFeaturesforWebBrowsers
B.1AdditionalSyntax
B.1.1NumericLiterals
B.1.1.1StaticSemantics
B.1.2StringLiterals
B.1.2.1StaticSemantics
B.1.3HTMLlikeComments
B.1.4RegularExpressionsPatterns
B.1.4.1PatternSemantics
B.1.4.1.1RS:CharacterRangeOrUnionAbstractOperation
B.2AdditionalBuiltinProperties
B.2.1AdditionalPropertiesoftheGlobalObject
B.2.1.1escape(string)
B.2.1.2unescape(string)
B.2.2AdditionalPropertiesoftheObject.prototypeObject
B.2.2.1Object.prototype.__proto__
B.2.2.1.1getObject.prototype.__proto__
B.2.2.1.2setObject.prototype.__proto__
B.2.3AdditionalPropertiesoftheString.prototypeObject
B.2.3.1String.prototype.substr(start,length)
B.2.3.2String.prototype.anchor(name)
B.2.3.2.1RS:CreateHTML(string,tag,attribute,value)
B.2.3.3String.prototype.big()
B.2.3.4String.prototype.blink()
B.2.3.5String.prototype.bold()
B.2.3.6String.prototype.ixed()
B.2.3.7String.prototype.fontcolor(color)
B.2.3.8String.prototype.fontsize(size)
B.2.3.9String.prototype.italics()
B.2.3.10String.prototype.link(url)
B.2.3.11String.prototype.small()
B.2.3.12String.prototype.strike()
B.2.3.13String.prototype.sub()
B.2.3.14String.prototype.sup()
B.2.4AdditionalPropertiesoftheDate.prototypeObject
B.2.4.1Date.prototype.getYear()
B.2.4.2Date.prototype.setYear(year)
B.2.4.3Date.prototype.toGMTString()
B.2.5AdditionalPropertiesoftheRegExp.prototypeObject
B.2.5.1RegExp.prototype.compile(pattern,lags)
B.3OtherAdditionalFeatures
B.3.1__proto__PropertyNamesinObjectInitializers
B.3.2LabelledFunctionDeclarations
B.3.3BlockLevelFunctionDeclarationsWebLegacyCompatibilitySemantics
B.3.3.1ChangestoFunctionDeclarationInstantiation
B.3.3.2ChangestoGlobalDeclarationInstantiation
B.3.3.3ChangestoEvalDeclarationInstantiation
B.3.4FunctionDeclarationsinIfStatementStatementClauses
B.3.5VariableStatementsinCatchBlocks
CTheStrictModeofECMAScript
DCorrectionsandClariicationsinECMAScript2015withPossibleCompatibilityImpact
EAdditionsandChangesThatIntroduceIncompatibilitieswithPriorEditions
FBibliography
GCopyright&SoftwareLicense
Introduction
ThisEcmaStandarddeinestheECMAScript2016Language.ItistheseventheditionoftheECMAScriptLanguage
Speciication.Sincepublicationoftheirsteditionin1997,ECMAScripthasgrowntobeoneoftheworld'smostwidelyused
generalpurposeprogramminglanguages.Itisbestknownasthelanguageembeddedinwebbrowsersbuthasalsobeen
widelyadoptedforserverandembeddedapplications.

ECMAScriptisbasedonseveraloriginatingtechnologies,themostwellknownbeingJavaScript(Netscape)andJScript
(Microsoft).ThelanguagewasinventedbyBrendanEichatNetscapeandirstappearedinthatcompany'sNavigator2.0
browser.IthasappearedinallsubsequentbrowsersfromNetscapeandinallbrowsersfromMicrosoftstartingwithInternet
Explorer3.0.

ThedevelopmentoftheECMAScriptLanguageSpeciicationstartedinNovember1996.TheirsteditionofthisEcma
StandardwasadoptedbytheEcmaGeneralAssemblyofJune1997.

ThatEcmaStandardwassubmittedtoISO/IECJTC1foradoptionunderthefasttrackprocedure,andapprovedas
internationalstandardISO/IEC16262,inApril1998.TheEcmaGeneralAssemblyofJune1998approvedthesecondedition
ofECMA262tokeepitfullyalignedwithISO/IEC16262.Changesbetweentheirstandthesecondeditionareeditorialin
nature.

ThethirdeditionoftheStandardintroducedpowerfulregularexpressions,betterstringhandling,newcontrolstatements,
try/catchexceptionhandling,tighterdeinitionoferrors,formattingfornumericoutputandminorchangesinanticipation
futurelanguagegrowth.ThethirdeditionoftheECMAScriptstandardwasadoptedbytheEcmaGeneralAssemblyof
December1999andpublishedasISO/IEC16262:2002inJune2002.

Afterpublicationofthethirdedition,ECMAScriptachievedmassiveadoptioninconjunctionwiththeWorldWideWebwhere
ithasbecometheprogramminglanguagethatissupportedbyessentiallyallwebbrowsers.Signiicantworkwasdoneto
developafourtheditionofECMAScript.However,thatworkwasnotcompletedandnotpublishedasthefourtheditionof
ECMAScriptbutsomeofitwasincorporatedintothedevelopmentofthesixthedition.

TheiftheditionofECMAScript(publishedasECMA2625thedition)codiieddefactointerpretationsofthelanguage
speciicationthathavebecomecommonamongbrowserimplementationsandaddedsupportfornewfeaturesthathad
emergedsincethepublicationofthethirdedition.Suchfeaturesincludeaccessorproperties,relectivecreationand
inspectionofobjects,programcontrolofpropertyattributes,additionalarraymanipulationfunctions,supportfortheJSON
objectencodingformat,andastrictmodethatprovidesenhancederrorcheckingandprogramsecurity.TheFifthEditionwas
adoptedbytheEcmaGeneralAssemblyofDecember2009.

TheifthEditionwassubmittedtoISO/IECJTC1foradoptionunderthefasttrackprocedure,andapprovedasinternational
standardISO/IEC16262:2011.Edition5.1oftheECMAScriptStandardincorporatedminorcorrectionsandisthesametext
asISO/IEC16262:2011.The5.1EditionwasadoptedbytheEcmaGeneralAssemblyofJune2011.

Focuseddevelopmentofthesixtheditionstartedin2009,astheiftheditionwasbeingpreparedforpublication.However,
thiswasprecededbysigniicantexperimentationandlanguageenhancementdesigneffortsdatingtothepublicationofthe
thirdeditionin1999.Inaveryrealsense,thecompletionofthesixtheditionistheculminationofaifteenyeareffort.The
goalsforthisadditionincludedprovidingbettersupportforlargeapplications,librarycreation,andforuseofECMAScriptas
acompilationtargetforotherlanguages.Someofitsmajorenhancementsincludedmodules,classdeclarations,lexicalblock
scoping,iteratorsandgenerators,promisesforasynchronousprogramming,destructuringpatterns,andpropertailcalls.The
ECMAScriptlibraryofbuiltinswasexpandedtosupportadditionaldataabstractionsincludingmaps,sets,andarraysof
binarynumericvaluesaswellasadditionalsupportforUnicodesupplementalcharactersinstringsandregularexpressions.
Thebuiltinswerealsomadeextensibleviasubclassing.Thesixtheditionprovidesthefoundationforregular,incremental
languageandlibraryenhancements.ThesixtheditionwasadoptedbytheGeneralAssemblyofJune2015.

ThisECMAScriptspeciicationistheirstECMAScripteditionreleasedunderEcmaTC39'snewyearlyreleasecadenceand
opendevelopmentprocess.AplaintextsourcedocumentwasbuiltfromtheECMAScript2015sourcedocumenttoserveas
thebaseforfurtherdevelopmententirelyonGitHub.Overtheyearofthisstandard'sdevelopment,hundredsofpullrequests
andissueswereiledrepresentingthousandsofbugixes,editorialixesandotherimprovements.Additionally,numerous
softwaretoolsweredevelopedtoaidinthiseffortincludingEcmarkup,Ecmarkdown,andGrammarkdown.Thisspeciication
alsoincludessupportforanewexponentiationoperatorandaddsanewmethodtoArray.prototypecalledincludes.

DozensofindividualsrepresentingmanyorganizationshavemadeverysigniicantcontributionswithinEcmaTC39tothe
developmentofthiseditionandtotheprioreditions.Inaddition,avibrantcommunityhasemergedsupportingTC39's
ECMAScriptefforts.Thiscommunityhasreviewednumerousdrafts,iledthousandsofbugreports,performed
implementationexperiments,contributedtestsuites,andeducatedtheworldwidedevelopercommunityaboutECMAScript.
Unfortunately,itisimpossibletoidentifyandacknowledgeeverypersonandorganizationwhohascontributedtothiseffort.

AllenWirfsBrock
ECMA262,6thEditionProjectEditor

BrianTerlson
ECMA262,7thEditionProjectEditor

1 Scope
ThisStandarddeinestheECMAScript2016generalpurposeprogramminglanguage.

2 Conformance
AconformingimplementationofECMAScriptmustprovideandsupportallthetypes,values,objects,properties,functions,
andprogramsyntaxandsemanticsdescribedinthisspeciication.

AconformingimplementationofECMAScriptmustinterpretsourcetextinputinconformancewiththeUnicodeStandard,
Version8.0.0orlaterandISO/IEC10646.

AconformingimplementationofECMAScriptthatprovidesanapplicationprogramminginterfacethatsupportsprograms
thatneedtoadapttothelinguisticandculturalconventionsusedbydifferenthumanlanguagesandcountriesmust
implementtheinterfacedeinedbythemostrecenteditionofECMA402thatiscompatiblewiththisspeciication.

AconformingimplementationofECMAScriptmayprovideadditionaltypes,values,objects,properties,andfunctionsbeyond
thosedescribedinthisspeciication.Inparticular,aconformingimplementationofECMAScriptmayprovidepropertiesnot
describedinthisspeciication,andvaluesforthoseproperties,forobjectsthataredescribedinthisspeciication.

AconformingimplementationofECMAScriptmaysupportprogramandregularexpressionsyntaxnotdescribedinthis
speciication.Inparticular,aconformingimplementationofECMAScriptmaysupportprogramsyntaxthatmakesuseofthe
futurereservedwordslistedinsubclause11.6.2.2ofthisspeciication.

AconformingimplementationofECMAScriptmustnotimplementanyextensionthatislistedasaForbiddenExtensionin
subclause16.2.

3 NormativeReferences
Thefollowingreferenceddocumentsareindispensablefortheapplicationofthisdocument.Fordatedreferences,onlythe
editioncitedapplies.Forundatedreferences,thelatesteditionofthereferenceddocument(includinganyamendments)
applies.

ISO/IEC10646:2003:InformationTechnologyUniversalMultipleOctetCodedCharacterSet(UCS)plusAmendment1:2005,
Amendment2:2006,Amendment3:2008,andAmendment4:2008,plusadditionalamendmentsandcorrigenda,orsuccessor

ECMA402,ECMAScript2015InternationalizationAPISpeciication.
http://www.ecmainternational.org/publications/standards/Ecma402.htm
ECMA404,TheJSONDataInterchangeFormat.
http://www.ecmainternational.org/publications/standards/Ecma404.htm

4 Overview
ThissectioncontainsanonnormativeoverviewoftheECMAScriptlanguage.

ECMAScriptisanobjectorientedprogramminglanguageforperformingcomputationsandmanipulatingcomputational
objectswithinahostenvironment.ECMAScriptasdeinedhereisnotintendedtobecomputationallyselfsuficient;indeed,
therearenoprovisionsinthisspeciicationforinputofexternaldataoroutputofcomputedresults.Instead,itisexpected
thatthecomputationalenvironmentofanECMAScriptprogramwillprovidenotonlytheobjectsandotherfacilities
describedinthisspeciicationbutalsocertainenvironmentspeciicobjects,whosedescriptionandbehaviourarebeyond
thescopeofthisspeciicationexcepttoindicatethattheymayprovidecertainpropertiesthatcanbeaccessedandcertain
functionsthatcanbecalledfromanECMAScriptprogram.

ECMAScriptwasoriginallydesignedtobeusedasascriptinglanguage,buthasbecomewidelyusedasageneralpurpose
programminglanguage.Ascriptinglanguageisaprogramminglanguagethatisusedtomanipulate,customize,andautomate
thefacilitiesofanexistingsystem.Insuchsystems,usefulfunctionalityisalreadyavailablethroughauserinterface,andthe
scriptinglanguageisamechanismforexposingthatfunctionalitytoprogramcontrol.Inthisway,theexistingsystemissaid
toprovideahostenvironmentofobjectsandfacilities,whichcompletesthecapabilitiesofthescriptinglanguage.Ascripting
languageisintendedforusebybothprofessionalandnonprofessionalprogrammers.

ECMAScriptwasoriginallydesignedtobeaWebscriptinglanguage,providingamechanismtoenlivenWebpagesin
browsersandtoperformservercomputationaspartofaWebbasedclientserverarchitecture.ECMAScriptisnowusedto
providecorescriptingcapabilitiesforavarietyofhostenvironments.Thereforethecorelanguageisspeciiedinthis
documentapartfromanyparticularhostenvironment.

ECMAScriptusagehasmovedbeyondsimplescriptinganditisnowusedforthefullspectrumofprogrammingtasksinmany
differentenvironmentsandscales.AstheusageofECMAScripthasexpanded,sohasthefeaturesandfacilitiesitprovides.
ECMAScriptisnowafullyfeaturedgeneralproposeprogramminglanguage.

SomeofthefacilitiesofECMAScriptaresimilartothoseusedinotherprogramminglanguages;inparticularC,Java,Self,
andSchemeasdescribedin:

ISO/IEC9899:1996,ProgrammingLanguagesC.

Gosling,James,BillJoyandGuySteele.TheJavaLanguageSpeciication.AddisonWesleyPublishingCo.,1996.

Ungar,David,andSmith,RandallB.Self:ThePowerofSimplicity.OOPSLA'87ConferenceProceedings,pp.227241,Orlando,
FL,October1987.

IEEEStandardfortheSchemeProgrammingLanguage.IEEEStd11781990.

4.1 WebScripting
AwebbrowserprovidesanECMAScripthostenvironmentforclientsidecomputationincluding,forinstance,objectsthat
representwindows,menus,popups,dialogboxes,textareas,anchors,frames,history,cookies,andinput/output.Further,
thehostenvironmentprovidesameanstoattachscriptingcodetoeventssuchaschangeoffocus,pageandimageloading,
unloading,errorandabort,selection,formsubmission,andmouseactions.ScriptingcodeappearswithintheHTMLandthe
displayedpageisacombinationofuserinterfaceelementsandixedandcomputedtextandimages.Thescriptingcodeis
reactivetouserinteractionandthereisnoneedforamainprogram.

Awebserverprovidesadifferenthostenvironmentforserversidecomputationincludingobjectsrepresentingrequests,
clients,andiles;andmechanismstolockandsharedata.Byusingbrowsersideandserversidescriptingtogether,itis
possibletodistributecomputationbetweentheclientandserverwhileprovidingacustomizeduserinterfaceforaWeb
basedapplication.
EachWebbrowserandserverthatsupportsECMAScriptsuppliesitsownhostenvironment,completingtheECMAScript
executionenvironment.

4.2 ECMAScriptOverview
ThefollowingisaninformaloverviewofECMAScriptnotallpartsofthelanguagearedescribed.Thisoverviewisnotpart
ofthestandardproper.

ECMAScriptisobjectbased:basiclanguageandhostfacilitiesareprovidedbyobjects,andanECMAScriptprogramisa
clusterofcommunicatingobjects.InECMAScript,anobjectisacollectionofzeroormorepropertieseachwithattributesthat
determinehoweachpropertycanbeusedforexample,whentheWritableattributeforapropertyissettofalse,any
attemptbyexecutedECMAScriptcodetoassignadifferentvaluetothepropertyfails.Propertiesarecontainersthathold
otherobjects,primitivevalues,orfunctions.Aprimitivevalueisamemberofoneofthefollowingbuiltintypes:Undeined,
Null,Boolean,Number,String,andSymbol;anobjectisamemberofthebuiltintypeObject;andafunctionisacallable
object.Afunctionthatisassociatedwithanobjectviaapropertyiscalledamethod.

ECMAScriptdeinesacollectionofbuiltinobjectsthatroundoutthedeinitionofECMAScriptentities.Thesebuiltinobjects
includetheglobalobject;objectsthatarefundamentaltotheruntimesemanticsofthelanguageincludingObject,
Function,Boolean,Symbol,andvariousErrorobjects;objectsthatrepresentandmanipulatenumericvaluesincluding
Math,Number,andDate;thetextprocessingobjectsStringandRegExp;objectsthatareindexedcollectionsofvalues
includingArrayandninedifferentkindsofTypedArrayswhoseelementsallhaveaspeciicnumericdatarepresentation;
keyedcollectionsincludingMapandSetobjects;objectssupportingstructureddataincludingtheJSONobject,
ArrayBuffer,andDataView;objectssupportingcontrolabstractionsincludinggeneratorfunctionsandPromiseobjects;
and,relectionobjectsincludingProxyandReflect.

ECMAScriptalsodeinesasetofbuiltinoperators.ECMAScriptoperatorsincludevariousunaryoperations,multiplicative
operators,additiveoperators,bitwiseshiftoperators,relationaloperators,equalityoperators,binarybitwiseoperators,
binarylogicaloperators,assignmentoperators,andthecommaoperator.

LargeECMAScriptprogramsaresupportedbymoduleswhichallowaprogramtobedividedintomultiplesequencesof
statementsanddeclarations.Eachmoduleexplicitlyidentiiesdeclarationsitusesthatneedtobeprovidedbyothermodules
andwhichofitsdeclarationsareavailableforusebyothermodules.

ECMAScriptsyntaxintentionallyresemblesJavasyntax.ECMAScriptsyntaxisrelaxedtoenableittoserveasaneasytouse
scriptinglanguage.Forexample,avariableisnotrequiredtohaveitstypedeclarednoraretypesassociatedwithproperties,
anddeinedfunctionsarenotrequiredtohavetheirdeclarationsappeartextuallybeforecallstothem.

4.2.1 Objects

EventhoughECMAScriptincludessyntaxforclassdeinitions,ECMAScriptobjectsarenotfundamentallyclassbasedsuchas
thoseinC++,Smalltalk,orJava.Insteadobjectsmaybecreatedinvariouswaysincludingviaaliteralnotationorvia
constructorswhichcreateobjectsandthenexecutecodethatinitializesallorpartofthembyassigninginitialvaluestotheir
properties.Eachconstructorisafunctionthathasapropertynamed"prototype"thatisusedtoimplementprototype
basedinheritanceandsharedproperties.Objectsarecreatedbyusingconstructorsinnewexpressions;forexample,
newDate(2009,11)createsanewDateobject.Invokingaconstructorwithoutusingnewhasconsequencesthatdepend
ontheconstructor.Forexample,Date()producesastringrepresentationofthecurrentdateandtimeratherthananobject.

Everyobjectcreatedbyaconstructorhasanimplicitreference(calledtheobject'sprototype)tothevalueofitsconstructor's
"prototype"property.Furthermore,aprototypemayhaveanonnullimplicitreferencetoitsprototype,andsoon;thisis
calledtheprototypechain.Whenareferenceismadetoapropertyinanobject,thatreferenceistothepropertyofthatname
intheirstobjectintheprototypechainthatcontainsapropertyofthatname.Inotherwords,irsttheobjectmentioned
directlyisexaminedforsuchaproperty;ifthatobjectcontainsthenamedproperty,thatisthepropertytowhichthe
referencerefers;ifthatobjectdoesnotcontainthenamedproperty,theprototypeforthatobjectisexaminednext;andsoon.
Figure1:Object/PrototypeRelationships

CF implicitprototypelink
prototype CF p
P1
explicitprototypeproperty
P2 CFP1

cf 1 cf 2 cf 3 cf 4 cf 5

q1 q1 q1 q1 q1
q2 q2 q2 q2 q2

Inaclassbasedobjectorientedlanguage,ingeneral,stateiscarriedbyinstances,methodsarecarriedbyclasses,and
inheritanceisonlyofstructureandbehaviour.InECMAScript,thestateandmethodsarecarriedbyobjects,whilestructure,
behaviour,andstateareallinherited.

Allobjectsthatdonotdirectlycontainaparticularpropertythattheirprototypecontainssharethatpropertyanditsvalue.
Figure1illustratesthis:

CFisaconstructor(andalsoanobject).Fiveobjectshavebeencreatedbyusingnewexpressions:cf1,cf2,cf3,cf4,andcf5.
Eachoftheseobjectscontainspropertiesnamedq1andq2.Thedashedlinesrepresenttheimplicitprototyperelationship;
so,forexample,cf3'sprototypeisCFp.Theconstructor,CF,hastwopropertiesitself,namedP1andP2,whicharenotvisible
toCFp,cf1,cf2,cf3,cf4,orcf5.ThepropertynamedCFP1inCFpissharedbycf1,cf2,cf3,cf4,andcf5(butnotbyCF),asare
anypropertiesfoundinCFp'simplicitprototypechainthatarenotnamedq1,q2,orCFP1.Noticethatthereisnoimplicit
prototypelinkbetweenCFandCFp.

Unlikemostclassbasedobjectlanguages,propertiescanbeaddedtoobjectsdynamicallybyassigningvaluestothem.That
is,constructorsarenotrequiredtonameorassignvaluestoalloranyoftheconstructedobject'sproperties.Intheabove
diagram,onecouldaddanewsharedpropertyforcf1,cf2,cf3,cf4,andcf5byassigninganewvaluetothepropertyinCFp.

AlthoughECMAScriptobjectsarenotinherentlyclassbased,itisoftenconvenienttodeineclasslikeabstractionsbased
uponacommonpatternofconstructorfunctions,prototypeobjects,andmethods.TheECMAScriptbuiltinobjects
themselvesfollowsuchaclasslikepattern.BeginningwithECMAScript2015,theECMAScriptlanguageincludessyntactic
classdeinitionsthatpermitprogrammerstoconciselydeineobjectsthatconformtothesameclasslikeabstractionpattern
usedbythebuiltinobjects.

4.2.2 TheStrictVariantofECMAScript

TheECMAScriptLanguagerecognizesthepossibilitythatsomeusersofthelanguagemaywishtorestricttheirusageofsome
featuresavailableinthelanguage.Theymightdosointheinterestsofsecurity,toavoidwhattheyconsidertobeerrorprone
features,togetenhancederrorchecking,orforotherreasonsoftheirchoosing.Insupportofthispossibility,ECMAScript
deinesastrictvariantofthelanguage.Thestrictvariantofthelanguageexcludessomespeciicsyntacticandsemantic
featuresoftheregularECMAScriptlanguageandmodiiesthedetailedsemanticsofsomefeatures.Thestrictvariantalso
speciiesadditionalerrorconditionsthatmustbereportedbythrowingerrorexceptionsinsituationsthatarenotspeciied
aserrorsbythenonstrictformofthelanguage.

ThestrictvariantofECMAScriptiscommonlyreferredtoasthestrictmodeofthelanguage.Strictmodeselectionanduseof
thestrictmodesyntaxandsemanticsofECMAScriptisexplicitlymadeatthelevelofindividualECMAScriptsourcetextunits.
Becausestrictmodeisselectedatthelevelofasyntacticsourcetextunit,strictmodeonlyimposesrestrictionsthathave
localeffectwithinsuchasourcetextunit.StrictmodedoesnotrestrictormodifyanyaspectoftheECMAScriptsemantics
thatmustoperateconsistentlyacrossmultiplesourcetextunits.AcompleteECMAScriptprogrammaybecomposedofboth
strictmodeandnonstrictmodeECMAScriptsourcetextunits.Inthiscase,strictmodeonlyapplieswhenactuallyexecuting
codethatisdeinedwithinastrictmodesourcetextunit.

Inordertoconformtothisspeciication,anECMAScriptimplementationmustimplementboththefullunrestricted
ECMAScriptlanguageandthestrictvariantoftheECMAScriptlanguageasdeinedbythisspeciication.Inaddition,an
implementationmustsupportthecombinationofunrestrictedandstrictmodesourcetextunitsintoasinglecomposite
program.

4.3 TermsandDeinitions
Forthepurposesofthisdocument,thefollowingtermsanddeinitionsapply.

4.3.1 type

setofdatavaluesasdeinedinclause6ofthisspeciication

4.3.2 primitivevalue

memberofoneofthetypesUndeined,Null,Boolean,Number,Symbol,orStringasdeinedinclause6

NOTE Aprimitivevalueisadatumthatisrepresenteddirectlyatthelowestlevelofthelanguageimplementation.

4.3.3 object

memberofthetypeObject

NOTE Anobjectisacollectionofpropertiesandhasasingleprototypeobject.Theprototypemaybethenullvalue.

4.3.4 constructor

functionobjectthatcreatesandinitializesobjects

NOTE Thevalueofaconstructor'sprototypepropertyisaprototypeobjectthatisusedtoimplementinheritance
andsharedproperties.

4.3.5 prototype

objectthatprovidessharedpropertiesforotherobjects

NOTE Whenaconstructorcreatesanobject,thatobjectimplicitlyreferencestheconstructor'sprototypeproperty
forthepurposeofresolvingpropertyreferences.Theconstructor'sprototypepropertycanbereferencedby
theprogramexpressionconstructor.prototype,andpropertiesaddedtoanobject'sprototypeareshared,
throughinheritance,byallobjectssharingtheprototype.Alternatively,anewobjectmaybecreatedwithan
explicitlyspeciiedprototypebyusingtheObject.createbuiltinfunction.

4.3.6 ordinaryobject

objectthathasthedefaultbehaviourfortheessentialinternalmethodsthatmustbesupportedbyallobjects

4.3.7 exoticobject

objectthatdoesnothavethedefaultbehaviourforoneormoreoftheessentialinternalmethods

NOTE Anyobjectthatisnotanordinaryobjectisanexoticobject.

4.3.8 standardobject

objectwhosesemanticsaredeinedbythisspeciication
4.3.9 builtinobject

objectspeciiedandsuppliedbyanECMAScriptimplementation

NOTE Standardbuiltinobjectsaredeinedinthisspeciication.AnECMAScriptimplementationmayspecifyand
supplyadditionalkindsofbuiltinobjects.Abuiltinconstructorisabuiltinobjectthatisalsoaconstructor.

4.3.10 undeinedvalue

primitivevalueusedwhenavariablehasnotbeenassignedavalue

4.3.11 Undeinedtype

typewhosesolevalueistheundeinedvalue

4.3.12 nullvalue

primitivevaluethatrepresentstheintentionalabsenceofanyobjectvalue

4.3.13 Nulltype

typewhosesolevalueisthenullvalue

4.3.14 Booleanvalue

memberoftheBooleantype

NOTE ThereareonlytwoBooleanvalues,trueandfalse

4.3.15 Booleantype

typeconsistingoftheprimitivevaluestrueandfalse

4.3.16 Booleanobject

memberoftheObjecttypethatisaninstanceofthestandardbuiltinBooleanconstructor

NOTE ABooleanobjectiscreatedbyusingtheBooleanconstructorinanewexpression,supplyingaBooleanvalue
asanargument.TheresultingobjecthasaninternalslotwhosevalueistheBooleanvalue.ABooleanobject
canbecoercedtoaBooleanvalue.

4.3.17 Stringvalue

primitivevaluethatisainiteorderedsequenceofzeroormore16bitunsignedinteger

NOTE AStringvalueisamemberoftheStringtype.Eachintegervalueinthesequenceusuallyrepresentsasingle16
bitunitofUTF16text.However,ECMAScriptdoesnotplaceanyrestrictionsorrequirementsonthevalues
exceptthattheymustbe16bitunsignedintegers.

4.3.18 Stringtype

setofallpossibleStringvalues

4.3.19 Stringobject

memberoftheObjecttypethatisaninstanceofthestandardbuiltinStringconstructor

NOTE AStringobjectiscreatedbyusingtheStringconstructorinanewexpression,supplyingaStringvalueasan
argument.TheresultingobjecthasaninternalslotwhosevalueistheStringvalue.AStringobjectcanbe
coercedtoaStringvaluebycallingtheStringconstructorasafunction(21.1.1.1).
4.3.20 Numbervalue

primitivevaluecorrespondingtoadoubleprecision64bitbinaryformatIEEE7542008value

NOTE ANumbervalueisamemberoftheNumbertypeandisadirectrepresentationofanumber.

4.3.21 Numbertype

setofallpossibleNumbervaluesincludingthespecialNotaNumber(NaN)value,positiveininity,andnegativeininity

4.3.22 Numberobject

memberoftheObjecttypethatisaninstanceofthestandardbuiltinNumberconstructor

NOTE ANumberobjectiscreatedbyusingtheNumberconstructorinanewexpression,supplyinganumbervalueas
anargument.Theresultingobjecthasaninternalslotwhosevalueisthenumbervalue.ANumberobjectcan
becoercedtoanumbervaluebycallingtheNumberconstructorasafunction(20.1.1.1).

4.3.23 Ininity

numbervaluethatisthepositiveininitenumbervalue

4.3.24 NaN

numbervaluethatisanIEEE7542008NotaNumbervalue

4.3.25 Symbolvalue

primitivevaluethatrepresentsaunique,nonStringObjectpropertykey

4.3.26 Symboltype

setofallpossibleSymbolvalues

4.3.27 Symbolobject

memberoftheObjecttypethatisaninstanceofthestandardbuiltinSymbolconstructor

4.3.28 function

memberoftheObjecttypethatmaybeinvokedasasubroutine

NOTE Inadditiontoitsproperties,afunctioncontainsexecutablecodeandstatethatdeterminehowitbehaveswhen
invoked.Afunction'scodemayormaynotbewritteninECMAScript.

4.3.29 builtinfunction

builtinobjectthatisafunction

NOTE ExamplesofbuiltinfunctionsincludeparseIntandMath.exp.Animplementationmayprovide
implementationdependentbuiltinfunctionsthatarenotdescribedinthisspeciication.

4.3.30 property

partofanobjectthatassociatesakey(eitheraStringvalueoraSymbolvalue)andavalue

NOTE Dependingupontheformofthepropertythevaluemayberepresentedeitherdirectlyasadatavalue(a
primitivevalue,anobject,orafunctionobject)orindirectlybyapairofaccessorfunctions.

4.3.31 method
functionthatisthevalueofaproperty

NOTE Whenafunctioniscalledasamethodofanobject,theobjectispassedtothefunctionasitsthisvalue.

4.3.32 builtinmethod

methodthatisabuiltinfunction

NOTE Standardbuiltinmethodsaredeinedinthisspeciication,andanECMAScriptimplementationmayspecify
andprovideotheradditionalbuiltinmethods.

4.3.33 attribute

internalvaluethatdeinessomecharacteristicofaproperty

4.3.34 ownproperty

propertythatisdirectlycontainedbyitsobject

4.3.35 inheritedproperty

propertyofanobjectthatisnotanownpropertybutisaproperty(eitherownorinherited)oftheobject'sprototype

4.4 OrganizationofThisSpeciication
Theremainderofthisspeciicationisorganizedasfollows:

Clause5deinesthenotationalconventionsusedthroughoutthespeciication.

Clauses69deinetheexecutionenvironmentwithinwhichECMAScriptprogramsoperate.

Clauses1016deinetheactualECMAScriptprogramminglanguageincludingitssyntacticencodingandtheexecution
semanticsofalllanguagefeatures.

Clauses1726deinetheECMAScriptstandardlibrary.Itincludesthedeinitionsofallofthestandardobjectsthatare
availableforusebyECMAScriptprogramsastheyexecute.

5 NotationalConventions
5.1 SyntacticandLexicalGrammars
5.1.1 ContextFreeGrammars

Acontextfreegrammarconsistsofanumberofproductions.Eachproductionhasanabstractsymbolcalledanonterminalas
itslefthandside,andasequenceofzeroormorenonterminalandterminalsymbolsasitsrighthandside.Foreachgrammar,
theterminalsymbolsaredrawnfromaspeciiedalphabet.

Achainproductionisaproductionthathasexactlyonenonterminalsymbolonitsrighthandsidealongwithzeroormore
terminalsymbols.

Startingfromasentenceconsistingofasingledistinguishednonterminal,calledthegoalsymbol,agivencontextfree
grammarspeciiesalanguage,namely,the(perhapsininite)setofpossiblesequencesofterminalsymbolsthatcanresult
fromrepeatedlyreplacinganynonterminalinthesequencewitharighthandsideofaproductionforwhichthenonterminal
isthelefthandside.

5.1.2 TheLexicalandRegExpGrammars
AlexicalgrammarforECMAScriptisgiveninclause11.ThisgrammarhasasitsterminalsymbolsUnicodecodepointsthat
conformtotherulesforSourceCharacterdeinedin10.1.Itdeinesasetofproductions,startingfromthegoalsymbol
InputElementDiv,InputElementTemplateTail,orInputElementRegExp,orInputElementRegExpOrTemplateTail,thatdescribe
howsequencesofsuchcodepointsaretranslatedintoasequenceofinputelements.

InputelementsotherthanwhitespaceandcommentsformtheterminalsymbolsforthesyntacticgrammarforECMAScript
andarecalledECMAScripttokens.Thesetokensarethereservedwords,identiiers,literals,andpunctuatorsofthe
ECMAScriptlanguage.Moreover,lineterminators,althoughnotconsideredtobetokens,alsobecomepartofthestreamof
inputelementsandguidetheprocessofautomaticsemicoloninsertion(11.9).Simplewhitespaceandsinglelinecomments
arediscardedanddonotappearinthestreamofinputelementsforthesyntacticgrammar.AMultiLineComment(thatis,a
commentoftheform/**/regardlessofwhetheritspansmorethanoneline)islikewisesimplydiscardedifitcontainsno
lineterminator;butifaMultiLineCommentcontainsoneormorelineterminators,thenitisreplacedbyasingleline
terminator,whichbecomespartofthestreamofinputelementsforthesyntacticgrammar.

ARegExpgrammarforECMAScriptisgivenin21.2.1.Thisgrammaralsohasasitsterminalsymbolsthecodepointsas
deinedbySourceCharacter.Itdeinesasetofproductions,startingfromthegoalsymbolPattern,thatdescribehow
sequencesofcodepointsaretranslatedintoregularexpressionpatterns.

ProductionsofthelexicalandRegExpgrammarsaredistinguishedbyhavingtwocolons::asseparatingpunctuation.The
lexicalandRegExpgrammarssharesomeproductions.

5.1.3 TheNumericStringGrammar

AnothergrammarisusedfortranslatingStringsintonumericvalues.Thisgrammarissimilartothepartofthelexical
grammarhavingtodowithnumericliteralsandhasasitsterminalsymbolsSourceCharacter.Thisgrammarappearsin
7.1.3.1.

Productionsofthenumericstringgrammararedistinguishedbyhavingthreecolons:::aspunctuation.

5.1.4 TheSyntacticGrammar

ThesyntacticgrammarforECMAScriptisgiveninclauses11,12,13,14,and15.ThisgrammarhasECMAScripttokens
deinedbythelexicalgrammarasitsterminalsymbols(5.1.2).Itdeinesasetofproductions,startingfromtwoalternative
goalsymbolsScriptandModule,thatdescribehowsequencesoftokensformsyntacticallycorrectindependentcomponents
ofECMAScriptprograms.

WhenastreamofcodepointsistobeparsedasanECMAScriptScriptorModule,itisirstconvertedtoastreamofinput
elementsbyrepeatedapplicationofthelexicalgrammar;thisstreamofinputelementsisthenparsedbyasingleapplication
ofthesyntacticgrammar.Theinputstreamissyntacticallyinerrorifthetokensinthestreamofinputelementscannotbe
parsedasasingleinstanceofthegoalnonterminal(ScriptorModule),withnotokensleftover.

Productionsofthesyntacticgrammararedistinguishedbyhavingjustonecolon:aspunctuation.

Thesyntacticgrammaraspresentedinclauses12,13,14and15isnotacompleteaccountofwhichtokensequencesare
acceptedasacorrectECMAScriptScriptorModule.Certainadditionaltokensequencesarealsoaccepted,namely,thosethat
wouldbedescribedbythegrammarifonlysemicolonswereaddedtothesequenceincertainplaces(suchasbeforeline
terminatorcharacters).Furthermore,certaintokensequencesthataredescribedbythegrammararenotconsidered
acceptableifalineterminatorcharacterappearsincertainawkwardplaces.

Incertaincasesinordertoavoidambiguitiesthesyntacticgrammarusesgeneralizedproductionsthatpermittoken
sequencesthatdonotformavalidECMAScriptScriptorModule.Forexample,thistechniqueisusedforobjectliteralsand
objectdestructuringpatterns.Insuchcasesamorerestrictivesupplementalgrammarisprovidedthatfurtherrestrictsthe
acceptabletokensequences.Incertaincontexts,whenexplicitlyspeciied,theinputelementscorrespondingtosucha
productionareparsedagainusingagoalsymbolofasupplementalgrammar.Theinputstreamissyntacticallyinerrorifthe
tokensinthestreamofinputelementsparsedbyacovergrammarcannotbeparsedasasingleinstanceofthe
correspondingsupplementalgoalsymbol,withnotokensleftover.
5.1.5 GrammarNotation

Terminalsymbolsofthelexical,RegExp,andnumericstringgrammarsareshowninfixedwidthfont,bothinthe
productionsofthegrammarsandthroughoutthisspeciicationwheneverthetextdirectlyreferstosuchaterminalsymbol.
Thesearetoappearinascriptexactlyaswritten.Allterminalsymbolcodepointsspeciiedinthiswayaretobeunderstood
astheappropriateUnicodecodepointsfromtheBasicLatinrange,asopposedtoanysimilarlookingcodepointsfromother
Unicoderanges.

Nonterminalsymbolsareshowninitalictype.Thedeinitionofanonterminal(alsocalledaproduction)isintroducedby
thenameofthenonterminalbeingdeinedfollowedbyoneormorecolons.(Thenumberofcolonsindicatestowhich
grammartheproductionbelongs.)Oneormorealternativerighthandsidesforthenonterminalthenfollowonsucceeding
lines.Forexample,thesyntacticdeinition:

WhileStatement :
while ( Expression ) Statement

statesthatthenonterminalWhileStatementrepresentsthetokenwhile,followedbyaleftparenthesistoken,followedbyan
Expression,followedbyarightparenthesistoken,followedbyaStatement.TheoccurrencesofExpressionandStatementare
themselvesnonterminals.Asanotherexample,thesyntacticdeinition:

ArgumentList :
AssignmentExpression
ArgumentList , AssignmentExpression

statesthatanArgumentListmayrepresenteitherasingleAssignmentExpressionoranArgumentList,followedbyacomma,
followedbyanAssignmentExpression.ThisdeinitionofArgumentListisrecursive,thatis,itisdeinedintermsofitself.The
resultisthatanArgumentListmaycontainanypositivenumberofarguments,separatedbycommas,whereeachargument
expressionisanAssignmentExpression.Suchrecursivedeinitionsofnonterminalsarecommon.

Thesubscriptedsufixopt,whichmayappearafteraterminalornonterminal,indicatesanoptionalsymbol.Thealternative
containingtheoptionalsymbolactuallyspeciiestworighthandsides,onethatomitstheoptionalelementandonethat
includesit.Thismeansthat:

VariableDeclaration :
BindingIdentiier Initializeropt

isaconvenientabbreviationfor:

VariableDeclaration :
BindingIdentiier
BindingIdentiier Initializer

andthat:

IterationStatement :
for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

isaconvenientabbreviationfor:

IterationStatement :
for ( LexicalDeclaration ; Expressionopt ) Statement
for ( LexicalDeclaration Expression ; Expressionopt ) Statement

whichinturnisanabbreviationfor:

IterationStatement :
for ( LexicalDeclaration ; ) Statement
for ( LexicalDeclaration ; Expression ) Statement
for ( LexicalDeclaration Expression ; ) Statement
for ( LexicalDeclaration Expression ; Expression ) Statement

so,inthisexample,thenonterminalIterationStatementactuallyhasfouralternativerighthandsides.

Aproductionmaybeparameterizedbyasubscriptedannotationoftheform[parameters],whichmayappearasasufixto
thenonterminalsymboldeinedbytheproduction.parametersmaybeeitherasinglenameoracommaseparatedlistof
names.Aparameterizedproductionisshorthandforasetofproductionsdeiningallcombinationsoftheparameternames,
precededbyanunderscore,appendedtotheparameterizednonterminalsymbol.Thismeansthat:

StatementList[Return] :
ReturnStatement
ExpressionStatement

isaconvenientabbreviationfor:

StatementList :
ReturnStatement
ExpressionStatement

StatementList_Return :
ReturnStatement
ExpressionStatement

andthat:

StatementList[Return,In] :
ReturnStatement
ExpressionStatement

isanabbreviationfor:

StatementList :
ReturnStatement
ExpressionStatement

StatementList_Return :
ReturnStatement
ExpressionStatement

StatementList_In :
ReturnStatement
ExpressionStatement

StatementList_Return_In :
ReturnStatement
ExpressionStatement

Multipleparametersproduceacombinatorynumberofproductions,notallofwhicharenecessarilyreferencedinacomplete
grammar.

Referencestononterminalsontherighthandsideofaproductioncanalsobeparameterized.Forexample:

StatementList :
ReturnStatement
ExpressionStatement[In]

isequivalenttosaying:
StatementList :
ReturnStatement
ExpressionStatement_In

Anonterminalreferencemayhavebothaparameterlistandanoptsufix.Forexample:

VariableDeclaration :
BindingIdentiier Initializer[In] opt

isanabbreviationfor:

VariableDeclaration :
BindingIdentiier
BindingIdentiier Initializer_In

Preixingaparameternamewith?onarighthandsidenonterminalreferencemakesthatparametervaluedependentupon
theoccurrenceoftheparameternameonthereferencetothecurrentproduction'slefthandsidesymbol.Forexample:

VariableDeclaration[In] :
BindingIdentiier Initializer[?In]

isanabbreviationfor:

VariableDeclaration :
BindingIdentiier Initializer

VariableDeclaration_In :
BindingIdentiier Initializer_In

Ifarighthandsidealternativeispreixedwith[+parameter]thatalternativeisonlyavailableifthenamedparameterwas
usedinreferencingtheproduction'snonterminalsymbol.Ifarighthandsidealternativeispreixedwith[~parameter]that
alternativeisonlyavailableifthenamedparameterwasnotusedinreferencingtheproduction'snonterminalsymbol.This
meansthat:

StatementList[Return] :
[+Return] ReturnStatement
ExpressionStatement

isanabbreviationfor:

StatementList :
ExpressionStatement

StatementList_Return :
ReturnStatement
ExpressionStatement

andthat

StatementList[Return] :
ReturnStatement
[~Return]
ExpressionStatement

isanabbreviationfor:

StatementList :
ReturnStatement
ExpressionStatement
StatementList_Return :
ExpressionStatement

Whenthewordsoneoffollowthecolon(s)inagrammardeinition,theysignifythateachoftheterminalsymbolsonthe
followinglineorlinesisanalternativedeinition.Forexample,thelexicalgrammarforECMAScriptcontainstheproduction:

NonZeroDigit :: oneof
1 2 3 4 5 6 7 8 9

whichismerelyaconvenientabbreviationfor:

NonZeroDigit ::
1
2
3
4
5
6
7
8
9

Ifthephrase[empty]appearsastherighthandsideofaproduction,itindicatesthattheproduction'srighthandside
containsnoterminalsornonterminals.

Ifthephrase[lookaheadset]appearsintherighthandsideofaproduction,itindicatesthattheproductionmaynotbe
usediftheimmediatelyfollowinginputtokensequenceisamemberofthegivenset.Thesetcanbewrittenasacomma
separatedlistofoneortwoelementterminalsequencesenclosedincurlybrackets.Forconvenience,thesetcanalsobe
writtenasanonterminal,inwhichcaseitrepresentsthesetofallterminalstowhichthatnonterminalcouldexpand.Ifthe
setconsistsofasingleterminalthephrase[lookaheadterminal]maybeused.

Forexample,giventhedeinitions

DecimalDigit :: oneof
0 1 2 3 4 5 6 7 8 9

DecimalDigits ::
DecimalDigit
DecimalDigits DecimalDigit

thedeinition

LookaheadExample ::
n [lookahead{1 ,3 ,5 ,7 ,9}] DecimalDigits
DecimalDigit [lookaheadDecimalDigit]

matcheseithertheletternfollowedbyoneormoredecimaldigitstheirstofwhichiseven,oradecimaldigitnotfollowed
byanotherdecimaldigit.

Ifthephrase[noLineTerminatorhere]appearsintherighthandsideofaproductionofthesyntacticgrammar,itindicates
thattheproductionisarestrictedproduction:itmaynotbeusedifaLineTerminatoroccursintheinputstreamatthe
indicatedposition.Forexample,theproduction:

ThrowStatement :
throw [noLineTerminatorhere] Expression ;

indicatesthattheproductionmaynotbeusedifaLineTerminatoroccursinthescriptbetweenthethrowtokenandthe
Expression.
UnlessthepresenceofaLineTerminatorisforbiddenbyarestrictedproduction,anynumberofoccurrencesof
LineTerminatormayappearbetweenanytwoconsecutivetokensinthestreamofinputelementswithoutaffectingthe
syntacticacceptabilityofthescript.

Whenanalternativeinaproductionofthelexicalgrammarorthenumericstringgrammarappearstobeamulticodepoint
token,itrepresentsthesequenceofcodepointsthatwouldmakeupsuchatoken.

Therighthandsideofaproductionmayspecifythatcertainexpansionsarenotpermittedbyusingthephrasebutnotand
thenindicatingtheexpansionstobeexcluded.Forexample,theproduction:

Identiier ::
IdentiierName butnotReservedWord

meansthatthenonterminalIdentiiermaybereplacedbyanysequenceofcodepointsthatcouldreplaceIdentiierName
providedthatthesamesequenceofcodepointscouldnotreplaceReservedWord.

Finally,afewnonterminalsymbolsaredescribedbyadescriptivephraseinsansseriftypeincaseswhereitwouldbe
impracticaltolistallthealternatives:

SourceCharacter ::
anyUnicodecodepoint

5.2 AlgorithmConventions
Thespeciicationoftenusesanumberedlisttospecifystepsinanalgorithm.Thesealgorithmsareusedtopreciselyspecify
therequiredsemanticsofECMAScriptlanguageconstructs.Thealgorithmsarenotintendedtoimplytheuseofanyspeciic
implementationtechnique.Inpractice,theremaybemoreeficientalgorithmsavailabletoimplementagivenfeature.

Algorithmsmaybeexplicitlyparameterized,inwhichcasethenamesandusageoftheparametersmustbeprovidedaspart
ofthealgorithm'sdeinition.Inordertofacilitatetheiruseinmultiplepartsofthisspeciication,somealgorithms,called
abstractoperations,arenamedandwritteninparameterizedfunctionalformsothattheymaybereferencedbynamefrom
withinotheralgorithms.Abstractoperationsaretypicallyreferencedusingafunctionalapplicationstylesuchas
operationName(arg1,arg2).Someabstractoperationsaretreatedaspolymorphicallydispatchedmethodsofclasslike
speciicationabstractions.Suchmethodlikeabstractoperationsaretypicallyreferencedusingamethodapplicationstyle
suchassomeValue.operationName(arg1,arg2).

CallstoabstractoperationsreturnCompletionRecords.Abstractoperationsreferencedusingthefunctionalapplicationstyle
andthemethodapplicationstylethatarepreixedby?indicatethatReturnIfAbruptshouldbeappliedtotheresulting
CompletionRecord.Forexample,?operationName()isequivalenttoReturnIfAbrupt(operationName()).Similarly,?
someValue.operationName()isequivalenttoReturnIfAbrupt(someValue.operationName()).

Thepreix!isusedtoindicatethatanabstractoperationwillneverreturnanabruptcompletionandthattheresulting
CompletionRecord'svalueieldshouldbeusedinplaceofthereturnvalueoftheoperation.Forexample,Letvalbe!
operationName()isequivalenttothefollowingalgorithmsteps:

1.LetvalbeoperationName().
2.Assert:valisneveranabruptcompletion.
3.IfvalisaCompletionRecord,letvalbeval.[[Value]].

AlgorithmsmaybeassociatedwithproductionsofoneoftheECMAScriptgrammars.Aproductionthathasmultiple
alternativedeinitionswilltypicallyhaveadistinctalgorithmforeachalternative.Whenanalgorithmisassociatedwitha
grammarproduction,itmayreferencetheterminalandnonterminalsymbolsoftheproductionalternativeasiftheywere
parametersofthealgorithm.Whenusedinthismanner,nonterminalsymbolsrefertotheactualalternativedeinitionthatis
matchedwhenparsingthesourcetext.

Whenanalgorithmisassociatedwithaproductionalternative,thealternativeistypicallyshownwithoutany[]grammar
annotations.Suchannotationsshouldonlyaffectthesyntacticrecognitionofthealternativeandhavenoeffectonthe
associatedsemanticsforthealternative.
Unlessexplicitlyspeciiedotherwise,allchainproductionshaveanimplicitdeinitionforeveryalgorithmthatmightbe
appliedtothatproduction'slefthandsidenonterminal.Theimplicitdeinitionsimplyreappliesthesamealgorithmname
withthesameparameters,ifany,tothechainproduction'ssolerighthandsidenonterminalandthenreturnstheresult.For
example,assumethereisaproduction:

Block :
{ StatementList }

butthereisnocorrespondingEvaluationalgorithmthatisexplicitlyspeciiedforthatproduction.Ifinsomealgorithmthere
isastatementoftheform:ReturntheresultofevaluatingBlockitisimplicitthatanEvaluationalgorithmexistsoftheform:

RuntimeSemantics:Evaluation

Block : { StatementList }

1.ReturntheresultofevaluatingStatementList.

Forclarityofexpression,algorithmstepsmaybesubdividedintosequentialsubsteps.Substepsareindentedandmay
themselvesbefurtherdividedintoindentedsubsteps.Outlinenumberingconventionsareusedtoidentifysubstepswiththe
irstlevelofsubstepslabelledwithlowercasealphabeticcharactersandthesecondlevelofsubstepslabelledwithlower
caseromannumerals.Ifmorethanthreelevelsarerequiredtheserulesrepeatwiththefourthlevelusingnumericlabels.For
example:

1.Toplevelstep
a.Substep.
b.Substep.
i.Subsubstep.
1.Subsubsubstep
a.Subsubsubsubstep
i.Subsubsubsubsubstep

Asteporsubstepmaybewrittenasanifpredicatethatconditionsitssubsteps.Inthiscase,thesubstepsareonlyappliedif
thepredicateistrue.Ifasteporsubstepbeginswiththewordelse,itisapredicatethatisthenegationoftheprecedingif
predicatestepatthesamelevel.

Astepmayspecifytheiterativeapplicationofitssubsteps.

AstepthatbeginswithAssert:assertsaninvariantconditionofitsalgorithm.Suchassertionsareusedtomakeexplicit
algorithmicinvariantsthatwouldotherwisebeimplicit.Suchassertionsaddnoadditionalsemanticrequirementsandhence
neednotbecheckedbyanimplementation.Theyareusedsimplytoclarifyalgorithms.

Mathematicaloperationssuchasaddition,subtraction,negation,multiplication,division,andthemathematicalfunctions
deinedlaterinthisclauseshouldalwaysbeunderstoodascomputingexactmathematicalresultsonmathematicalreal
numbers,whichunlessotherwisenoteddonotincludeininitiesanddonotincludeanegativezerothatisdistinguishedfrom
positivezero.Algorithmsinthisstandardthatmodelloatingpointarithmeticincludeexplicitsteps,wherenecessary,to
handleininitiesandsignedzeroandtoperformrounding.Ifamathematicaloperationorfunctionisappliedtoaloating
pointnumber,itshouldbeunderstoodasbeingappliedtotheexactmathematicalvaluerepresentedbythatloatingpoint
number;suchaloatingpointnumbermustbeinite,andifitis+0or0thenthecorrespondingmathematicalvalueis
simply0.

Themathematicalfunctionabs(x)producestheabsolutevalueofx,whichisxifxisnegative(lessthanzero)andotherwise
isxitself.

Themathematicalfunctionmin(x1,x2,...,xN)producesthemathematicallysmallestofx1throughxN.Themathematical
functionmax(x1,x2,...,xN)producesthemathematicallylargestofx1throughxN.Thedomainandrangeofthese
mathematicalfunctionsinclude+and.
Thenotationxmoduloy(ymustbeiniteandnonzero)computesavaluekofthesamesignasy(orzero)suchthat
abs(k)<abs(y)andxk=qyforsomeintegerq.

Themathematicalfunctionloor(x)producesthelargestinteger(closesttopositiveininity)thatisnotlargerthanx.

NOTE loor(x)=x(xmodulo1).

5.3 StaticSemanticRules
Contextfreegrammarsarenotsuficientlypowerfultoexpressalltherulesthatdeinewhetherastreamofinputelements
formavalidECMAScriptScriptorModulethatmaybeevaluated.Insomesituationsadditionalrulesareneededthatmaybe
expressedusingeitherECMAScriptalgorithmconventionsorproserequirements.Suchrulesarealwaysassociatedwitha
productionofagrammarandarecalledthestaticsemanticsoftheproduction.

StaticSemanticRuleshavenamesandtypicallyaredeinedusinganalgorithm.NamedStaticSemanticRulesareassociated
withgrammarproductionsandaproductionthathasmultiplealternativedeinitionswilltypicallyhaveforeachalternativea
distinctalgorithmforeachapplicablenamedstaticsemanticrule.

Unlessotherwisespeciiedeverygrammarproductionalternativeinthisspeciicationimplicitlyhasadeinitionforastatic
semanticrulenamedContainswhichtakesanargumentnamedsymbolwhosevalueisaterminalornonterminalofthe
grammarthatincludestheassociatedproduction.ThedefaultdeinitionofContainsis:

1.Foreachterminalandnonterminalgrammarsymbol,sym,inthedeinitionofthisproductiondo
a.Ifsymisthesamegrammarsymbolassymbol,returntrue.
b.Ifsymisanonterminal,then
i.LetcontainedbetheresultofsymContainssymbol.
ii.Ifcontainedistrue,returntrue.
2.Returnfalse.

Theabovedeinitionisexplicitlyoverriddenforspeciicproductions.

AspecialkindofstaticsemanticruleisanEarlyErrorRule.Earlyerrorrulesdeineearlyerrorconditions(seeclause16)that
areassociatedwithspeciicgrammarproductions.Evaluationofmostearlyerrorrulesarenotexplicitlyinvokedwithinthe
algorithmsofthisspeciication.Aconformingimplementationmust,priortotheirstevaluationofaScriptorModule,
validatealloftheearlyerrorrulesoftheproductionsusedtoparsethatScriptorModule.Ifanyoftheearlyerrorrulesare
violatedtheScriptorModuleisinvalidandcannotbeevaluated.

6 ECMAScriptDataTypesandValues
Algorithmswithinthisspeciicationmanipulatevalueseachofwhichhasanassociatedtype.Thepossiblevaluetypesare
exactlythosedeinedinthisclause.TypesarefurthersubclassiiedintoECMAScriptlanguagetypesandspeciicationtypes.

Withinthisspeciication,thenotationType(x)isusedasshorthandforthetypeofxwheretypereferstothe
ECMAScriptlanguageandspeciicationtypesdeinedinthisclause.Whenthetermemptyisusedasifitwasnaminga
value,itisequivalenttosayingnovalueofanytype.

6.1 ECMAScriptLanguageTypes
AnECMAScriptlanguagetypecorrespondstovaluesthataredirectlymanipulatedbyanECMAScriptprogrammerusingthe
ECMAScriptlanguage.TheECMAScriptlanguagetypesareUndeined,Null,Boolean,String,Symbol,Number,andObject.An
ECMAScriptlanguagevalueisavaluethatischaracterizedbyanECMAScriptlanguagetype.

6.1.1 TheUndeinedType

TheUndeinedtypehasexactlyonevalue,calledundeined.Anyvariablethathasnotbeenassignedavaluehasthevalue
undeined.
6.1.2 TheNullType

TheNulltypehasexactlyonevalue,callednull.

6.1.3 TheBooleanType

TheBooleantyperepresentsalogicalentityhavingtwovalues,calledtrueandfalse.

6.1.4 TheStringType

TheStringtypeisthesetofallorderedsequencesofzeroormore16bitunsignedintegervalues(elements)uptoa
maximumlengthof2531elements.TheStringtypeisgenerallyusedtorepresenttextualdatainarunningECMAScript
program,inwhichcaseeachelementintheStringistreatedasaUTF16codeunitvalue.Eachelementisregardedas
occupyingapositionwithinthesequence.Thesepositionsareindexedwithnonnegativeintegers.Theirstelement(ifany)is
atindex0,thenextelement(ifany)atindex1,andsoon.ThelengthofaStringisthenumberofelements(i.e.,16bitvalues)
withinit.TheemptyStringhaslengthzeroandthereforecontainsnoelements.

WhereECMAScriptoperationsinterpretStringvalues,eachelementisinterpretedasasingleUTF16codeunit.However,
ECMAScriptdoesnotplaceanyrestrictionsorrequirementsonthesequenceofcodeunitsinaStringvalue,sotheymaybe
illformedwheninterpretedasUTF16codeunitsequences.OperationsthatdonotinterpretStringcontentstreatthemas
sequencesofundifferentiated16bitunsignedintegers.ThefunctionString.prototype.normalize(see21.1.3.12)canbe
usedtoexplicitlynormalizeaStringvalue.String.prototype.localeCompare(see21.1.3.10)internallynormalizes
Stringvalues,butnootheroperationsimplicitlynormalizethestringsuponwhichtheyoperate.Onlyoperationsthatare
explicitlyspeciiedtobelanguageorlocalesensitiveproducelanguagesensitiveresults.

NOTE TherationalebehindthisdesignwastokeeptheimplementationofStringsassimpleandhighperformingas
possible.IfECMAScriptsourcetextisinNormalizedFormC,stringliteralsareguaranteedtoalsobe
normalized,aslongastheydonotcontainanyUnicodeescapesequences.

SomeoperationsinterpretStringcontentsasUTF16encodedUnicodecodepoints.Inthatcasetheinterpretationis:

Acodeunitintherange0to0xD7FForintherange0xE000to0xFFFFisinterpretedasacodepointwiththesame
value.
Asequenceoftwocodeunits,wheretheirstcodeunitc1isintherange0xD800to0xDBFFandthesecondcodeunitc2
isintherange0xDC00to0xDFFF,isasurrogatepairandisinterpretedasacodepointwiththevalue(c10xD800)
0x400+(c20xDC00)+0x10000.(See10.1.2)
Acodeunitthatisintherange0xD800to0xDFFF,butisnotpartofasurrogatepair,isinterpretedasacodepointwith
thesamevalue.

6.1.5 TheSymbolType

TheSymboltypeisthesetofallnonStringvaluesthatmaybeusedasthekeyofanObjectproperty(6.1.7).

EachpossibleSymbolvalueisuniqueandimmutable.

EachSymbolvalueimmutablyholdsanassociatedvaluecalled[[Description]]thatiseitherundeinedoraStringvalue.

6.1.5.1 WellKnownSymbols

WellknownsymbolsarebuiltinSymbolvaluesthatareexplicitlyreferencedbyalgorithmsofthisspeciication.Theyare
typicallyusedasthekeysofpropertieswhosevaluesserveasextensionpointsofaspeciicationalgorithm.Unlessotherwise
speciied,wellknownsymbolsvaluesaresharedbyallrealms(8.2).

Withinthisspeciicationawellknownsymbolisreferredtobyusinganotationoftheform@@name,wherenameisone
ofthevalueslistedinTable1.
Table1:WellknownSymbols
SpeciicationName [[Description]] ValueandPurpose

@@hasInstance "Symbol.hasInstance" Amethodthatdeterminesifaconstructorobjectrecognizes


anobjectasoneoftheconstructor'sinstances.Calledbythe
semanticsoftheinstanceofoperator.

@@isConcatSpreadable "Symbol.isConcatSpreadable" ABooleanvaluedpropertythatiftrueindicatesthatan


objectshouldbelattenedtoitsarrayelementsby
Array.prototype.concat.

@@iterator "Symbol.iterator" AmethodthatreturnsthedefaultIteratorforanobject.


Calledbythesemanticsoftheforofstatement.

@@match "Symbol.match" Aregularexpressionmethodthatmatchestheregular


expressionagainstastring.Calledbythe
String.prototype.matchmethod.

@@replace "Symbol.replace" Aregularexpressionmethodthatreplacesmatched


substringsofastring.Calledbythe
String.prototype.replacemethod.

@@search "Symbol.search" Aregularexpressionmethodthatreturnstheindexwithina


stringthatmatchestheregularexpression.Calledbythe
String.prototype.searchmethod.

@@species "Symbol.species" Afunctionvaluedpropertythatistheconstructorfunction


thatisusedtocreatederivedobjects.

@@split "Symbol.split" Aregularexpressionmethodthatsplitsastringatthe


indicesthatmatchtheregularexpression.Calledbythe
String.prototype.splitmethod.

@@toPrimitive "Symbol.toPrimitive" Amethodthatconvertsanobjecttoacorresponding


primitivevalue.CalledbytheToPrimitiveabstract
operation.

@@toStringTag "Symbol.toStringTag" AStringvaluedpropertythatisusedinthecreationofthe


defaultstringdescriptionofanobject.Accessedbythe
builtinmethodObject.prototype.toString.

@@unscopables "Symbol.unscopables" Anobjectvaluedpropertywhoseownandinherited


propertynamesarepropertynamesthatareexcludedfrom
thewithenvironmentbindingsoftheassociatedobject.

6.1.6 TheNumberType

TheNumbertypehasexactly18437736874454810627(thatis,264253+3)values,representingthedoubleprecision64bit
formatIEEE7542008valuesasspeciiedintheIEEEStandardforBinaryFloatingPointArithmetic,exceptthatthe
9007199254740990(thatis,2532)distinctNotaNumbervaluesoftheIEEEStandardarerepresentedinECMAScriptasa
singlespecialNaNvalue.(NotethattheNaNvalueisproducedbytheprogramexpressionNaN.)Insomeimplementations,
externalcodemightbeabletodetectadifferencebetweenvariousNotaNumbervalues,butsuchbehaviouris
implementationdependent;toECMAScriptcode,allNaNvaluesareindistinguishablefromeachother.

NOTE ThebitpatternthatmightbeobservedinanArrayBuffer(see24.1)afteraNumbervaluehasbeenstoredinto
itisnotnecessarilythesameastheinternalrepresentationofthatNumbervalueusedbytheECMAScript
implementation.
Therearetwootherspecialvalues,calledpositiveIninityandnegativeIninity.Forbrevity,thesevaluesarealsoreferred
toforexpositorypurposesbythesymbols+and,respectively.(NotethatthesetwoininiteNumbervaluesare
producedbytheprogramexpressions+Infinity(orsimplyInfinity)andInfinity.)

Theother18437736874454810624(thatis,264253)valuesarecalledtheinitenumbers.Halfofthesearepositivenumbers
andhalfarenegativenumbers;foreveryinitepositiveNumbervaluethereisacorrespondingnegativevaluehavingthe
samemagnitude.

Notethatthereisbothapositivezeroandanegativezero.Forbrevity,thesevaluesarealsoreferredtoforexpository
purposesbythesymbols+0and0,respectively.(NotethatthesetwodifferentzeroNumbervaluesareproducedbythe
programexpressions+0(orsimply0)and0.)

The18437736874454810622(thatis,2642532)initenonzerovaluesareoftwokinds:

18428729675200069632(thatis,264254)ofthemarenormalized,havingtheform

sm2e

wheresis+1or1,misapositiveintegerlessthan253butnotlessthan252,andeisanintegerrangingfrom1074to971,
inclusive.

Theremaining9007199254740990(thatis,2532)valuesaredenormalized,havingtheform

sm2e

wheresis+1or1,misapositiveintegerlessthan252,andeis1074.

Notethatallthepositiveandnegativeintegerswhosemagnitudeisnogreaterthan253arerepresentableintheNumbertype
(indeed,theinteger0hastworepresentations,+0and0).

Ainitenumberhasanoddsigniicandifitisnonzeroandtheintegermusedtoexpressit(inoneofthetwoformsshown
above)isodd.Otherwise,ithasanevensigniicand.

Inthisspeciication,thephrasetheNumbervalueforxwherexrepresentsanexactnonzerorealmathematicalquantity
(whichmightevenbeanirrationalnumbersuchas)meansaNumbervaluechoseninthefollowingmanner.Considerthe
setofallinitevaluesoftheNumbertype,with0removedandwithtwoadditionalvaluesaddedtoitthatarenot
representableintheNumbertype,namely21024(whichis+12532971)and21024(whichis12532971).Choosethe
memberofthissetthatisclosestinvaluetox.Iftwovaluesofthesetareequallyclose,thentheonewithanevensigniicand
ischosen;forthispurpose,thetwoextravalues21024and21024areconsideredtohaveevensigniicands.Finally,if21024
waschosen,replaceitwith+;if21024waschosen,replaceitwith;if+0waschosen,replaceitwith0ifandonlyifxis
lessthanzero;anyotherchosenvalueisusedunchanged.TheresultistheNumbervalueforx.(Thisprocedurecorresponds
exactlytothebehaviouroftheIEEE7542008roundtonearest,tiestoevenmode.)

SomeECMAScriptoperatorsdealonlywithintegersinspeciicrangessuchas231through2311,inclusive,orintherange0
through2161,inclusive.TheseoperatorsacceptanyvalueoftheNumbertypebutirstconverteachsuchvaluetoaninteger
valueintheexpectedrange.Seethedescriptionsofthenumericconversionoperationsin7.1.

6.1.7 TheObjectType

AnObjectislogicallyacollectionofproperties.Eachpropertyiseitheradataproperty,oranaccessorproperty:

AdatapropertyassociatesakeyvaluewithanECMAScriptlanguagevalueandasetofBooleanattributes.
Anaccessorpropertyassociatesakeyvaluewithoneortwoaccessorfunctions,andasetofBooleanattributes.The
accessorfunctionsareusedtostoreorretrieveanECMAScriptlanguagevaluethatisassociatedwiththeproperty.

Propertiesareidentiiedusingkeyvalues.ApropertykeyvalueiseitheranECMAScriptStringvalueoraSymbolvalue.All
StringandSymbolvalues,includingtheemptystring,arevalidaspropertykeys.Apropertynameisapropertykeythatisa
Stringvalue.
AnintegerindexisaStringvaluedpropertykeythatisacanonicalnumericString(see7.1.16)andwhosenumericvalueis
either+0orapositiveinteger2531.Anarrayindexisanintegerindexwhosenumericvalueiisintherange+0i<2321.

Propertykeysareusedtoaccesspropertiesandtheirvalues.Therearetwokindsofaccessforproperties:getandset,
correspondingtovalueretrievalandassignment,respectively.Thepropertiesaccessibleviagetandsetaccessincludesboth
ownpropertiesthatareadirectpartofanobjectandinheritedpropertieswhichareprovidedbyanotherassociatedobjectvia
apropertyinheritancerelationship.Inheritedpropertiesmaybeeitherownorinheritedpropertiesoftheassociatedobject.
Eachownpropertyofanobjectmusteachhaveakeyvaluethatisdistinctfromthekeyvaluesoftheotherownpropertiesof
thatobject.

Allobjectsarelogicallycollectionsofproperties,buttherearemultipleformsofobjectsthatdifferintheirsemanticsfor
accessingandmanipulatingtheirproperties.Ordinaryobjectsarethemostcommonformofobjectsandhavethedefault
objectsemantics.Anexoticobjectisanyformofobjectwhosepropertysemanticsdifferinanywayfromthedefault
semantics.

6.1.7.1 PropertyAttributes

AttributesareusedinthisspeciicationtodeineandexplainthestateofObjectproperties.Adatapropertyassociatesakey
valuewiththeattributeslistedinTable2.

Table2:AttributesofaDataProperty
Attribute Value Description
Name Domain

[[Value]] Any Thevalueretrievedbyagetaccessoftheproperty.


ECMAScript
languagetype

[[Writable]] Boolean Iffalse,attemptsbyECMAScriptcodetochangetheproperty's[[Value]]attributeusing


[[Set]]willnotsucceed.

[[Enumerable]] Boolean Iftrue,thepropertywillbeenumeratedbyaforinenumeration(see13.7.5).


Otherwise,thepropertyissaidtobenonenumerable.

[[Conigurable]] Boolean Iffalse,attemptstodeletetheproperty,changethepropertytobeanaccessorproperty,


orchangeitsattributes(otherthan[[Value]],orchanging[[Writable]]tofalse)willfail.

AnaccessorpropertyassociatesakeyvaluewiththeattributeslistedinTable3.
Table3:AttributesofanAccessorProperty
Attribute Value Description
Name Domain

[[Get]] Object| IfthevalueisanObjectitmustbeafunctionobject.Thefunction's[[Call]]internalmethod


Undeined (Table6)iscalledwithanemptyargumentslisttoretrievethepropertyvalueeachtimea
getaccessofthepropertyisperformed.

[[Set]] Object| IfthevalueisanObjectitmustbeafunctionobject.Thefunction's[[Call]]internalmethod


Undeined (Table6)iscalledwithanargumentslistcontainingtheassignedvalueasitssoleargument
eachtimeasetaccessofthepropertyisperformed.Theeffectofaproperty's[[Set]]internal
methodmay,butisnotrequiredto,haveaneffectonthevaluereturnedbysubsequentcalls
totheproperty's[[Get]]internalmethod.

[[Enumerable]] Boolean Iftrue,thepropertyistobeenumeratedbyaforinenumeration(see13.7.5).Otherwise,


thepropertyissaidtobenonenumerable.

[[Conigurable]] Boolean Iffalse,attemptstodeletetheproperty,changethepropertytobeadataproperty,or


changeitsattributeswillfail.

Iftheinitialvaluesofaproperty'sattributesarenotexplicitlyspeciiedbythisspeciication,thedefaultvaluedeinedin
Table4isused.

Table4:DefaultAttributeValues
AttributeName DefaultValue

[[Value]] undeined

[[Get]] undeined

[[Set]] undeined

[[Writable]] false

[[Enumerable]] false

[[Conigurable]] false

6.1.7.2 ObjectInternalMethodsandInternalSlots

Theactualsemanticsofobjects,inECMAScript,arespeciiedviaalgorithmscalledinternalmethods.Eachobjectinan
ECMAScriptengineisassociatedwithasetofinternalmethodsthatdeinesitsruntimebehaviour.Theseinternalmethods
arenotpartoftheECMAScriptlanguage.Theyaredeinedbythisspeciicationpurelyforexpositorypurposes.However,
eachobjectwithinanimplementationofECMAScriptmustbehaveasspeciiedbytheinternalmethodsassociatedwithit.
Theexactmannerinwhichthisisaccomplishedisdeterminedbytheimplementation.

Internalmethodnamesarepolymorphic.Thismeansthatdifferentobjectvaluesmayperformdifferentalgorithmswhena
commoninternalmethodnameisinvokeduponthem.Thatactualobjectuponwhichaninternalmethodisinvokedisthe
targetoftheinvocation.If,atruntime,theimplementationofanalgorithmattemptstouseaninternalmethodofanobject
thattheobjectdoesnotsupport,aTypeErrorexceptionisthrown.

InternalslotscorrespondtointernalstatethatisassociatedwithobjectsandusedbyvariousECMAScriptspeciication
algorithms.Internalslotsarenotobjectpropertiesandtheyarenotinherited.Dependinguponthespeciicinternalslot
speciication,suchstatemayconsistofvaluesofanyECMAScriptlanguagetypeorofspeciicECMAScriptspeciicationtype
values.Unlessexplicitlyspeciiedotherwise,internalslotsareallocatedaspartoftheprocessofcreatinganobjectandmay
notbedynamicallyaddedtoanobject.Unlessspeciiedotherwise,theinitialvalueofaninternalslotisthevalueundeined.
Variousalgorithmswithinthisspeciicationcreateobjectsthathaveinternalslots.However,theECMAScriptlanguage
providesnodirectwaytoassociateinternalslotswithanobject.

Internalmethodsandinternalslotsareidentiiedwithinthisspeciicationusingnamesenclosedindoublesquarebrackets[[
]].

Table5summarizestheessentialinternalmethodsusedbythisspeciicationthatareapplicabletoallobjectscreatedor
manipulatedbyECMAScriptcode.Everyobjectmusthavealgorithmsforalloftheessentialinternalmethods.However,all
objectsdonotnecessarilyusethesamealgorithmsforthosemethods.

TheSignaturecolumnofTable5andothersimilartablesdescribestheinvocationpatternforeachinternalmethod.The
invocationpatternalwaysincludesaparenthesizedlistofdescriptiveparameternames.Ifaparameternameisthesameas
anECMAScripttypenamethenthenamedescribestherequiredtypeoftheparametervalue.Ifaninternalmethodexplicitly
returnsavalue,itsparameterlistisfollowedbythesymbolandthetypenameofthereturnedvalue.Thetypenames
usedinsignaturesrefertothetypesdeinedinclause6augmentedbythefollowingadditionalnames.anymeansthevalue
maybeanyECMAScriptlanguagetype.AninternalmethodimplicitlyreturnsaCompletionRecord.Inadditiontoits
parameters,aninternalmethodalwayshasaccesstotheobjectthatisthetargetofthemethodinvocation.
Table5:EssentialInternalMethods
InternalMethod Signature Description

[[GetPrototypeOf]] ()Object|Null Determinetheobjectthatprovidesinheritedpropertiesforthisobject.A


nullvalueindicatesthattherearenoinheritedproperties.

[[SetPrototypeOf]] (Object|Null) Associatethisobjectwithanotherobjectthatprovidesinheritedproperties.


Boolean Passingnullindicatesthattherearenoinheritedproperties.Returnstrue
indicatingthattheoperationwascompletedsuccessfullyorfalseindicating
thattheoperationwasnotsuccessful.

[[IsExtensible]] ()Boolean Determinewhetheritispermittedtoaddadditionalpropertiestothis


object.

[[PreventExtensions]] ()Boolean Controlwhethernewpropertiesmaybeaddedtothisobject.Returnstrue


iftheoperationwassuccessfulorfalseiftheoperationwasunsuccessful.

[[GetOwnProperty]] (propertyKey) ReturnaPropertyDescriptorfortheownpropertyofthisobjectwhosekey


Undeined| ispropertyKey,orundeinedifnosuchpropertyexists.
Property
Descriptor

[[HasProperty]] (propertyKey) ReturnaBooleanvalueindicatingwhetherthisobjectalreadyhaseitheran


Boolean ownorinheritedpropertywhosekeyispropertyKey.

[[Get]] (propertyKey, ReturnthevalueofthepropertywhosekeyispropertyKeyfromthisobject.


Receiver)any IfanyECMAScriptcodemustbeexecutedtoretrievethepropertyvalue,
Receiverisusedasthethisvaluewhenevaluatingthecode.

[[Set]] (propertyKey,value, SetthevalueofthepropertywhosekeyispropertyKeytovalue.Ifany


Receiver) ECMAScriptcodemustbeexecutedtosetthepropertyvalue,Receiveris
Boolean usedasthethisvaluewhenevaluatingthecode.Returnstrueifthe
propertyvaluewassetorfalseifitcouldnotbeset.

[[Delete]] (propertyKey) RemovetheownpropertywhosekeyispropertyKeyfromthisobject.


Boolean Returnfalseifthepropertywasnotdeletedandisstillpresent.Return
trueifthepropertywasdeletedorisnotpresent.

[[DeineOwnProperty]] (propertyKey, Createoraltertheownproperty,whosekeyispropertyKey,tohavethe


PropertyDescriptor) statedescribedbyPropertyDescriptor.Returntrueifthatpropertywas
Boolean successfullycreated/updatedorfalseifthepropertycouldnotbecreated
orupdated.

[[OwnPropertyKeys]] ()Listof ReturnaListwhoseelementsarealloftheownpropertykeysforthe


propertyKey object.

Table6summarizesadditionalessentialinternalmethodsthataresupportedbyobjectsthatmaybecalledasfunctions.A
functionobjectisanobjectthatsupportsthe[[Call]]internalmethods.Aconstructor(alsoreferredtoasaconstructor
function)isafunctionobjectthatsupportsthe[[Construct]]internalmethod.
Table6:AdditionalEssentialInternalMethodsofFunctionObjects
Internal Signature Description
Method

[[Call]] (any,a Executescodeassociatedwiththisobject.Invokedviaafunctioncallexpression.The


Listof argumentstotheinternalmethodareathisvalueandalistcontainingtheargumentspassedto
any) thefunctionbyacallexpression.Objectsthatimplementthisinternalmethodarecallable.
any

[[Construct]] (aListof Createsanobject.Invokedviatheneworsuperoperators.Theirstargumenttotheinternal


any, methodisalistcontainingtheargumentsoftheoperator.Thesecondargumentistheobjectto
Object) whichthenewoperatorwasinitiallyapplied.Objectsthatimplementthisinternalmethodare
Object calledconstructors.Afunctionobjectisnotnecessarilyaconstructorandsuchnonconstructor
functionobjectsdonothavea[[Construct]]internalmethod.

Thesemanticsoftheessentialinternalmethodsforordinaryobjectsandstandardexoticobjectsarespeciiedinclause9.If
anyspeciieduseofaninternalmethodofanexoticobjectisnotsupportedbyanimplementation,thatusagemustthrowa
TypeErrorexceptionwhenattempted.

6.1.7.3 InvariantsoftheEssentialInternalMethods

TheInternalMethodsofObjectsofanECMAScriptenginemustconformtothelistofinvariantsspeciiedbelow.Ordinary
ECMAScriptObjectsaswellasallstandardexoticobjectsinthisspeciicationmaintaintheseinvariants.ECMAScriptProxy
objectsmaintaintheseinvariantsbymeansofruntimechecksontheresultoftrapsinvokedonthe[[ProxyHandler]]object.

Anyimplementationprovidedexoticobjectsmustalsomaintaintheseinvariantsforthoseobjects.Violationofthese
invariantsmaycauseECMAScriptcodetohaveunpredictablebehaviourandcreatesecurityissues.However,violationof
theseinvariantsmustnevercompromisethememorysafetyofanimplementation.

Animplementationmustnotallowtheseinvariantstobecircumventedinanymannersuchasbyprovidingalternative
interfacesthatimplementthefunctionalityoftheessentialinternalmethodswithoutenforcingtheirinvariants.

Deinitions:

Thetargetofaninternalmethodistheobjectuponwhichtheinternalmethodiscalled.
Atargetisnonextensibleifithasbeenobservedtoreturnfalsefromits[[IsExtensible]]internalmethod,ortruefrom
its[[PreventExtensions]]internalmethod.
Anonexistentpropertyisapropertythatdoesnotexistasanownpropertyonanonextensibletarget.
AllreferencestoSameValueareaccordingtothedeinitionoftheSameValuealgorithm.

[[GetPrototypeOf]]()

TheTypeofthereturnvaluemustbeeitherObjectorNull.
Iftargetisnonextensible,and[[GetPrototypeOf]]returnsavaluev,thenanyfuturecallsto[[GetPrototypeOf]]should
returntheSameValueasv.

NOTE1 Anobject'sprototypechainshouldhaveinitelength(thatis,startingfromanyobject,recursivelyapplyingthe
[[GetPrototypeOf]]internalmethodtoitsresultshouldeventuallyleadtothevaluenull).However,this
requirementisnotenforceableasanobjectlevelinvariantiftheprototypechainincludesanyexoticobjects
thatdonotusetheordinaryobjectdeinitionof[[GetPrototypeOf]].Suchacircularprototypechainmayresult
inininiteloopswhenaccessingobjectproperties.

[[SetPrototypeOf]](V)

TheTypeofthereturnvaluemustbeBoolean.
Iftargetisnonextensible,[[SetPrototypeOf]]mustreturnfalse,unlessVistheSameValueasthetarget'sobserved
[[GetPrototypeOf]]value.
[[IsExtensible]]()

TheTypeofthereturnvaluemustbeBoolean.
If[[IsExtensible]]returnsfalse,allfuturecallsto[[IsExtensible]]onthetargetmustreturnfalse.

[[PreventExtensions]]()

TheTypeofthereturnvaluemustbeBoolean.
If[[PreventExtensions]]returnstrue,allfuturecallsto[[IsExtensible]]onthetargetmustreturnfalseandthetargetis
nowconsiderednonextensible.

[[GetOwnProperty]](P)

TheTypeofthereturnvaluemustbeeitherPropertyDescriptororUndeined.
IftheTypeofthereturnvalueisPropertyDescriptor,thereturnvaluemustbeacompletepropertydescriptor(see
6.2.4.6).
IfapropertyPisdescribedasadatapropertywithDesc.[[Value]]equaltovandDesc.[[Writable]]andDesc.
[[Conigurable]]arebothfalse,thentheSameValuemustbereturnedfortheDesc.[[Value]]attributeofthepropertyon
allfuturecallsto[[GetOwnProperty]](P).
IfP'sattributesotherthan[[Writable]]maychangeovertimeorifthepropertymightdisappear,thenP's
[[Conigurable]]attributemustbetrue.
Ifthe[[Writable]]attributemaychangefromfalsetotrue,thenthe[[Conigurable]]attributemustbetrue.
IfthetargetisnonextensibleandPisnonexistent,thenallfuturecallsto[[GetOwnProperty]](P)onthetargetmust
describePasnonexistent(i.e.[[GetOwnProperty]](P)mustreturnundeined).

NOTE2 Asaconsequenceofthethirdinvariant,ifapropertyisdescribedasadatapropertyanditmayreturndifferent
valuesovertime,theneitherorbothoftheDesc.[[Writable]]andDesc.[[Conigurable]]attributesmustbetrue
evenifnomechanismtochangethevalueisexposedviatheotherinternalmethods.

[[DeineOwnProperty]](P,Desc)

TheTypeofthereturnvaluemustbeBoolean.

[[DeineOwnProperty]]mustreturnfalseifPhaspreviouslybeenobservedasanonconigurableownpropertyofthe
target,unlesseither:

1.Pisanonconigurablewritableowndataproperty.Anonconigurablewritabledatapropertycanbechanged
intoanonconigurablenonwritabledataproperty.
2.AllattributesinDescaretheSameValueasP'sattributes.
[[DeineOwnProperty]](P,Desc)mustreturnfalseiftargetisnonextensibleandPisanonexistentownproperty.That
is,anonextensibletargetobjectcannotbeextendedwithnewproperties.

[[HasProperty]](P)

TheTypeofthereturnvaluemustbeBoolean.
IfPwaspreviouslyobservedasanonconigurabledataoraccessorownpropertyofthetarget,[[HasProperty]]must
returntrue.

[[Get]](P,Receiver)

IfPwaspreviouslyobservedasanonconigurable,nonwritableowndatapropertyofthetargetwithvaluev,then
[[Get]]mustreturntheSameValue.
IfPwaspreviouslyobservedasanonconigurableownaccessorpropertyofthetargetwhose[[Get]]attributeis
undeined,the[[Get]]operationmustreturnundeined.

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

TheTypeofthereturnvaluemustbeBoolean.
IfPwaspreviouslyobservedasanonconigurable,nonwritableowndatapropertyofthetarget,then[[Set]]must
returnfalseunlessVistheSameValueasP's[[Value]]attribute.
IfPwaspreviouslyobservedasanonconigurableownaccessorpropertyofthetargetwhose[[Set]]attributeis
undeined,the[[Set]]operationmustreturnfalse.

[[Delete]](P)

TheTypeofthereturnvaluemustbeBoolean.
IfPwaspreviouslyobservedtobeanonconigurableowndataoraccessorpropertyofthetarget,[[Delete]]must
returnfalse.

[[OwnPropertyKeys]]()

ThereturnvaluemustbeaList.
TheTypeofeachelementofthereturnedListiseitherStringorSymbol.
ThereturnedListmustcontainatleastthekeysofallnonconigurableownpropertiesthathavepreviouslybeen
observed.
Iftheobjectisnonextensible,thereturnedListmustcontainonlythekeysofallownpropertiesoftheobjectthatare
observableusing[[GetOwnProperty]].

[[Construct]]()

TheTypeofthereturnvaluemustbeObject.

6.1.7.4 WellKnownIntrinsicObjects

Wellknownintrinsicsarebuiltinobjectsthatareexplicitlyreferencedbythealgorithmsofthisspeciicationandwhich
usuallyhaverealmspeciicidentities.Unlessotherwisespeciiedeachintrinsicobjectactuallycorrespondstoasetofsimilar
objects,oneperrealm.

Withinthisspeciicationareferencesuchas%name%meanstheintrinsicobject,associatedwiththecurrentrealm,
correspondingtothename.Determinationofthecurrentrealmanditsintrinsicsisdescribedin8.3.Thewellknown
intrinsicsarelistedinTable7.
Table7:WellknownIntrinsicObjects
IntrinsicName GlobalName ECMAScriptLanguageAssociation

%Array% Array TheArrayconstructor(22.1.1)

%ArrayBuffer% ArrayBuffer TheArrayBufferconstructor(24.1.2)

%ArrayBufferPrototype% ArrayBuffer.prototype Theinitialvalueoftheprototypedataproperty


of%ArrayBuffer%.

%ArrayIteratorPrototype% TheprototypeofArrayiteratorobjects(22.1.5)

%ArrayPrototype% Array.prototype Theinitialvalueoftheprototypedataproperty


of%Array%(22.1.3)

%ArrayProto_values% Array.prototype.values Theinitialvalueofthevaluesdatapropertyof


%ArrayPrototype%(22.1.3.30)

%Boolean% Boolean TheBooleanconstructor(19.3.1)

%BooleanPrototype% Boolean.prototype Theinitialvalueoftheprototypedataproperty


of%Boolean%(19.3.3)

%DataView% DataView TheDataViewconstructor(24.2.2)

%DataViewPrototype% DataView.prototype Theinitialvalueoftheprototypedataproperty


of%DataView%

%Date% Date TheDateconstructor(20.3.2)

%DatePrototype% Date.prototype Theinitialvalueoftheprototypedataproperty


of%Date%.

%decodeURI% decodeURI ThedecodeURIfunction(18.2.6.2)

%decodeURIComponent% decodeURIComponent ThedecodeURIComponentfunction(18.2.6.3)

%encodeURI% encodeURI TheencodeURIfunction(18.2.6.4)

%encodeURIComponent% encodeURIComponent TheencodeURIComponentfunction(18.2.6.5)

%Error% Error TheErrorconstructor(19.5.1)

%ErrorPrototype% Error.prototype Theinitialvalueoftheprototypedataproperty


of%Error%

%eval% eval Theevalfunction(18.2.1)

%EvalError% EvalError TheEvalErrorconstructor(19.5.5.1)

%EvalErrorPrototype% EvalError.prototype Theinitialvalueoftheprototypepropertyof


%EvalError%

%Float32Array% Float32Array TheFloat32Arrayconstructor(22.2)

%Float32ArrayPrototype% Float32Array.prototype Theinitialvalueoftheprototypedataproperty


of%Float32Array%.

%Float64Array% Float64Array TheFloat64Arrayconstructor(22.2)

%Float64ArrayPrototype% Float64Array.prototype Theinitialvalueoftheprototypedataproperty


of%Float64Array%

%Function% Function TheFunctionconstructor(19.2.1)


%FunctionPrototype% Function.prototype Theinitialvalueoftheprototypedataproperty
of%Function%

%Generator% Theinitialvalueoftheprototypepropertyof
%GeneratorFunction%

%GeneratorFunction% Theconstructorofgeneratorobjects(25.2.1)

%GeneratorPrototype% Theinitialvalueoftheprototypepropertyof
%Generator%

%Int8Array% Int8Array TheInt8Arrayconstructor(22.2)

%Int8ArrayPrototype% Int8Array.prototype Theinitialvalueoftheprototypedataproperty


of%Int8Array%

%Int16Array% Int16Array TheInt16Arrayconstructor(22.2)

%Int16ArrayPrototype% Int16Array.prototype Theinitialvalueoftheprototypedataproperty


of%Int16Array%

%Int32Array% Int32Array TheInt32Arrayconstructor(22.2)

%Int32ArrayPrototype% Int32Array.prototype Theinitialvalueoftheprototypedataproperty


of%Int32Array%

%isFinite% isFinite TheisFinitefunction(18.2.2)

%isNaN% isNaN TheisNaNfunction(18.2.3)

%IteratorPrototype% Anobjectthatallstandardbuiltiniterator
objectsindirectlyinheritfrom

%JSON% JSON TheJSONobject(24.3)

%Map% Map TheMapconstructor(23.1.1)

%MapIteratorPrototype% TheprototypeofMapiteratorobjects(23.1.5)

%MapPrototype% Map.prototype Theinitialvalueoftheprototypedataproperty


of%Map%

%Math% Math TheMathobject(20.2)

%Number% Number TheNumberconstructor(20.1.1)

%NumberPrototype% Number.prototype Theinitialvalueoftheprototypepropertyof


%Number%

%Object% Object TheObjectconstructor(19.1.1)

%ObjectPrototype% Object.prototype Theinitialvalueoftheprototypedataproperty


of%Object%.(19.1.3)

%ObjProto_toString% Object.prototype.toString TheinitialvalueofthetoStringdataproperty


of%ObjectPrototype%(19.1.3.6)

%ObjProto_valueOf% Object.prototype.valueOf TheinitialvalueofthevalueOfdatapropertyof


%ObjectPrototype%(19.1.3.7)

%parseFloat% parseFloat TheparseFloatfunction(18.2.4)

%parseInt% parseInt TheparseIntfunction(18.2.5)

%Promise% Promise ThePromiseconstructor(25.4.3)


%PromisePrototype% Promise.prototype Theinitialvalueoftheprototypedataproperty
of%Promise%

%Proxy% Proxy TheProxyconstructor(26.2.1)

%RangeError% RangeError TheRangeErrorconstructor(19.5.5.2)

%RangeErrorPrototype% RangeError.prototype Theinitialvalueoftheprototypepropertyof


%RangeError%

%ReferenceError% ReferenceError TheReferenceErrorconstructor(19.5.5.3)

%ReferenceErrorPrototype% ReferenceError.prototype Theinitialvalueoftheprototypepropertyof


%ReferenceError%

%Relect% Reflect TheReflectobject(26.1)

%RegExp% RegExp TheRegExpconstructor(21.2.3)

%RegExpPrototype% RegExp.prototype Theinitialvalueoftheprototypedataproperty


of%RegExp%

%Set% Set TheSetconstructor(23.2.1)

%SetIteratorPrototype% TheprototypeofSetiteratorobjects(23.2.5)

%SetPrototype% Set.prototype Theinitialvalueoftheprototypedataproperty


of%Set%

%String% String TheStringconstructor(21.1.1)

%StringIteratorPrototype% TheprototypeofStringiteratorobjects(21.1.5)

%StringPrototype% String.prototype Theinitialvalueoftheprototypedataproperty


of%String%

%Symbol% Symbol TheSymbolconstructor(19.4.1)

%SymbolPrototype% Symbol.prototype Theinitialvalueoftheprototypedataproperty


of%Symbol%.(19.4.3)

%SyntaxError% SyntaxError TheSyntaxErrorconstructor(19.5.5.4)

%SyntaxErrorPrototype% SyntaxError.prototype Theinitialvalueoftheprototypepropertyof


%SyntaxError%

%ThrowTypeError% Afunctionobjectthatunconditionallythrowsa
newinstanceof%TypeError%

%TypedArray% ThesuperclassofalltypedArrayconstructors
(22.2.1)

%TypedArrayPrototype% Theinitialvalueoftheprototypepropertyof
%TypedArray%

%TypeError% TypeError TheTypeErrorconstructor(19.5.5.5)

%TypeErrorPrototype% TypeError.prototype Theinitialvalueoftheprototypepropertyof


%TypeError%

%Uint8Array% Uint8Array TheUint8Arrayconstructor(22.2)

%Uint8ArrayPrototype% Uint8Array.prototype Theinitialvalueoftheprototypedataproperty


of%Uint8Array%

%Uint8ClampedArray% Uint8ClampedArray TheUint8ClampedArrayconstructor(22.2)

%Uint8ClampedArrayPrototype% Uint8ClampedArray.prototype Theinitialvalueoftheprototypedataproperty


of%Uint8ClampedArray%

%Uint16Array% Uint16Array TheUint16Arrayconstructor(22.2)

%Uint16ArrayPrototype% Uint16Array.prototype Theinitialvalueoftheprototypedataproperty


of%Uint16Array%

%Uint32Array% Uint32Array TheUint32Arrayconstructor(22.2)

%Uint32ArrayPrototype% Uint32Array.prototype Theinitialvalueoftheprototypedataproperty


of%Uint32Array%

%URIError% URIError TheURIErrorconstructor(19.5.5.6)

%URIErrorPrototype% URIError.prototype Theinitialvalueoftheprototypepropertyof


%URIError%

%WeakMap% WeakMap TheWeakMapconstructor(23.3.1)

%WeakMapPrototype% WeakMap.prototype Theinitialvalueoftheprototypedataproperty


of%WeakMap%

%WeakSet% WeakSet TheWeakSetconstructor(23.4.1)

%WeakSetPrototype% WeakSet.prototype Theinitialvalueoftheprototypedataproperty


of%WeakSet%

6.2 ECMAScriptSpeciicationTypes
AspeciicationtypecorrespondstometavaluesthatareusedwithinalgorithmstodescribethesemanticsofECMAScript
languageconstructsandECMAScriptlanguagetypes.ThespeciicationtypesareReference,List,Completion,Property
Descriptor,LexicalEnvironment,EnvironmentRecord,andDataBlock.Speciicationtypevaluesarespeciicationartefacts
thatdonotnecessarilycorrespondtoanyspeciicentitywithinanECMAScriptimplementation.Speciicationtypevalues
maybeusedtodescribeintermediateresultsofECMAScriptexpressionevaluationbutsuchvaluescannotbestoredas
propertiesofobjectsorvaluesofECMAScriptlanguagevariables.

6.2.1 TheListandRecordSpeciicationTypes

TheListtypeisusedtoexplaintheevaluationofargumentlists(see12.3.6)innewexpressions,infunctioncalls,andinother
algorithmswhereasimpleorderedlistofvaluesisneeded.ValuesoftheListtypearesimplyorderedsequencesoflist
elementscontainingtheindividualvalues.Thesesequencesmaybeofanylength.Theelementsofalistmayberandomly
accessedusing0originindices.FornotationalconvenienceanarraylikesyntaxcanbeusedtoaccessListelements.For
example,arguments[2]isshorthandforsayingthe3rdelementoftheListarguments.

Fornotationalconveniencewithinthisspeciication,aliteralsyntaxcanbeusedtoexpressanewListvalue.Forexample,1,
2deinesaListvaluethathastwoelementseachofwhichisinitializedtoaspeciicvalue.AnewemptyListcanbe
expressedas.

TheRecordtypeisusedtodescribedataaggregationswithinthealgorithmsofthisspeciication.ARecordtypevalue
consistsofoneormorenamedields.ThevalueofeachieldiseitheranECMAScriptvalueoranabstractvaluerepresented
byanameassociatedwiththeRecordtype.Fieldnamesarealwaysenclosedindoublebrackets,forexample[[Value]].
Fornotationalconveniencewithinthisspeciication,anobjectliterallikesyntaxcanbeusedtoexpressaRecordvalue.For
example,{[[Field1]]:42,[[Field2]]:false,[[Field3]]:empty}deinesaRecordvaluethathasthreeields,eachofwhichis
initializedtoaspeciicvalue.Fieldnameorderisnotsigniicant.Anyieldsthatarenotexplicitlylistedareconsideredtobe
absent.

Inspeciicationtextandalgorithms,dotnotationmaybeusedtorefertoaspeciicieldofaRecordvalue.Forexample,ifRis
therecordshowninthepreviousparagraphthenR.[[Field2]]isshorthandfortheieldofRnamed[[Field2]].

SchemaforcommonlyusedRecordieldcombinationsmaybenamed,andthatnamemaybeusedasapreixtoaliteral
Recordvaluetoidentifythespeciickindofaggregationsthatisbeingdescribed.Forexample:PropertyDescriptor{[[Value]]:
42,[[Writable]]:false,[[Conigurable]]:true}.

6.2.2 TheCompletionRecordSpeciicationType

TheCompletiontypeisaRecordusedtoexplaintheruntimepropagationofvaluesandcontrollowsuchasthebehaviourof
statements(break,continue,returnandthrow)thatperformnonlocaltransfersofcontrol.

ValuesoftheCompletiontypeareRecordvalueswhoseieldsaredeinedasbyTable8.Suchvaluesarereferredtoas
CompletionRecords.

Table8:CompletionRecordFields
Field Value Meaning

[[Type]] Oneofnormal,break,continue,return,orthrow Thetypeofcompletionthatoccurred.

[[Value]] anyECMAScriptlanguagevalueorempty Thevaluethatwasproduced.

[[Target]] anyECMAScriptstringorempty Thetargetlabelfordirectedcontroltransfers.

Thetermabruptcompletionreferstoanycompletionwitha[[Type]]valueotherthannormal.

6.2.2.1 NormalCompletion

TheabstractoperationNormalCompletionwithasingleargument,suchas:

1.ReturnNormalCompletion(argument).

Isashorthandthatisdeinedasfollows:

1.ReturnCompletion{[[Type]]:normal,[[Value]]:argument,[[Target]]:empty}.

6.2.2.2 ImplicitCompletionValues

ThealgorithmsofthisspeciicationoftenimplicitlyreturnCompletionRecordswhose[[Type]]isnormal.Unlessitis
otherwiseobviousfromthecontext,analgorithmstatementthatreturnsavaluethatisnotaCompletionRecord,suchas:

1.Return"Infinity".

meansthesamethingas:

1.ReturnNormalCompletion("Infinity").

However,ifthevalueexpressionofareturnstatementisaCompletionRecordconstructionliteral,theresultingCompletion
Recordisreturned.Ifthevalueexpressionisacalltoanabstractoperation,thereturnstatementsimplyreturnsthe
CompletionRecordproducedbytheabstractoperation.

TheabstractoperationCompletion(completionRecord)isusedtoemphasizethatapreviouslycomputedCompletionRecord
isbeingreturned.TheCompletionabstractoperationtakesasingleargument,completionRecord,andperformsthefollowing
steps:
1.Assert:completionRecordisaCompletionRecord.
2.ReturncompletionRecordastheCompletionRecordofthisabstractoperation.

Areturnstatementwithoutavalueinanalgorithmstepmeansthesamethingas:

1.ReturnNormalCompletion(undeined).

AnyreferencetoaCompletionRecordvaluethatisinacontextthatdoesnotexplicitlyrequireacompleteCompletionRecord
valueisequivalenttoanexplicitreferencetothe[[Value]]ieldoftheCompletionRecordvalueunlesstheCompletionRecord
isanabruptcompletion.

6.2.2.3 ThrowanException

Algorithmsstepsthatsaytothrowanexception,suchas

1.ThrowaTypeErrorexception.

meanthesamethingsas:

1.ReturnCompletion{[[Type]]:throw,[[Value]]:anewlycreatedTypeErrorobject,[[Target]]:empty}.

6.2.2.4 ReturnIfAbrupt

Algorithmsstepsthatsayorareotherwiseequivalentto:

1.ReturnIfAbrupt(argument).

meanthesamethingas:

1.Ifargumentisanabruptcompletion,returnargument.
2.ElseifargumentisaCompletionRecord,letargumentbeargument.[[Value]].

Algorithmsstepsthatsayorareotherwiseequivalentto:

1.ReturnIfAbrupt(AbstractOperation()).

meanthesamethingas:

1.LethygienicTempbeAbstractOperation().
2.IfhygienicTempisanabruptcompletion,returnhygienicTemp.
3.ElseifhygienicTempisaCompletionRecord,lethygienicTempbehygienicTemp.[[Value]].

WherehygienicTempisephemeralandvisibleonlyinthestepspertainingtoReturnIfAbrupt.

6.2.2.5 UpdateEmpty(completionRecord,value)

TheabstractoperationUpdateEmptywithargumentscompletionRecordandvalueperformsthefollowingsteps:

1.Assert:IfcompletionRecord.[[Type]]iseitherreturnorthrow,thencompletionRecord.[[Value]]isnotempty.
2.IfcompletionRecord.[[Value]]isnotempty,returnCompletion(completionRecord).
3.ReturnCompletion{[[Type]]:completionRecord.[[Type]],[[Value]]:value,[[Target]]:completionRecord.[[Target]]}.

6.2.3 TheReferenceSpeciicationType

NOTE TheReferencetypeisusedtoexplainthebehaviourofsuchoperatorsasdelete,typeof,theassignment
operators,thesuperkeywordandotherlanguagefeatures.Forexample,thelefthandoperandofan
assignmentisexpectedtoproduceareference.

AReferenceisaresolvednameorpropertybinding.AReferenceconsistsofthreecomponents,thebasevalue,thereferenced
nameandtheBooleanvaluedstrictreferencelag.Thebasevalueiseitherundeined,anObject,aBoolean,aString,a
Symbol,aNumber,oranEnvironmentRecord.AbasevalueofundeinedindicatesthattheReferencecouldnotberesolved
toabinding.ThereferencednameisaStringorSymbolvalue.

ASuperReferenceisaReferencethatisusedtorepresentsanamebindingthatwasexpressedusingthesuperkeyword.A
SuperReferencehasanadditionalthisValuecomponentanditsbasevaluewillneverbeanEnvironmentRecord.

Thefollowingabstractoperationsareusedinthisspeciicationtoaccessthecomponentsofreferences:

GetBase(V).ReturnsthebasevaluecomponentofthereferenceV.
GetReferencedName(V).ReturnsthereferencednamecomponentofthereferenceV.
IsStrictReference(V).ReturnsthestrictreferencelagcomponentofthereferenceV.
HasPrimitiveBase(V).ReturnstrueifType(base)isBoolean,String,Symbol,orNumber.
IsPropertyReference(V).ReturnstrueifeitherthebasevalueisanobjectorHasPrimitiveBase(V)istrue;otherwise
returnsfalse.
IsUnresolvableReference(V).Returnstrueifthebasevalueisundeinedandfalseotherwise.
IsSuperReference(V).ReturnstrueifthisreferencehasathisValuecomponent.

Thefollowingabstractoperationsareusedinthisspeciicationtooperateonreferences:

6.2.3.1 GetValue(V)

1.ReturnIfAbrupt(V).
2.IfType(V)isnotReference,returnV.
3.LetbasebeGetBase(V).
4.IfIsUnresolvableReference(V)istrue,throwaReferenceErrorexception.
5.IfIsPropertyReference(V)istrue,then
a.IfHasPrimitiveBase(V)istrue,then
i.Assert:Inthiscase,basewillneverbenullorundeined.
ii.LetbasebeToObject(base).
b.Return?base.[[Get]](GetReferencedName(V),GetThisValue(V)).
6.ElsebasemustbeanEnvironmentRecord,
a.Return?base.GetBindingValue(GetReferencedName(V),IsStrictReference(V))(see8.1.1).

NOTE Theobjectthatmaybecreatedinstep5.a.iiisnotaccessibleoutsideoftheaboveabstractoperationandthe
ordinaryobject[[Get]]internalmethod.Animplementationmightchoosetoavoidtheactualcreationofthe
object.

6.2.3.2 PutValue(V,W)

1.ReturnIfAbrupt(V).
2.ReturnIfAbrupt(W).
3.IfType(V)isnotReference,throwaReferenceErrorexception.
4.LetbasebeGetBase(V).
5.IfIsUnresolvableReference(V)istrue,then
a.IfIsStrictReference(V)istrue,then
i.ThrowaReferenceErrorexception.
b.LetglobalObjbeGetGlobalObject().
c.Return?Set(globalObj,GetReferencedName(V),W,false).
6.ElseifIsPropertyReference(V)istrue,then
a.IfHasPrimitiveBase(V)istrue,then
i.Assert:Inthiscase,basewillneverbenullorundeined.
ii.SetbasetoToObject(base).
b.Letsucceededbe?base.[[Set]](GetReferencedName(V),W,GetThisValue(V)).
c.IfsucceededisfalseandIsStrictReference(V)istrue,throwaTypeErrorexception.
d.Return.
7.ElsebasemustbeanEnvironmentRecord,
a.Return?base.SetMutableBinding(GetReferencedName(V),W,IsStrictReference(V))(see8.1.1).
NOTE Theobjectthatmaybecreatedinstep6.a.iiisnotaccessibleoutsideoftheabovealgorithmandtheordinary
object[[Set]]internalmethod.Animplementationmightchoosetoavoidtheactualcreationofthatobject.

6.2.3.3 GetThisValue(V)

1.Assert:IsPropertyReference(V)istrue.
2.IfIsSuperReference(V)istrue,then
a.ReturnthevalueofthethisValuecomponentofthereferenceV.
3.ReturnGetBase(V).

6.2.3.4 InitializeReferencedBinding(V,W)

1.ReturnIfAbrupt(V).
2.ReturnIfAbrupt(W).
3.Assert:Type(V)isReference.
4.Assert:IsUnresolvableReference(V)isfalse.
5.LetbasebeGetBase(V).
6.Assert:baseisanEnvironmentRecord.
7.Returnbase.InitializeBinding(GetReferencedName(V),W).

6.2.4 ThePropertyDescriptorSpeciicationType

ThePropertyDescriptortypeisusedtoexplainthemanipulationandreiicationofObjectpropertyattributes.Valuesofthe
PropertyDescriptortypeareRecords.Eachield'snameisanattributenameanditsvalueisacorrespondingattributevalue
asspeciiedin6.1.7.1.Inaddition,anyieldmaybepresentorabsent.Theschemanameusedwithinthisspeciicationtotag
literaldescriptionsofPropertyDescriptorrecordsisPropertyDescriptor.

PropertyDescriptorvaluesmaybefurtherclassiiedasdataPropertyDescriptorsandaccessorPropertyDescriptorsbased
upontheexistenceoruseofcertainields.AdataPropertyDescriptorisonethatincludesanyieldsnamedeither[[Value]]
or[[Writable]].AnaccessorPropertyDescriptorisonethatincludesanyieldsnamedeither[[Get]]or[[Set]].AnyProperty
Descriptormayhaveieldsnamed[[Enumerable]]and[[Conigurable]].APropertyDescriptorvaluemaynotbebothadata
PropertyDescriptorandanaccessorPropertyDescriptor;however,itmaybeneither.AgenericPropertyDescriptorisa
PropertyDescriptorvaluethatisneitheradataPropertyDescriptornoranaccessorPropertyDescriptor.Afullypopulated
PropertyDescriptorisonethatiseitheranaccessorPropertyDescriptororadataPropertyDescriptorandthathasallofthe
ieldsthatcorrespondtothepropertyattributesdeinedineitherTable2orTable3.

ThefollowingabstractoperationsareusedinthisspeciicationtooperateuponPropertyDescriptorvalues:

6.2.4.1 IsAccessorDescriptor(Desc)

WhentheabstractoperationIsAccessorDescriptoriscalledwithPropertyDescriptorDesc,thefollowingstepsaretaken:

1.IfDescisundeined,returnfalse.
2.IfbothDesc.[[Get]]andDesc.[[Set]]areabsent,returnfalse.
3.Returntrue.

6.2.4.2 IsDataDescriptor(Desc)

WhentheabstractoperationIsDataDescriptoriscalledwithPropertyDescriptorDesc,thefollowingstepsaretaken:

1.IfDescisundeined,returnfalse.
2.IfbothDesc.[[Value]]andDesc.[[Writable]]areabsent,returnfalse.
3.Returntrue.

6.2.4.3 IsGenericDescriptor(Desc)

WhentheabstractoperationIsGenericDescriptoriscalledwithPropertyDescriptorDesc,thefollowingstepsaretaken:

1.IfDescisundeined,returnfalse.
2.IfIsAccessorDescriptor(Desc)andIsDataDescriptor(Desc)arebothfalse,returntrue.
3.Returnfalse.

6.2.4.4 FromPropertyDescriptor(Desc)

WhentheabstractoperationFromPropertyDescriptoriscalledwithPropertyDescriptorDesc,thefollowingstepsaretaken:

1.IfDescisundeined,returnundeined.
2.LetobjbeObjectCreate(%ObjectPrototype%).
3.Assert:objisanextensibleordinaryobjectwithnoownproperties.
4.IfDeschasa[[Value]]ield,then
a.PerformCreateDataProperty(obj,"value",Desc.[[Value]]).
5.IfDeschasa[[Writable]]ield,then
a.PerformCreateDataProperty(obj,"writable",Desc.[[Writable]]).
6.IfDeschasa[[Get]]ield,then
a.PerformCreateDataProperty(obj,"get",Desc.[[Get]]).
7.IfDeschasa[[Set]]ield,then
a.PerformCreateDataProperty(obj,"set",Desc.[[Set]]).
8.IfDeschasan[[Enumerable]]ield,then
a.PerformCreateDataProperty(obj,"enumerable",Desc.[[Enumerable]]).
9.IfDeschasa[[Conigurable]]ield,then
a.PerformCreateDataProperty(obj,"configurable",Desc.[[Conigurable]]).
10.Assert:alloftheaboveCreateDataPropertyoperationsreturntrue.
11.Returnobj.

6.2.4.5 ToPropertyDescriptor(Obj)

WhentheabstractoperationToPropertyDescriptoriscalledwithobjectObj,thefollowingstepsaretaken:

1.IfType(Obj)isnotObject,throwaTypeErrorexception.
2.LetdescbeanewPropertyDescriptorthatinitiallyhasnoields.
3.LethasEnumerablebe?HasProperty(Obj,"enumerable").
4.IfhasEnumerableistrue,then
a.LetenumbeToBoolean(?Get(Obj,"enumerable")).
b.Setthe[[Enumerable]]ieldofdesctoenum.
5.LethasConigurablebe?HasProperty(Obj,"configurable").
6.IfhasConigurableistrue,then
a.LetconfbeToBoolean(?Get(Obj,"configurable")).
b.Setthe[[Conigurable]]ieldofdesctoconf.
7.LethasValuebe?HasProperty(Obj,"value").
8.IfhasValueistrue,then
a.Letvaluebe?Get(Obj,"value").
b.Setthe[[Value]]ieldofdesctovalue.
9.LethasWritablebe?HasProperty(Obj,"writable").
10.IfhasWritableistrue,then
a.LetwritablebeToBoolean(?Get(Obj,"writable")).
b.Setthe[[Writable]]ieldofdesctowritable.
11.LethasGetbe?HasProperty(Obj,"get").
12.IfhasGetistrue,then
a.Letgetterbe?Get(Obj,"get").
b.IfIsCallable(getter)isfalseandgetterisnotundeined,throwaTypeErrorexception.
c.Setthe[[Get]]ieldofdesctogetter.
13.LethasSetbe?HasProperty(Obj,"set").
14.IfhasSetistrue,then
a.Letsetterbe?Get(Obj,"set").
b.IfIsCallable(setter)isfalseandsetterisnotundeined,throwaTypeErrorexception.
c.Setthe[[Set]]ieldofdesctosetter.
15.Ifeitherdesc.[[Get]]ordesc.[[Set]]ispresent,then
a.Ifeitherdesc.[[Value]]ordesc.[[Writable]]ispresent,throwaTypeErrorexception.
16.Returndesc.

6.2.4.6 CompletePropertyDescriptor(Desc)

WhentheabstractoperationCompletePropertyDescriptoriscalledwithPropertyDescriptorDesc,thefollowingstepsare
taken:

1.Assert:DescisaPropertyDescriptor.
2.LetlikebeRecord{[[Value]]:undeined,[[Writable]]:false,[[Get]]:undeined,[[Set]]:undeined,[[Enumerable]]:
false,[[Conigurable]]:false}.
3.IfeitherIsGenericDescriptor(Desc)orIsDataDescriptor(Desc)istrue,then
a.IfDescdoesnothavea[[Value]]ield,setDesc.[[Value]]tolike.[[Value]].
b.IfDescdoesnothavea[[Writable]]ield,setDesc.[[Writable]]tolike.[[Writable]].
4.Else,
a.IfDescdoesnothavea[[Get]]ield,setDesc.[[Get]]tolike.[[Get]].
b.IfDescdoesnothavea[[Set]]ield,setDesc.[[Set]]tolike.[[Set]].
5.IfDescdoesnothavean[[Enumerable]]ield,setDesc.[[Enumerable]]tolike.[[Enumerable]].
6.IfDescdoesnothavea[[Conigurable]]ield,setDesc.[[Conigurable]]tolike.[[Conigurable]].
7.ReturnDesc.

6.2.5 TheLexicalEnvironmentandEnvironmentRecordSpeciicationTypes

TheLexicalEnvironmentandEnvironmentRecordtypesareusedtoexplainthebehaviourofnameresolutioninnested
functionsandblocks.Thesetypesandtheoperationsuponthemaredeinedin8.1.

6.2.6 DataBlocks

TheDataBlockspeciicationtypeisusedtodescribeadistinctandmutablesequenceofbytesized(8bit)numericvalues.A
DataBlockvalueiscreatedwithaixednumberofbytesthateachhavetheinitialvalue0.

Fornotationalconveniencewithinthisspeciication,anarraylikesyntaxcanbeusedtoaccesstheindividualbytesofaData
Blockvalue.ThisnotationpresentsaDataBlockvalueasa0originedintegerindexedsequenceofbytes.Forexample,ifdbis
a5byteDataBlockvaluethendb[2]canbeusedtoaccessits3rdbyte.

ThefollowingabstractoperationsareusedinthisspeciicationtooperateuponDataBlockvalues:

6.2.6.1 CreateByteDataBlock(size)

WhentheabstractoperationCreateByteDataBlockiscalledwithintegerargumentsize,thefollowingstepsaretaken:

1.Assert:size0.
2.LetdbbeanewDataBlockvalueconsistingofsizebytes.IfitisimpossibletocreatesuchaDataBlock,throwa
RangeErrorexception.
3.Setallofthebytesofdbto0.
4.Returndb.

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

WhentheabstractoperationCopyDataBlockBytesiscalled,thefollowingstepsaretaken:

1.Assert:fromBlockandtoBlockaredistinctDataBlockvalues.
2.Assert:fromIndex,toIndex,andcountareintegervalues0.
3.LetfromSizebethenumberofbytesinfromBlock.
4.Assert:fromIndex+countfromSize.
5.LettoSizebethenumberofbytesintoBlock.
6.Assert:toIndex+counttoSize.
7.Repeat,whilecount>0
a.SettoBlock[toIndex]tothevalueoffromBlock[fromIndex].
b.IncrementtoIndexandfromIndexeachby1.
c.Decrementcountby1.
8.ReturnNormalCompletion(empty).

7 AbstractOperations
TheseoperationsarenotapartoftheECMAScriptlanguage;theyaredeinedheretosolelytoaidthespeciicationofthe
semanticsoftheECMAScriptlanguage.Other,morespecializedabstractoperationsaredeinedthroughoutthisspeciication.

7.1 TypeConversion
TheECMAScriptlanguageimplicitlyperformsautomatictypeconversionasneeded.Toclarifythesemanticsofcertain
constructsitisusefultodeineasetofconversionabstractoperations.Theconversionabstractoperationsarepolymorphic;
theycanacceptavalueofanyECMAScriptlanguagetype.Butnootherspeciicationtypesareusedwiththeseoperations.

7.1.1 ToPrimitive(input[,PreferredType])

TheabstractoperationToPrimitivetakesaninputargumentandanoptionalargumentPreferredType.Theabstractoperation
ToPrimitiveconvertsitsinputargumenttoanonObjecttype.Ifanobjectiscapableofconvertingtomorethanoneprimitive
type,itmayusetheoptionalhintPreferredTypetofavourthattype.ConversionoccursaccordingtoTable9:

Table9:ToPrimitiveConversions
InputType Result

Undeined Returninput.

Null Returninput.

Boolean Returninput.

Number Returninput.

String Returninput.

Symbol Returninput.

Object Performthestepsfollowingthistable.

WhenType(input)isObject,thefollowingstepsaretaken:

1.IfPreferredTypewasnotpassed,lethintbe"default".
2.ElseifPreferredTypeishintString,lethintbe"string".
3.ElsePreferredTypeishintNumber,lethintbe"number".
4.LetexoticToPrimbe?GetMethod(input,@@toPrimitive).
5.IfexoticToPrimisnotundeined,then
a.Letresultbe?Call(exoticToPrim,input,hint).
b.IfType(result)isnotObject,returnresult.
c.ThrowaTypeErrorexception.
6.Ifhintis"default",lethintbe"number".
7.Return?OrdinaryToPrimitive(input,hint).

WhentheabstractoperationOrdinaryToPrimitiveiscalledwithargumentsOandhint,thefollowingstepsaretaken:
1.Assert:Type(O)isObject.
2.Assert:Type(hint)isStringanditsvalueiseither"string"or"number".
3.Ifhintis"string",then
a.LetmethodNamesbe"toString","valueOf".
4.Else,
a.LetmethodNamesbe"valueOf","toString".
5.ForeachnameinmethodNamesinListorder,do
a.Letmethodbe?Get(O,name).
b.IfIsCallable(method)istrue,then
i.Letresultbe?Call(method,O).
ii.IfType(result)isnotObject,returnresult.
6.ThrowaTypeErrorexception.

NOTE WhenToPrimitiveiscalledwithnohint,thenitgenerallybehavesasifthehintwereNumber.However,objects
mayoverridethisbehaviourbydeininga@@toPrimitivemethod.Oftheobjectsdeinedinthisspeciication
onlyDateobjects(see20.3.4.45)andSymbolobjects(see19.4.3.4)overridethedefaultToPrimitivebehaviour.
DateobjectstreatnohintasifthehintwereString.

7.1.2 ToBoolean(argument)

TheabstractoperationToBooleanconvertsargumenttoavalueoftypeBooleanaccordingtoTable10:

Table10:ToBooleanConversions
ArgumentType Result

Undeined Returnfalse.

Null Returnfalse.

Boolean Returnargument.

Number Returnfalseifargumentis+0,0,orNaN;otherwisereturntrue.

String ReturnfalseifargumentistheemptyString(itslengthiszero);otherwisereturntrue.

Symbol Returntrue.

Object Returntrue.

7.1.3 ToNumber(argument)

TheabstractoperationToNumberconvertsargumenttoavalueoftypeNumberaccordingtoTable11:
Table11:ToNumberConversions
ArgumentType Result

Undeined ReturnNaN.

Null Return+0.

Boolean Return1ifargumentistrue.Return+0ifargumentisfalse.

Number Returnargument(noconversion).

String Seegrammarandconversionalgorithmbelow.

Symbol ThrowaTypeErrorexception.

Object Applythefollowingsteps:

1.LetprimValuebe?ToPrimitive(argument,hintNumber).
2.Return?ToNumber(primValue).

7.1.3.1 ToNumberAppliedtotheStringType

ToNumberappliedtoStringsappliesthefollowinggrammartotheinputStringinterpretedasasequenceofUTF16encoded
codepoints(6.1.4).IfthegrammarcannotinterprettheStringasanexpansionofStringNumericLiteral,thentheresultof
ToNumberisNaN.

NOTE1 TheterminalsymbolsofthisgrammarareallcomposedofUnicodeBMPcodepointssotheresultwillbeNaN
ifthestringcontainstheUTF16encodingofanysupplementarycodepointsoranyunpairedsurrogatecode
points.

Syntax

StringNumericLiteral :::
StrWhiteSpaceopt
StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt

StrWhiteSpace :::
StrWhiteSpaceChar StrWhiteSpaceopt

StrWhiteSpaceChar :::
WhiteSpace
LineTerminator

StrNumericLiteral :::
StrDecimalLiteral
BinaryIntegerLiteral
OctalIntegerLiteral
HexIntegerLiteral

StrDecimalLiteral :::
StrUnsignedDecimalLiteral
+ StrUnsignedDecimalLiteral
StrUnsignedDecimalLiteral

StrUnsignedDecimalLiteral :::
Infinity
DecimalDigits . DecimalDigitsopt ExponentPartopt
. DecimalDigits ExponentPartopt
DecimalDigits ExponentPartopt

AllgrammarsymbolsnotexplicitlydeinedabovehavethedeinitionsusedintheLexicalGrammarfornumericliterals
(11.8.3)

NOTE2 SomedifferencesshouldbenotedbetweenthesyntaxofaStringNumericLiteralandaNumericLiteral:

AStringNumericLiteralmayincludeleadingand/ortrailingwhitespaceand/orlineterminators.
AStringNumericLiteralthatisdecimalmayhaveanynumberofleading0digits.
AStringNumericLiteralthatisdecimalmayincludea+ortoindicateitssign.
AStringNumericLiteralthatisemptyorcontainsonlywhitespaceisconvertedto+0.
InfinityandInfinityarerecognizedasaStringNumericLiteralbutnotasaNumericLiteral.

7.1.3.1.1 RuntimeSemantics:MV's

TheconversionofaStringtoaNumbervalueissimilaroveralltothedeterminationoftheNumbervalueforanumericliteral
(see11.8.3),butsomeofthedetailsaredifferent,sotheprocessforconvertingaStringnumericliteraltoavalueofNumber
typeisgivenhere.Thisvalueisdeterminedintwosteps:irst,amathematicalvalue(MV)isderivedfromtheStringnumeric
literal;second,thismathematicalvalueisroundedasdescribedbelow.TheMVonanygrammarsymbol,notprovidedbelow,
istheMVforthatsymboldeinedin11.8.3.1.

TheMVofStringNumericLiteral ::: [empty] is0.


TheMVofStringNumericLiteral ::: StrWhiteSpace is0.
TheMVofStringNumericLiteral ::: StrWhiteSpace StrNumericLiteral StrWhiteSpace istheMVofStrNumericLiteral,no
matterwhetherwhitespaceispresentornot.
TheMVofStrNumericLiteral ::: StrDecimalLiteral istheMVofStrDecimalLiteral.
TheMVofStrNumericLiteral ::: BinaryIntegerLiteral istheMVofBinaryIntegerLiteral.
TheMVofStrNumericLiteral ::: OctalIntegerLiteral istheMVofOctalIntegerLiteral.
TheMVofStrNumericLiteral ::: HexIntegerLiteral istheMVofHexIntegerLiteral.
TheMVofStrDecimalLiteral ::: StrUnsignedDecimalLiteral istheMVofStrUnsignedDecimalLiteral.
TheMVofStrDecimalLiteral ::: + StrUnsignedDecimalLiteral istheMVofStrUnsignedDecimalLiteral.
TheMVofStrDecimalLiteral ::: StrUnsignedDecimalLiteral isthenegativeoftheMVofStrUnsignedDecimalLiteral.
(NotethatiftheMVofStrUnsignedDecimalLiteralis0,thenegativeofthisMVisalso0.Theroundingruledescribed
belowhandlestheconversionofthissignlessmathematicalzerotoaloatingpoint+0or0asappropriate.)
TheMVofStrUnsignedDecimalLiteral ::: Infinity is1010000(avaluesolargethatitwillroundto+).
TheMVofStrUnsignedDecimalLiteral ::: DecimalDigits . istheMVofDecimalDigits.
TheMVofStrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigits istheMVoftheirstDecimalDigitsplus(the
MVofthesecondDecimalDigitstimes10n),wherenisthenumberofcodepointsinthesecondDecimalDigits.
TheMVofStrUnsignedDecimalLiteral ::: DecimalDigits . ExponentPart istheMVofDecimalDigitstimes10e,wheree
istheMVofExponentPart.
TheMVofStrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigits ExponentPart is(theMVoftheirst
DecimalDigitsplus(theMVofthesecondDecimalDigitstimes10n))times10e,wherenisthenumberofcodepointsin
thesecondDecimalDigitsandeistheMVofExponentPart.
TheMVofStrUnsignedDecimalLiteral ::: . DecimalDigits istheMVofDecimalDigitstimes10n,wherenisthenumber
ofcodepointsinDecimalDigits.
TheMVofStrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPart istheMVofDecimalDigitstimes10en,where
nisthenumberofcodepointsinDecimalDigitsandeistheMVofExponentPart.
TheMVofStrUnsignedDecimalLiteral ::: DecimalDigits istheMVofDecimalDigits.
TheMVofStrUnsignedDecimalLiteral ::: DecimalDigits ExponentPart istheMVofDecimalDigitstimes10e,whereeis
theMVofExponentPart.

OncetheexactMVforaStringnumericliteralhasbeendetermined,itisthenroundedtoavalueoftheNumbertype.Ifthe
MVis0,thentheroundedvalueis+0unlesstheirstnonwhitespacecodepointintheStringnumericliteralis"",inwhich
casetheroundedvalueis0.Otherwise,theroundedvaluemustbetheNumbervaluefortheMV(inthesensedeinedin
6.1.6),unlesstheliteralincludesaStrUnsignedDecimalLiteralandtheliteralhasmorethan20signiicantdigits,inwhichcase
theNumbervaluemaybeeithertheNumbervaluefortheMVofaliteralproducedbyreplacingeachsigniicantdigitafter
the20thwitha0digitortheNumbervaluefortheMVofaliteralproducedbyreplacingeachsigniicantdigitafterthe20th
witha0digitandthenincrementingtheliteralatthe20thdigitposition.Adigitissigniicantifitisnotpartofan
ExponentPartand

itisnot0;or
thereisanonzerodigittoitsleftandthereisanonzerodigit,notintheExponentPart,toitsright.

7.1.4 ToInteger(argument)

TheabstractoperationToIntegerconvertsargumenttoanintegralnumericvalue.Thisabstractoperationfunctionsas
follows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,return+0.
3.Ifnumberis+0,0,+,or,returnnumber.
4.Returnthenumbervaluethatisthesamesignasnumberandwhosemagnitudeisloor(abs(number)).

7.1.5 ToInt32(argument)

TheabstractoperationToInt32convertsargumenttooneof232integervaluesintherange231through2311,inclusive.
Thisabstractoperationfunctionsasfollows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,+0,0,+,or,return+0.
3.Letintbethemathematicalvaluethatisthesamesignasnumberandwhosemagnitudeisloor(abs(number)).
4.Letint32bitbeintmodulo232.
5.Ifint32bit231,returnint32bit232;otherwisereturnint32bit.

NOTE GiventheabovedeinitionofToInt32:

TheToInt32abstractoperationisidempotent:ifappliedtoaresultthatitproduced,thesecond
applicationleavesthatvalueunchanged.
ToInt32(ToUint32(x))isequaltoToInt32(x)forallvaluesofx.(Itistopreservethislatterpropertythat
+andaremappedto+0.)
ToInt32maps0to+0.

7.1.6 ToUint32(argument)

TheabstractoperationToUint32convertsargumenttooneof232integervaluesintherange0through2321,inclusive.This
abstractoperationfunctionsasfollows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,+0,0,+,or,return+0.
3.Letintbethemathematicalvaluethatisthesamesignasnumberandwhosemagnitudeisloor(abs(number)).
4.Letint32bitbeintmodulo232.
5.Returnint32bit.

NOTE GiventheabovedeinitionofToUint32:

Step5istheonlydifferencebetweenToUint32andToInt32.
TheToUint32abstractoperationisidempotent:ifappliedtoaresultthatitproduced,thesecond
applicationleavesthatvalueunchanged.
ToUint32(ToInt32(x))isequaltoToUint32(x)forallvaluesofx.(Itistopreservethislatterpropertythat
+andaremappedto+0.)
ToUint32maps0to+0.
7.1.7 ToInt16(argument)

TheabstractoperationToInt16convertsargumenttooneof216integervaluesintherange32768through32767,inclusive.
Thisabstractoperationfunctionsasfollows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,+0,0,+,or,return+0.
3.Letintbethemathematicalvaluethatisthesamesignasnumberandwhosemagnitudeisloor(abs(number)).
4.Letint16bitbeintmodulo216.
5.Ifint16bit215,returnint16bit216;otherwisereturnint16bit.

7.1.8 ToUint16(argument)

TheabstractoperationToUint16convertsargumenttooneof216integervaluesintherange0through2161,inclusive.This
abstractoperationfunctionsasfollows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,+0,0,+,or,return+0.
3.Letintbethemathematicalvaluethatisthesamesignasnumberandwhosemagnitudeisloor(abs(number)).
4.Letint16bitbeintmodulo216.
5.Returnint16bit.

NOTE GiventheabovedeinitionofToUint16:

Thesubstitutionof216for232instep4istheonlydifferencebetweenToUint32andToUint16.
ToUint16maps0to+0.

7.1.9 ToInt8(argument)

TheabstractoperationToInt8convertsargumenttooneof28integervaluesintherange128through127,inclusive.This
abstractoperationfunctionsasfollows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,+0,0,+,or,return+0.
3.Letintbethemathematicalvaluethatisthesamesignasnumberandwhosemagnitudeisloor(abs(number)).
4.Letint8bitbeintmodulo28.
5.Ifint8bit27,returnint8bit28;otherwisereturnint8bit.

7.1.10 ToUint8(argument)

TheabstractoperationToUint8convertsargumenttooneof28integervaluesintherange0through255,inclusive.This
abstractoperationfunctionsasfollows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,+0,0,+,or,return+0.
3.Letintbethemathematicalvaluethatisthesamesignasnumberandwhosemagnitudeisloor(abs(number)).
4.Letint8bitbeintmodulo28.
5.Returnint8bit.

7.1.11 ToUint8Clamp(argument)

TheabstractoperationToUint8Clampconvertsargumenttooneof28integervaluesintherange0through255,inclusive.
Thisabstractoperationfunctionsasfollows:

1.Letnumberbe?ToNumber(argument).
2.IfnumberisNaN,return+0.
3.Ifnumber0,return+0.
4.Ifnumber255,return255.
5.Letfbeloor(number).
6.Iff+0.5<number,returnf+1.
7.Ifnumber<f+0.5,returnf.
8.Iffisodd,returnf+1.
9.Returnf.

NOTE UnliketheotherECMAScriptintegerconversionabstractoperation,ToUint8Clamproundsratherthan
truncatesnonintegervaluesanddoesnotconvert+to0.ToUint8Clampdoesroundhalftoeventie
breaking.ThisdiffersfromMath.roundwhichdoesroundhalfuptiebreaking.

7.1.12 ToString(argument)

TheabstractoperationToStringconvertsargumenttoavalueoftypeStringaccordingtoTable12:

Table12:ToStringConversions
ArgumentType Result

Undeined Return"undefined".

Null Return"null".

Boolean Ifargumentistrue,return"true".

Ifargumentisfalse,return"false".

Number See7.1.12.1.

String Returnargument.

Symbol ThrowaTypeErrorexception.

Object Applythefollowingsteps:

1.LetprimValuebe?ToPrimitive(argument,hintString).
2.Return?ToString(primValue).

7.1.12.1 ToStringAppliedtotheNumberType

TheabstractoperationToStringconvertsaNumbermtoStringformatasfollows:

1.IfmisNaN,returntheString"NaN".
2.Ifmis+0or0,returntheString"0".
3.Ifmislessthanzero,returntheStringconcatenationoftheString""andToString(m).
4.Ifmis+,returntheString"Infinity".
5.Otherwise,letn,k,andsbeintegerssuchthatk1,10k1s<10k,theNumbervaluefors10nkism,andkisassmall
aspossible.Notethatkisthenumberofdigitsinthedecimalrepresentationofs,thatsisnotdivisibleby10,andthat
theleastsigniicantdigitofsisnotnecessarilyuniquelydeterminedbythesecriteria.
6.Ifkn21,returntheStringconsistingofthecodeunitsofthekdigitsofthedecimalrepresentationofs(inorder,
withnoleadingzeroes),followedbynkoccurrencesofthecodeunit0x0030(DIGITZERO).
7.If0<n21,returntheStringconsistingofthecodeunitsofthemostsigniicantndigitsofthedecimalrepresentation
ofs,followedbythecodeunit0x002E(FULLSTOP),followedbythecodeunitsoftheremainingkndigitsofthe
decimalrepresentationofs.
8.If6<n0,returntheStringconsistingofthecodeunit0x0030(DIGITZERO),followedbythecodeunit0x002E(FULL
STOP),followedbynoccurrencesofthecodeunit0x0030(DIGITZERO),followedbythecodeunitsofthekdigitsof
thedecimalrepresentationofs.
9.Otherwise,ifk=1,returntheStringconsistingofthecodeunitofthesingledigitofs,followedbycodeunit0x0065
(LATINSMALLLETTERE),followedbythecodeunit0x002B(PLUSSIGN)orthecodeunit0x002D(HYPHENMINUS)
accordingtowhethern1ispositiveornegative,followedbythecodeunitsofthedecimalrepresentationoftheinteger
abs(n1)(withnoleadingzeroes).
10.ReturntheStringconsistingofthecodeunitsofthemostsigniicantdigitofthedecimalrepresentationofs,followedby
codeunit0x002E(FULLSTOP),followedbythecodeunitsoftheremainingk1digitsofthedecimalrepresentationofs,
followedbycodeunit0x0065(LATINSMALLLETTERE),followedbycodeunit0x002B(PLUSSIGN)orthecodeunit
0x002D(HYPHENMINUS)accordingtowhethern1ispositiveornegative,followedbythecodeunitsofthedecimal
representationoftheintegerabs(n1)(withnoleadingzeroes).

NOTE1 Thefollowingobservationsmaybeusefulasguidelinesforimplementations,butarenotpartofthenormative
requirementsofthisStandard:

IfxisanyNumbervalueotherthan0,thenToNumber(ToString(x))isexactlythesameNumbervalueas
x.
Theleastsigniicantdigitofsisnotalwaysuniquelydeterminedbytherequirementslistedinstep5.

NOTE2 Forimplementationsthatprovidemoreaccurateconversionsthanrequiredbytherulesabove,itis
recommendedthatthefollowingalternativeversionofstep5beusedasaguideline:

5.Otherwise,letn,k,andsbeintegerssuchthatk1,10k1s<10k,theNumbervaluefors10nkism,
andkisassmallaspossible.Iftherearemultiplepossibilitiesfors,choosethevalueofsforwhichs10n
kisclosestinvaluetom.Iftherearetwosuchpossiblevaluesofs,choosetheonethatiseven.Notethatk

isthenumberofdigitsinthedecimalrepresentationofsandthatsisnotdivisibleby10.

NOTE3 ImplementersofECMAScriptmayindusefulthepaperandcodewrittenbyDavidM.Gayforbinarytodecimal
conversionofloatingpointnumbers:

Gay,DavidM.CorrectlyRoundedBinaryDecimalandDecimalBinaryConversions.NumericalAnalysis,
Manuscript9010.AT&TBellLaboratories(MurrayHill,NewJersey).November30,1990.Availableas
http://ampl.com/REFS/abstracts.html#rounding.Associatedcodeavailableas
http://netlib.sandia.gov/fp/dtoa.candas
http://netlib.sandia.gov/fp/g_fmt.candmayalsobefoundatthevariousnetlibmirrorsites.

7.1.13 ToObject(argument)

TheabstractoperationToObjectconvertsargumenttoavalueoftypeObjectaccordingtoTable13:
Table13:ToObjectConversions
Argument Result
Type

Undeined ThrowaTypeErrorexception.

Null ThrowaTypeErrorexception.

Boolean ReturnanewBooleanobjectwhose[[BooleanData]]internalslotissettothevalueofargument.See19.3for
adescriptionofBooleanobjects.

Number ReturnanewNumberobjectwhose[[NumberData]]internalslotissettothevalueofargument.See20.1for
adescriptionofNumberobjects.

String ReturnanewStringobjectwhose[[StringData]]internalslotissettothevalueofargument.See21.1fora
descriptionofStringobjects.

Symbol ReturnanewSymbolobjectwhose[[SymbolData]]internalslotissettothevalueofargument.See19.4fora
descriptionofSymbolobjects.

Object Returnargument.

7.1.14 ToPropertyKey(argument)

TheabstractoperationToPropertyKeyconvertsargumenttoavaluethatcanbeusedasapropertykeybyperformingthe
followingsteps:

1.Letkeybe?ToPrimitive(argument,hintString).
2.IfType(key)isSymbol,then
a.Returnkey.
3.Return!ToString(key).

7.1.15 ToLength(argument)

TheabstractoperationToLengthconvertsargumenttoanintegersuitableforuseasthelengthofanarraylikeobject.It
performsthefollowingsteps:

1.Letlenbe?ToInteger(argument).
2.Iflen+0,return+0.
3.Iflenis+,return2531.
4.Returnmin(len,2531).

7.1.16 CanonicalNumericIndexString(argument)

TheabstractoperationCanonicalNumericIndexStringreturnsargumentconvertedtoanumericvalueifitisaString
representationofaNumberthatwouldbeproducedbyToString,orthestring"0".Otherwise,itreturnsundeined.This
abstractoperationfunctionsasfollows:

1.Assert:Type(argument)isString.
2.Ifargumentis"0",return0.
3.LetnbeToNumber(argument).
4.IfSameValue(!ToString(n),argument)isfalse,returnundeined.
5.Returnn.

AcanonicalnumericstringisanyStringvalueforwhichtheCanonicalNumericIndexStringabstractoperationdoesnotreturn
undeined.
7.2 TestingandComparisonOperations
7.2.1 RequireObjectCoercible(argument)

TheabstractoperationRequireObjectCoerciblethrowsanerrorifargumentisavaluethatcannotbeconvertedtoanObject
usingToObject.ItisdeinedbyTable14:

Table14:RequireObjectCoercibleResults
ArgumentType Result

Undeined ThrowaTypeErrorexception.

Null ThrowaTypeErrorexception.

Boolean Returnargument.

Number Returnargument.

String Returnargument.

Symbol Returnargument.

Object Returnargument.

7.2.2 IsArray(argument)

TheabstractoperationIsArraytakesoneargumentargument,andperformsthefollowingsteps:

1.IfType(argument)isnotObject,returnfalse.
2.IfargumentisanArrayexoticobject,returntrue.
3.IfargumentisaProxyexoticobject,then
a.Ifthevalueofthe[[ProxyHandler]]internalslotofargumentisnull,throwaTypeErrorexception.
b.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofargument.
c.Return?IsArray(target).
4.Returnfalse.

7.2.3 IsCallable(argument)

TheabstractoperationIsCallabledeterminesifargument,whichmustbeanECMAScriptlanguagevalue,isacallablefunction
witha[[Call]]internalmethod.

1.IfType(argument)isnotObject,returnfalse.
2.Ifargumenthasa[[Call]]internalmethod,returntrue.
3.Returnfalse.

7.2.4 IsConstructor(argument)

TheabstractoperationIsConstructordeterminesifargument,whichmustbeanECMAScriptlanguagevalue,isafunction
objectwitha[[Construct]]internalmethod.

1.IfType(argument)isnotObject,returnfalse.
2.Ifargumenthasa[[Construct]]internalmethod,returntrue.
3.Returnfalse.

7.2.5 IsExtensible(O)

TheabstractoperationIsExtensibleisusedtodeterminewhetheradditionalpropertiescanbeaddedtotheobjectthatisO.A
Booleanvalueisreturned.Thisabstractoperationperformsthefollowingsteps:
1.Assert:Type(O)isObject.
2.Return?O.[[IsExtensible]]().

7.2.6 IsInteger(argument)

TheabstractoperationIsIntegerdeterminesifargumentisainiteintegernumericvalue.

1.IfType(argument)isnotNumber,returnfalse.
2.IfargumentisNaN,+,or,returnfalse.
3.Ifloor(abs(argument))abs(argument),returnfalse.
4.Returntrue.

7.2.7 IsPropertyKey(argument)

TheabstractoperationIsPropertyKeydeterminesifargument,whichmustbeanECMAScriptlanguagevalue,isavaluethat
maybeusedasapropertykey.

1.IfType(argument)isString,returntrue.
2.IfType(argument)isSymbol,returntrue.
3.Returnfalse.

7.2.8 IsRegExp(argument)

TheabstractoperationIsRegExpwithargumentargumentperformsthefollowingsteps:

1.IfType(argument)isnotObject,returnfalse.
2.LetisRegExpbe?Get(argument,@@match).
3.IfisRegExpisnotundeined,returnToBoolean(isRegExp).
4.Ifargumenthasa[[RegExpMatcher]]internalslot,returntrue.
5.Returnfalse.

7.2.9 SameValue(x,y)

TheinternalcomparisonabstractoperationSameValue(x,y),wherexandyareECMAScriptlanguagevalues,producestrue
orfalse.Suchacomparisonisperformedasfollows:

1.IfType(x)isdifferentfromType(y),returnfalse.
2.IfType(x)isNumber,then
a.IfxisNaNandyisNaN,returntrue.
b.Ifxis+0andyis0,returnfalse.
c.Ifxis0andyis+0,returnfalse.
d.IfxisthesameNumbervalueasy,returntrue.
e.Returnfalse.
3.ReturnSameValueNonNumber(x,y).

NOTE ThisalgorithmdiffersfromtheStrictEqualityComparisonAlgorithminitstreatmentofsignedzeroesand
NaNs.

7.2.10 SameValueZero(x,y)

TheinternalcomparisonabstractoperationSameValueZero(x,y),wherexandyareECMAScriptlanguagevalues,produces
trueorfalse.Suchacomparisonisperformedasfollows:

1.IfType(x)isdifferentfromType(y),returnfalse.
2.IfType(x)isNumber,then
a.IfxisNaNandyisNaN,returntrue.
b.Ifxis+0andyis0,returntrue.
c.Ifxis0andyis+0,returntrue.
d.IfxisthesameNumbervalueasy,returntrue.
e.Returnfalse.
3.ReturnSameValueNonNumber(x,y).

NOTE SameValueZerodiffersfromSameValueonlyinitstreatmentof+0and0.

7.2.11 SameValueNonNumber(x,y)

TheinternalcomparisonabstractoperationSameValueNonNumber(x,y),whereneitherxnoryareNumbervalues,produces
trueorfalse.Suchacomparisonisperformedasfollows:

1.Assert:Type(x)isnotNumber.
2.Assert:Type(x)isthesameasType(y).
3.IfType(x)isUndeined,returntrue.
4.IfType(x)isNull,returntrue.
5.IfType(x)isString,then
a.Ifxandyareexactlythesamesequenceofcodeunits(samelengthandsamecodeunitsatcorrespondingindices),
returntrue;otherwise,returnfalse.
6.IfType(x)isBoolean,then
a.Ifxandyarebothtrueorbothfalse,returntrue;otherwise,returnfalse.
7.IfType(x)isSymbol,then
a.IfxandyareboththesameSymbolvalue,returntrue;otherwise,returnfalse.
8.ReturntrueifxandyarethesameObjectvalue.Otherwise,returnfalse.

7.2.12 AbstractRelationalComparison

Thecomparisonx<y,wherexandyarevalues,producestrue,false,orundeined(whichindicatesthatatleastone
operandisNaN).InadditiontoxandythealgorithmtakesaBooleanlagnamedLeftFirstasaparameter.Thelagisusedto
controltheorderinwhichoperationswithpotentiallyvisiblesideeffectsareperformeduponxandy.Itisnecessarybecause
ECMAScriptspeciieslefttorightevaluationofexpressions.ThedefaultvalueofLeftFirstistrueandindicatesthatthex
parametercorrespondstoanexpressionthatoccurstotheleftoftheyparameter'scorrespondingexpression.IfLeftFirstis
false,thereverseisthecaseandoperationsmustbeperformeduponybeforex.Suchacomparisonisperformedasfollows:

1.IftheLeftFirstlagistrue,then
a.Letpxbe?ToPrimitive(x,hintNumber).
b.Letpybe?ToPrimitive(y,hintNumber).
2.Elsetheorderofevaluationneedstobereversedtopreservelefttorightevaluation
a.Letpybe?ToPrimitive(y,hintNumber).
b.Letpxbe?ToPrimitive(x,hintNumber).
3.IfbothpxandpyareStrings,then
a.Ifpyisapreixofpx,returnfalse.(AStringvaluepisapreixofStringvalueqifqcanbetheresultof
concatenatingpandsomeotherStringr.NotethatanyStringisapreixofitself,becausermaybetheempty
String.)
b.Ifpxisapreixofpy,returntrue.
c.Letkbethesmallestnonnegativeintegersuchthatthecodeunitatindexkwithinpxisdifferentfromthecodeunit
atindexkwithinpy.(Theremustbesuchak,forneitherStringisapreixoftheother.)
d.Letmbetheintegerthatisthecodeunitvalueatindexkwithinpx.
e.Letnbetheintegerthatisthecodeunitvalueatindexkwithinpy.
f.Ifm<n,returntrue.Otherwise,returnfalse.
4.Else,
a.Letnxbe?ToNumber(px).Becausepxandpyareprimitivevaluesevaluationorderisnotimportant.
b.Letnybe?ToNumber(py).
c.IfnxisNaN,returnundeined.
d.IfnyisNaN,returnundeined.
e.IfnxandnyarethesameNumbervalue,returnfalse.
f.Ifnxis+0andnyis0,returnfalse.
g.Ifnxis0andnyis+0,returnfalse.
h.Ifnxis+,returnfalse.
i.Ifnyis+,returntrue.
j.Ifnyis,returnfalse.
k.Ifnxis,returntrue.
l.Ifthemathematicalvalueofnxislessthanthemathematicalvalueofnynotethatthesemathematicalvaluesare
bothiniteandnotbothzeroreturntrue.Otherwise,returnfalse.

NOTE1 Step3differsfromstep7inthealgorithmfortheadditionoperator+(12.8.3)inusingandinsteadofor.

NOTE2 ThecomparisonofStringsusesasimplelexicographicorderingonsequencesofcodeunitvalues.Thereisno
attempttousethemorecomplex,semanticallyorienteddeinitionsofcharacterorstringequalityandcollating
orderdeinedintheUnicodespeciication.ThereforeStringvaluesthatarecanonicallyequalaccordingtothe
Unicodestandardcouldtestasunequal.IneffectthisalgorithmassumesthatbothStringsarealreadyin
normalizedform.Also,notethatforstringscontainingsupplementarycharacters,lexicographicorderingon
sequencesofUTF16codeunitvaluesdiffersfromthatonsequencesofcodepointvalues.

7.2.13 AbstractEqualityComparison

Thecomparisonx==y,wherexandyarevalues,producestrueorfalse.Suchacomparisonisperformedasfollows:

1.IfType(x)isthesameasType(y),then
a.ReturntheresultofperformingStrictEqualityComparisonx===y.
2.Ifxisnullandyisundeined,returntrue.
3.Ifxisundeinedandyisnull,returntrue.
4.IfType(x)isNumberandType(y)isString,returntheresultofthecomparisonx==ToNumber(y).
5.IfType(x)isStringandType(y)isNumber,returntheresultofthecomparisonToNumber(x)==y.
6.IfType(x)isBoolean,returntheresultofthecomparisonToNumber(x)==y.
7.IfType(y)isBoolean,returntheresultofthecomparisonx==ToNumber(y).
8.IfType(x)iseitherString,Number,orSymbolandType(y)isObject,returntheresultofthecomparisonx==
ToPrimitive(y).
9.IfType(x)isObjectandType(y)iseitherString,Number,orSymbol,returntheresultofthecomparisonToPrimitive(x)
==y.
10.Returnfalse.

7.2.14 StrictEqualityComparison

Thecomparisonx===y,wherexandyarevalues,producestrueorfalse.Suchacomparisonisperformedasfollows:

1.IfType(x)isdifferentfromType(y),returnfalse.
2.IfType(x)isNumber,then
a.IfxisNaN,returnfalse.
b.IfyisNaN,returnfalse.
c.IfxisthesameNumbervalueasy,returntrue.
d.Ifxis+0andyis0,returntrue.
e.Ifxis0andyis+0,returntrue.
f.Returnfalse.
3.ReturnSameValueNonNumber(x,y).

NOTE ThisalgorithmdiffersfromtheSameValueAlgorithminitstreatmentofsignedzeroesandNaNs.

7.3 OperationsonObjects
7.3.1 Get(O,P)

TheabstractoperationGetisusedtoretrievethevalueofaspeciicpropertyofanobject.Theoperationiscalledwith
argumentsOandPwhereOistheobjectandPisthepropertykey.Thisabstractoperationperformsthefollowingsteps:
1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.Return?O.[[Get]](P,O).

7.3.2 GetV(V,P)

TheabstractoperationGetVisusedtoretrievethevalueofaspeciicpropertyofanECMAScriptlanguagevalue.Ifthevalue
isnotanobject,thepropertylookupisperformedusingawrapperobjectappropriateforthetypeofthevalue.Theoperation
iscalledwithargumentsVandPwhereVisthevalueandPisthepropertykey.Thisabstractoperationperformsthe
followingsteps:

1.Assert:IsPropertyKey(P)istrue.
2.LetObe?ToObject(V).
3.Return?O.[[Get]](P,V).

7.3.3 Set(O,P,V,Throw)

TheabstractoperationSetisusedtosetthevalueofaspeciicpropertyofanobject.Theoperationiscalledwitharguments
O,P,V,andThrowwhereOistheobject,Pisthepropertykey,VisthenewvalueforthepropertyandThrowisaBooleanlag.
Thisabstractoperationperformsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.Assert:Type(Throw)isBoolean.
4.Letsuccessbe?O.[[Set]](P,V,O).
5.IfsuccessisfalseandThrowistrue,throwaTypeErrorexception.
6.Returnsuccess.

7.3.4 CreateDataProperty(O,P,V)

TheabstractoperationCreateDataPropertyisusedtocreateanewownpropertyofanobject.Theoperationiscalledwith
argumentsO,P,andVwhereOistheobject,Pisthepropertykey,andVisthevaluefortheproperty.Thisabstractoperation
performsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.LetnewDescbethePropertyDescriptor{[[Value]]:V,[[Writable]]:true,[[Enumerable]]:true,[[Conigurable]]:true}.
4.Return?O.[[DeineOwnProperty]](P,newDesc).

NOTE Thisabstractoperationcreatesapropertywhoseattributesaresettothesamedefaultsusedforproperties
createdbytheECMAScriptlanguageassignmentoperator.Normally,thepropertywillnotalreadyexist.Ifit
doesexistandisnotconigurableorifOisnotextensible,[[DeineOwnProperty]]willreturnfalse.

7.3.5 CreateMethodProperty(O,P,V)

TheabstractoperationCreateMethodPropertyisusedtocreateanewownpropertyofanobject.Theoperationiscalledwith
argumentsO,P,andVwhereOistheobject,Pisthepropertykey,andVisthevaluefortheproperty.Thisabstractoperation
performsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.LetnewDescbethePropertyDescriptor{[[Value]]:V,[[Writable]]:true,[[Enumerable]]:false,[[Conigurable]]:true}.
4.Return?O.[[DeineOwnProperty]](P,newDesc).

NOTE Thisabstractoperationcreatesapropertywhoseattributesaresettothesamedefaultsusedforbuiltin
methodsandmethodsdeinedusingclassdeclarationsyntax.Normally,thepropertywillnotalreadyexist.Ifit
doesexistandisnotconigurableorifOisnotextensible,[[DeineOwnProperty]]willreturnfalse.
7.3.6 CreateDataPropertyOrThrow(O,P,V)

TheabstractoperationCreateDataPropertyOrThrowisusedtocreateanewownpropertyofanobject.Itthrowsa
TypeErrorexceptioniftherequestedpropertyupdatecannotbeperformed.TheoperationiscalledwithargumentsO,P,
andVwhereOistheobject,Pisthepropertykey,andVisthevaluefortheproperty.Thisabstractoperationperformsthe
followingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.Letsuccessbe?CreateDataProperty(O,P,V).
4.Ifsuccessisfalse,throwaTypeErrorexception.
5.Returnsuccess.

NOTE Thisabstractoperationcreatesapropertywhoseattributesaresettothesamedefaultsusedforproperties
createdbytheECMAScriptlanguageassignmentoperator.Normally,thepropertywillnotalreadyexist.Ifit
doesexistandisnotconigurableorifOisnotextensible,[[DeineOwnProperty]]willreturnfalsecausingthis
operationtothrowaTypeErrorexception.

7.3.7 DeinePropertyOrThrow(O,P,desc)

TheabstractoperationDeinePropertyOrThrowisusedtocallthe[[DeineOwnProperty]]internalmethodofanobjectina
mannerthatwillthrowaTypeErrorexceptioniftherequestedpropertyupdatecannotbeperformed.Theoperationis
calledwithargumentsO,P,anddescwhereOistheobject,Pisthepropertykey,anddescisthePropertyDescriptorforthe
property.Thisabstractoperationperformsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.Letsuccessbe?O.[[DeineOwnProperty]](P,desc).
4.Ifsuccessisfalse,throwaTypeErrorexception.
5.Returnsuccess.

7.3.8 DeletePropertyOrThrow(O,P)

TheabstractoperationDeletePropertyOrThrowisusedtoremoveaspeciicownpropertyofanobject.Itthrowsan
exceptionifthepropertyisnotconigurable.TheoperationiscalledwithargumentsOandPwhereOistheobjectandPis
thepropertykey.Thisabstractoperationperformsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.Letsuccessbe?O.[[Delete]](P).
4.Ifsuccessisfalse,throwaTypeErrorexception.
5.Returnsuccess.

7.3.9 GetMethod(V,P)

TheabstractoperationGetMethodisusedtogetthevalueofaspeciicpropertyofanECMAScriptlanguagevaluewhenthe
valueofthepropertyisexpectedtobeafunction.TheoperationiscalledwithargumentsVandPwhereVistheECMAScript
languagevalue,Pisthepropertykey.Thisabstractoperationperformsthefollowingsteps:

1.Assert:IsPropertyKey(P)istrue.
2.Letfuncbe?GetV(V,P).
3.Iffunciseitherundeinedornull,returnundeined.
4.IfIsCallable(func)isfalse,throwaTypeErrorexception.
5.Returnfunc.

7.3.10 HasProperty(O,P)
TheabstractoperationHasPropertyisusedtodeterminewhetheranobjecthasapropertywiththespeciiedpropertykey.
Thepropertymaybeeitheranownorinherited.ABooleanvalueisreturned.TheoperationiscalledwithargumentsOandP
whereOistheobjectandPisthepropertykey.Thisabstractoperationperformsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.Return?O.[[HasProperty]](P).

7.3.11 HasOwnProperty(O,P)

TheabstractoperationHasOwnPropertyisusedtodeterminewhetheranobjecthasanownpropertywiththespeciied
propertykey.ABooleanvalueisreturned.TheoperationiscalledwithargumentsOandPwhereOistheobjectandPisthe
propertykey.Thisabstractoperationperformsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:IsPropertyKey(P)istrue.
3.Letdescbe?O.[[GetOwnProperty]](P).
4.Ifdescisundeined,returnfalse.
5.Returntrue.

7.3.12 Call(F,V[,argumentsList])

TheabstractoperationCallisusedtocallthe[[Call]]internalmethodofafunctionobject.Theoperationiscalledwith
argumentsF,V,andoptionallyargumentsListwhereFisthefunctionobject,VisanECMAScriptlanguagevaluethatisthe
thisvalueofthe[[Call]],andargumentsLististhevaluepassedtothecorrespondingargumentoftheinternalmethod.If
argumentsListisnotpresent,anewemptyListisusedasitsvalue.Thisabstractoperationperformsthefollowingsteps:

1.IfargumentsListwasnotpassed,letargumentsListbeanewemptyList.
2.IfIsCallable(F)isfalse,throwaTypeErrorexception.
3.Return?F.[[Call]](V,argumentsList).

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

TheabstractoperationConstructisusedtocallthe[[Construct]]internalmethodofafunctionobject.Theoperationiscalled
withargumentsF,andoptionallyargumentsList,andnewTargetwhereFisthefunctionobject.argumentsListandnewTarget
arethevaluestobepassedasthecorrespondingargumentsoftheinternalmethod.IfargumentsListisnotpresent,anew
emptyListisusedasitsvalue.IfnewTargetisnotpresent,Fisusedasitsvalue.Thisabstractoperationperformsthe
followingsteps:

1.IfnewTargetwasnotpassed,letnewTargetbeF.
2.IfargumentsListwasnotpassed,letargumentsListbeanewemptyList.
3.Assert:IsConstructor(F)istrue.
4.Assert:IsConstructor(newTarget)istrue.
5.Return?F.[[Construct]](argumentsList,newTarget).

NOTE IfnewTargetisnotpassed,thisoperationisequivalentto:newF(...argumentsList)

7.3.14 SetIntegrityLevel(O,level)

TheabstractoperationSetIntegrityLevelisusedtoixthesetofownpropertiesofanobject.Thisabstractoperation
performsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:leveliseither"sealed"or"frozen".
3.Letstatusbe?O.[[PreventExtensions]]().
4.Ifstatusisfalse,returnfalse.
5.Letkeysbe?O.[[OwnPropertyKeys]]().
6.Iflevelis"sealed",then
a.Repeatforeachelementkofkeys,
i.Perform?DeinePropertyOrThrow(O,k,PropertyDescriptor{[[Conigurable]]:false}).
7.Elselevelis"frozen",
a.Repeatforeachelementkofkeys,
i.LetcurrentDescbe?O.[[GetOwnProperty]](k).
ii.IfcurrentDescisnotundeined,then
1.IfIsAccessorDescriptor(currentDesc)istrue,then
a.LetdescbethePropertyDescriptor{[[Conigurable]]:false}.
2.Else,
a.LetdescbethePropertyDescriptor{[[Conigurable]]:false,[[Writable]]:false}.
3.Perform?DeinePropertyOrThrow(O,k,desc).
8.Returntrue.

7.3.15 TestIntegrityLevel(O,level)

TheabstractoperationTestIntegrityLevelisusedtodetermineifthesetofownpropertiesofanobjectareixed.This
abstractoperationperformsthefollowingsteps:

1.Assert:Type(O)isObject.
2.Assert:leveliseither"sealed"or"frozen".
3.Letstatusbe?IsExtensible(O).
4.Ifstatusistrue,returnfalse.
5.NOTEIftheobjectisextensible,noneofitspropertiesareexamined.
6.Letkeysbe?O.[[OwnPropertyKeys]]().
7.Repeatforeachelementkofkeys,
a.LetcurrentDescbe?O.[[GetOwnProperty]](k).
b.IfcurrentDescisnotundeined,then
i.IfcurrentDesc.[[Conigurable]]istrue,returnfalse.
ii.Iflevelis"frozen"andIsDataDescriptor(currentDesc)istrue,then
1.IfcurrentDesc.[[Writable]]istrue,returnfalse.
8.Returntrue.

7.3.16 CreateArrayFromList(elements)

TheabstractoperationCreateArrayFromListisusedtocreateanArrayobjectwhoseelementsareprovidedbyaList.This
abstractoperationperformsthefollowingsteps:

1.Assert:elementsisaListwhoseelementsareallECMAScriptlanguagevalues.
2.LetarraybeArrayCreate(0).
3.Letnbe0.
4.Foreachelementeofelements
a.LetstatusbeCreateDataProperty(array,!ToString(n),e).
b.Assert:statusistrue.
c.Incrementnby1.
5.Returnarray.

7.3.17 CreateListFromArrayLike(obj[,elementTypes])

TheabstractoperationCreateListFromArrayLikeisusedtocreateaListvaluewhoseelementsareprovidedbytheindexed
propertiesofanarraylikeobject,obj.TheoptionalargumentelementTypesisaListcontainingthenamesofECMAScript
LanguageTypesthatareallowedforelementvaluesoftheListthatiscreated.Thisabstractoperationperformsthefollowing
steps:

1.IfelementTypeswasnotpassed,letelementTypesbeUndeined,Null,Boolean,String,Symbol,Number,Object.
2.IfType(obj)isnotObject,throwaTypeErrorexception.
3.Letlenbe?ToLength(?Get(obj,"length")).
4.LetlistbeanewemptyList.
5.Letindexbe0.
6.Repeatwhileindex<len
a.LetindexNamebe!ToString(index).
b.Letnextbe?Get(obj,indexName).
c.IfType(next)isnotanelementofelementTypes,throwaTypeErrorexception.
d.Appendnextasthelastelementoflist.
e.Setindextoindex+1.
7.Returnlist.

7.3.18 Invoke(V,P[,argumentsList])

TheabstractoperationInvokeisusedtocallamethodpropertyofanECMAScriptlanguagevalue.Theoperationiscalled
withargumentsV,P,andoptionallyargumentsListwhereVservesasboththelookuppointforthepropertyandthethis
valueofthecall,Pisthepropertykey,andargumentsLististhelistofargumentsvaluespassedtothemethod.If
argumentsListisnotpresent,anewemptyListisusedasitsvalue.Thisabstractoperationperformsthefollowingsteps:

1.Assert:IsPropertyKey(P)istrue.
2.IfargumentsListwasnotpassed,letargumentsListbeanewemptyList.
3.Letfuncbe?GetV(V,P).
4.Return?Call(func,V,argumentsList).

7.3.19 OrdinaryHasInstance(C,O)

TheabstractoperationOrdinaryHasInstanceimplementsthedefaultalgorithmfordeterminingifanobjectOinheritsfrom
theinstanceobjectinheritancepathprovidedbyconstructorC.Thisabstractoperationperformsthefollowingsteps:

1.IfIsCallable(C)isfalse,returnfalse.
2.IfChasa[[BoundTargetFunction]]internalslot,then
a.LetBCbethevalueofC's[[BoundTargetFunction]]internalslot.
b.Return?InstanceofOperator(O,BC).
3.IfType(O)isnotObject,returnfalse.
4.LetPbe?Get(C,"prototype").
5.IfType(P)isnotObject,throwaTypeErrorexception.
6.Repeat
a.LetObe?O.[[GetPrototypeOf]]().
b.IfOisnull,returnfalse.
c.IfSameValue(P,O)istrue,returntrue.

7.3.20 SpeciesConstructor(O,defaultConstructor)

TheabstractoperationSpeciesConstructorisusedtoretrievetheconstructorthatshouldbeusedtocreatenewobjectsthat
arederivedfromtheargumentobjectO.ThedefaultConstructorargumentistheconstructortouseifaconstructor
@@speciespropertycannotbefoundstartingfromO.Thisabstractoperationperformsthefollowingsteps:

1.Assert:Type(O)isObject.
2.LetCbe?Get(O,"constructor").
3.IfCisundeined,returndefaultConstructor.
4.IfType(C)isnotObject,throwaTypeErrorexception.
5.LetSbe?Get(C,@@species).
6.IfSiseitherundeinedornull,returndefaultConstructor.
7.IfIsConstructor(S)istrue,returnS.
8.ThrowaTypeErrorexception.

7.3.21 EnumerableOwnNames(O)

WhentheabstractoperationEnumerableOwnNamesiscalledwithObjectO,thefollowingstepsaretaken:
1.Assert:Type(O)isObject.
2.LetownKeysbe?O.[[OwnPropertyKeys]]().
3.LetnamesbeanewemptyList.
4.Repeat,foreachelementkeyofownKeysinListorder
a.IfType(key)isString,then
i.Letdescbe?O.[[GetOwnProperty]](key).
ii.Ifdescisnotundeined,then
1.Ifdesc.[[Enumerable]]istrue,appendkeytonames.
5.OrdertheelementsofnamessotheyareinthesamerelativeorderaswouldbeproducedbytheIteratorthatwouldbe
returnediftheEnumerateObjectPropertiesinternalmethodwasinvokedwithO.
6.Returnnames.

7.3.22 GetFunctionRealm(obj)

TheabstractoperationGetFunctionRealmwithargumentobjperformsthefollowingsteps:

1.Assert:objisacallableobject.
2.Ifobjhasa[[Realm]]internalslot,then
a.Returnobj's[[Realm]]internalslot.
3.IfobjisaBoundFunctionexoticobject,then
a.Lettargetbeobj's[[BoundTargetFunction]]internalslot.
b.Return?GetFunctionRealm(target).
4.IfobjisaProxyexoticobject,then
a.Ifthevalueofthe[[ProxyHandler]]internalslotofobjisnull,throwaTypeErrorexception.
b.LetproxyTargetbethevalueofobj's[[ProxyTarget]]internalslot.
c.Return?GetFunctionRealm(proxyTarget).
5.ReturnthecurrentRealmRecord.

NOTE Step5willonlybereachediftargetisanonstandardexoticfunctionobjectthatdoesnothavea[[Realm]]
internalslot.

7.4 OperationsonIteratorObjects
SeeCommonIterationInterfaces(25.1).

7.4.1 GetIterator(obj[,method])

TheabstractoperationGetIteratorwithargumentobjandoptionalargumentmethodperformsthefollowingsteps:

1.Ifmethodwasnotpassed,then
a.Letmethodbe?GetMethod(obj,@@iterator).
2.Letiteratorbe?Call(method,obj).
3.IfType(iterator)isnotObject,throwaTypeErrorexception.
4.Returniterator.

7.4.2 IteratorNext(iterator[,value])

TheabstractoperationIteratorNextwithargumentiteratorandoptionalargumentvalueperformsthefollowingsteps:

1.Ifvaluewasnotpassed,then
a.Letresultbe?Invoke(iterator,"next",).
2.Else,
a.Letresultbe?Invoke(iterator,"next",value).
3.IfType(result)isnotObject,throwaTypeErrorexception.
4.Returnresult.
7.4.3 IteratorComplete(iterResult)

TheabstractoperationIteratorCompletewithargumentiterResultperformsthefollowingsteps:

1.Assert:Type(iterResult)isObject.
2.ReturnToBoolean(?Get(iterResult,"done")).

7.4.4 IteratorValue(iterResult)

TheabstractoperationIteratorValuewithargumentiterResultperformsthefollowingsteps:

1.Assert:Type(iterResult)isObject.
2.Return?Get(iterResult,"value").

7.4.5 IteratorStep(iterator)

TheabstractoperationIteratorStepwithargumentiteratorrequeststhenextvaluefromiteratorandreturnseitherfalse
indicatingthattheiteratorhasreacheditsendortheIteratorResultobjectifanextvalueisavailable.IteratorStepperforms
thefollowingsteps:

1.Letresultbe?IteratorNext(iterator).
2.Letdonebe?IteratorComplete(result).
3.Ifdoneistrue,returnfalse.
4.Returnresult.

7.4.6 IteratorClose(iterator,completion)

TheabstractoperationIteratorClosewithargumentsiteratorandcompletionisusedtonotifyaniteratorthatitshould
performanyactionsitwouldnormallyperformwhenithasreacheditscompletedstate:

1.Assert:Type(iterator)isObject.
2.Assert:completionisaCompletionRecord.
3.Letreturnbe?GetMethod(iterator,"return").
4.Ifreturnisundeined,returnCompletion(completion).
5.LetinnerResultbeCall(return,iterator,).
6.Ifcompletion.[[Type]]isthrow,returnCompletion(completion).
7.IfinnerResult.[[Type]]isthrow,returnCompletion(innerResult).
8.IfType(innerResult.[[Value]])isnotObject,throwaTypeErrorexception.
9.ReturnCompletion(completion).

7.4.7 CreateIterResultObject(value,done)

TheabstractoperationCreateIterResultObjectwithargumentsvalueanddonecreatesanobjectthatsupportsthe
IteratorResultinterfacebyperformingthefollowingsteps:

1.Assert:Type(done)isBoolean.
2.LetobjbeObjectCreate(%ObjectPrototype%).
3.PerformCreateDataProperty(obj,"value",value).
4.PerformCreateDataProperty(obj,"done",done).
5.Returnobj.

7.4.8 CreateListIterator(list)

TheabstractoperationCreateListIteratorwithargumentlistcreatesanIterator(25.1.1.2)objectwhosenextmethodreturns
thesuccessiveelementsoflist.Itperformsthefollowingsteps:

1.LetiteratorbeObjectCreate(%IteratorPrototype%,[[IteratorNext]],[[IteratedList]],[[ListIteratorNextIndex]]).
2.Setiterator's[[IteratedList]]internalslottolist.
3.Setiterator's[[ListIteratorNextIndex]]internalslotto0.
4.LetnextbeanewbuiltinfunctionobjectasdeinedinListIteratornext(7.4.8.1).
5.Setiterator's[[IteratorNext]]internalslottonext.
6.PerformCreateMethodProperty(iterator,"next",next).
7.Returniterator.

7.4.8.1 ListIteratornext()

TheListIteratornextmethodisastandardbuiltinfunctionobject(clause17)thatperformsthefollowingsteps:

1.LetObethethisvalue.
2.Letfbetheactivefunctionobject.
3.IfOdoesnothavea[[IteratorNext]]internalslot,throwaTypeErrorexception.
4.Letnextbethevalueofthe[[IteratorNext]]internalslotofO.
5.IfSameValue(f,next)isfalse,throwaTypeErrorexception.
6.IfOdoesnothavean[[IteratedList]]internalslot,throwaTypeErrorexception.
7.Letlistbethevalueofthe[[IteratedList]]internalslotofO.
8.Letindexbethevalueofthe[[ListIteratorNextIndex]]internalslotofO.
9.Letlenbethenumberofelementsoflist.
10.Ifindexlen,then
a.ReturnCreateIterResultObject(undeined,true).
11.Setthevalueofthe[[ListIteratorNextIndex]]internalslotofOtoindex+1.
12.ReturnCreateIterResultObject(list[index],false).

NOTE AListIteratornextmethodwillthrowanexceptionifappliedtoanyobjectotherthantheonewithwhichit
wasoriginallyassociated.

8 ExecutableCodeandExecutionContexts
8.1 LexicalEnvironments
ALexicalEnvironmentisaspeciicationtypeusedtodeinetheassociationofIdentiierstospeciicvariablesandfunctions
baseduponthelexicalnestingstructureofECMAScriptcode.ALexicalEnvironmentconsistsofanEnvironmentRecordanda
possiblynullreferencetoanouterLexicalEnvironment.UsuallyaLexicalEnvironmentisassociatedwithsomespeciic
syntacticstructureofECMAScriptcodesuchasaFunctionDeclaration,aBlockStatement,oraCatchclauseofaTryStatement
andanewLexicalEnvironmentiscreatedeachtimesuchcodeisevaluated.

AnEnvironmentRecordrecordstheidentiierbindingsthatarecreatedwithinthescopeofitsassociatedLexical
Environment.ItisreferredtoastheLexicalEnvironment'sEnvironmentRecord

TheouterenvironmentreferenceisusedtomodelthelogicalnestingofLexicalEnvironmentvalues.Theouterreferenceofa
(inner)LexicalEnvironmentisareferencetotheLexicalEnvironmentthatlogicallysurroundstheinnerLexical
Environment.AnouterLexicalEnvironmentmay,ofcourse,haveitsownouterLexicalEnvironment.ALexicalEnvironment
mayserveastheouterenvironmentformultipleinnerLexicalEnvironments.Forexample,ifaFunctionDeclarationcontains
twonestedFunctionDeclarationsthentheLexicalEnvironmentsofeachofthenestedfunctionswillhaveastheirouter
LexicalEnvironmenttheLexicalEnvironmentofthecurrentevaluationofthesurroundingfunction.

AglobalenvironmentisaLexicalEnvironmentwhichdoesnothaveanouterenvironment.Theglobalenvironment'souter
environmentreferenceisnull.Aglobalenvironment'sEnvironmentRecordmaybeprepopulatedwithidentiierbindingsand
includesanassociatedglobalobjectwhosepropertiesprovidesomeoftheglobalenvironment'sidentiierbindings.As
ECMAScriptcodeisexecuted,additionalpropertiesmaybeaddedtotheglobalobjectandtheinitialpropertiesmaybe
modiied.

AmoduleenvironmentisaLexicalEnvironmentthatcontainsthebindingsforthetopleveldeclarationsofaModule.Italso
containsthebindingsthatareexplicitlyimportedbytheModule.Theouterenvironmentofamoduleenvironmentisaglobal
environment.

AfunctionenvironmentisaLexicalEnvironmentthatcorrespondstotheinvocationofanECMAScriptfunctionobject.A
functionenvironmentmayestablishanewthisbinding.Afunctionenvironmentalsocapturesthestatenecessaryto
supportsupermethodinvocations.

LexicalEnvironmentsandEnvironmentRecordvaluesarepurelyspeciicationmechanismsandneednotcorrespondtoany
speciicartefactofanECMAScriptimplementation.ItisimpossibleforanECMAScriptprogramtodirectlyaccessor
manipulatesuchvalues.

8.1.1 EnvironmentRecords

TherearetwoprimarykindsofEnvironmentRecordvaluesusedinthisspeciication:declarativeEnvironmentRecordsand
objectEnvironmentRecords.DeclarativeEnvironmentRecordsareusedtodeinetheeffectofECMAScriptlanguagesyntactic
elementssuchasFunctionDeclarations,VariableDeclarations,andCatchclausesthatdirectlyassociateidentiierbindings
withECMAScriptlanguagevalues.ObjectEnvironmentRecordsareusedtodeinetheeffectofECMAScriptelementssuchas
WithStatementthatassociateidentiierbindingswiththepropertiesofsomeobject.GlobalEnvironmentRecordsand
functionEnvironmentRecordsarespecializationsthatareusedforspeciicallyforScriptglobaldeclarationsandfortoplevel
declarationswithinfunctions.

ForspeciicationpurposesEnvironmentRecordvaluesarevaluesoftheRecordspeciicationtypeandcanbethoughtofas
existinginasimpleobjectorientedhierarchywhereEnvironmentRecordisanabstractclasswiththreeconcretesubclasses,
declarativeEnvironmentRecord,objectEnvironmentRecord,andglobalEnvironmentRecord.FunctionEnvironment
RecordsandmoduleEnvironmentRecordsaresubclassesofdeclarativeEnvironmentRecord.Theabstractclassincludesthe
abstractspeciicationmethodsdeinedinTable15.Theseabstractmethodshavedistinctconcretealgorithmsforeachofthe
concretesubclasses.
Table15:AbstractMethodsofEnvironmentRecords
Method Purpose

HasBinding(N) DetermineifanEnvironmentRecordhasabindingfortheStringvalueN.Returntrueifit
doesandfalseifitdoesnot

CreateMutableBinding(N, CreateanewbutuninitializedmutablebindinginanEnvironmentRecord.TheStringvalue
D) Nisthetextoftheboundname.IftheBooleanargumentDistruethebindingmaybe
subsequentlydeleted.

CreateImmutableBinding(N, CreateanewbutuninitializedimmutablebindinginanEnvironmentRecord.TheString
S) valueNisthetextoftheboundname.IfSistruethenattemptstoaccessthevalueofthe
bindingbeforeitisinitializedorsetitafterithasbeeninitializedwillalwaysthrowan
exception,regardlessofthestrictmodesettingofoperationsthatreferencethatbinding.

InitializeBinding(N,V) SetthevalueofanalreadyexistingbutuninitializedbindinginanEnvironmentRecord.The
StringvalueNisthetextoftheboundname.Visthevalueforthebindingandisavalueof
anyECMAScriptlanguagetype.

SetMutableBinding(N,V,S) SetthevalueofanalreadyexistingmutablebindinginanEnvironmentRecord.TheString
valueNisthetextoftheboundname.Visthevalueforthebindingandmaybeavalueofany
ECMAScriptlanguagetype.SisaBooleanlag.IfSistrueandthebindingcannotbeset
throwaTypeErrorexception.

GetBindingValue(N,S) ReturnsthevalueofanalreadyexistingbindingfromanEnvironmentRecord.TheString
valueNisthetextoftheboundname.Sisusedtoidentifyreferencesoriginatinginstrict
modecodeorthatotherwiserequirestrictmodereferencesemantics.IfSistrueandthe
bindingdoesnotexistthrowaReferenceErrorexception.Ifthebindingexistsbutis
uninitializedaReferenceErroristhrown,regardlessofthevalueofS.

DeleteBinding(N) DeleteabindingfromanEnvironmentRecord.TheStringvalueNisthetextofthebound
name.IfabindingforNexists,removethebindingandreturntrue.Ifthebindingexistsbut
cannotberemovedreturnfalse.Ifthebindingdoesnotexistreturntrue.

HasThisBinding() DetermineifanEnvironmentRecordestablishesathisbinding.Returntrueifitdoesand
falseifitdoesnot.

HasSuperBinding() DetermineifanEnvironmentRecordestablishesasupermethodbinding.Returntrueifit
doesandfalseifitdoesnot.

WithBaseObject() IfthisEnvironmentRecordisassociatedwithawithstatement,returnthewithobject.
Otherwise,returnundeined.

8.1.1.1 DeclarativeEnvironmentRecords

EachdeclarativeEnvironmentRecordisassociatedwithanECMAScriptprogramscopecontainingvariable,constant,let,
class,module,import,and/orfunctiondeclarations.AdeclarativeEnvironmentRecordbindsthesetofidentiiersdeinedby
thedeclarationscontainedwithinitsscope.

ThebehaviouroftheconcretespeciicationmethodsfordeclarativeEnvironmentRecordsisdeinedbythefollowing
algorithms.

8.1.1.1.1 HasBinding(N)

TheconcreteEnvironmentRecordmethodHasBindingfordeclarativeEnvironmentRecordssimplydeterminesifthe
argumentidentiierisoneoftheidentiiersboundbytherecord:

1.LetenvRecbethedeclarativeEnvironmentRecordforwhichthemethodwasinvoked.
2.IfenvRechasabindingforthenamethatisthevalueofN,returntrue.
3.Returnfalse.

8.1.1.1.2 CreateMutableBinding(N,D)

TheconcreteEnvironmentRecordmethodCreateMutableBindingfordeclarativeEnvironmentRecordscreatesanew
mutablebindingforthenameNthatisuninitialized.AbindingmustnotalreadyexistinthisEnvironmentRecordforN.If
BooleanargumentDhasthevaluetruethenewbindingismarkedasbeingsubjecttodeletion.

1.LetenvRecbethedeclarativeEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRecdoesnotalreadyhaveabindingforN.
3.CreateamutablebindinginenvRecforNandrecordthatitisuninitialized.IfDistrue,recordthatthenewlycreated
bindingmaybedeletedbyasubsequentDeleteBindingcall.
4.ReturnNormalCompletion(empty).

8.1.1.1.3 CreateImmutableBinding(N,S)

TheconcreteEnvironmentRecordmethodCreateImmutableBindingfordeclarativeEnvironmentRecordscreatesanew
immutablebindingforthenameNthatisuninitialized.AbindingmustnotalreadyexistinthisEnvironmentRecordforN.If
theBooleanargumentShasthevaluetruethenewbindingismarkedasastrictbinding.

1.LetenvRecbethedeclarativeEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRecdoesnotalreadyhaveabindingforN.
3.CreateanimmutablebindinginenvRecforNandrecordthatitisuninitialized.IfSistrue,recordthatthenewlycreated
bindingisastrictbinding.
4.ReturnNormalCompletion(empty).

8.1.1.1.4 InitializeBinding(N,V)

TheconcreteEnvironmentRecordmethodInitializeBindingfordeclarativeEnvironmentRecordsisusedtosetthebound
valueofthecurrentbindingoftheidentiierwhosenameisthevalueoftheargumentNtothevalueofargumentV.An
uninitializedbindingforNmustalreadyexist.

1.LetenvRecbethedeclarativeEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRecmusthaveanuninitializedbindingforN.
3.SettheboundvalueforNinenvRectoV.
4.RecordthatthebindingforNinenvRechasbeeninitialized.
5.ReturnNormalCompletion(empty).

8.1.1.1.5 SetMutableBinding(N,V,S)

TheconcreteEnvironmentRecordmethodSetMutableBindingfordeclarativeEnvironmentRecordsattemptstochangethe
boundvalueofthecurrentbindingoftheidentiierwhosenameisthevalueoftheargumentNtothevalueofargumentV.A
bindingforNnormallyalreadyexist,butinrarecasesitmaynot.Ifthebindingisanimmutablebinding,aTypeErroris
thrownifSistrue.

1.LetenvRecbethedeclarativeEnvironmentRecordforwhichthemethodwasinvoked.
2.IfenvRecdoesnothaveabindingforN,then
a.IfSistrue,throwaReferenceErrorexception.
b.PerformenvRec.CreateMutableBinding(N,true).
c.PerformenvRec.InitializeBinding(N,V).
d.ReturnNormalCompletion(empty).
3.IfthebindingforNinenvRecisastrictbinding,letSbetrue.
4.IfthebindingforNinenvRechasnotyetbeeninitialized,throwaReferenceErrorexception.
5.ElseifthebindingforNinenvRecisamutablebinding,changeitsboundvaluetoV.
6.ElsethismustbeanattempttochangethevalueofanimmutablebindingsoifSistrue,throwaTypeErrorexception.
7.ReturnNormalCompletion(empty).
NOTE AnexampleofECMAScriptcodethatresultsinamissingbindingatstep2is:

functionf(){eval("varx;x=(deletex,0);")}

8.1.1.1.6 GetBindingValue(N,S)

TheconcreteEnvironmentRecordmethodGetBindingValuefordeclarativeEnvironmentRecordssimplyreturnsthevalueof
itsboundidentiierwhosenameisthevalueoftheargumentN.IfthebindingexistsbutisuninitializedaReferenceErroris
thrown,regardlessofthevalueofS.

1.LetenvRecbethedeclarativeEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRechasabindingforN.
3.IfthebindingforNinenvRecisanuninitializedbinding,throwaReferenceErrorexception.
4.ReturnthevaluecurrentlyboundtoNinenvRec.

8.1.1.1.7 DeleteBinding(N)

TheconcreteEnvironmentRecordmethodDeleteBindingfordeclarativeEnvironmentRecordscanonlydeletebindingsthat
havebeenexplicitlydesignatedasbeingsubjecttodeletion.

1.LetenvRecbethedeclarativeEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRechasabindingforthenamethatisthevalueofN.
3.IfthebindingforNinenvReccannotbedeleted,returnfalse.
4.RemovethebindingforNfromenvRec.
5.Returntrue.

8.1.1.1.8 HasThisBinding()

RegulardeclarativeEnvironmentRecordsdonotprovideathisbinding.

1.Returnfalse.

8.1.1.1.9 HasSuperBinding()

RegulardeclarativeEnvironmentRecordsdonotprovideasuperbinding.

1.Returnfalse.

8.1.1.1.10 WithBaseObject()

DeclarativeEnvironmentRecordsalwaysreturnundeinedastheirWithBaseObject.

1.Returnundeined.

8.1.1.2 ObjectEnvironmentRecords

EachobjectEnvironmentRecordisassociatedwithanobjectcalleditsbindingobject.AnobjectEnvironmentRecordbinds
thesetofstringidentiiernamesthatdirectlycorrespondtothepropertynamesofitsbindingobject.Propertykeysthatare
notstringsintheformofanIdentiierNamearenotincludedinthesetofboundidentiiers.Bothownandinherited
propertiesareincludedinthesetregardlessofthesettingoftheir[[Enumerable]]attribute.Becausepropertiescanbe
dynamicallyaddedanddeletedfromobjects,thesetofidentiiersboundbyanobjectEnvironmentRecordmaypotentially
changeasasideeffectofanyoperationthataddsordeletesproperties.Anybindingsthatarecreatedasaresultofsucha
sideeffectareconsideredtobeamutablebindingeveniftheWritableattributeofthecorrespondingpropertyhasthevalue
false.ImmutablebindingsdonotexistforobjectEnvironmentRecords.

ObjectEnvironmentRecordscreatedforwithstatements(13.11)canprovidetheirbindingobjectasanimplicitthisvalue
foruseinfunctioncalls.ThecapabilityiscontrolledbyawithEnvironmentBooleanvaluethatisassociatedwitheachobject
EnvironmentRecord.Bydefault,thevalueofwithEnvironmentisfalseforanyobjectEnvironmentRecord.

ThebehaviouroftheconcretespeciicationmethodsforobjectEnvironmentRecordsisdeinedbythefollowingalgorithms.
8.1.1.2.1 HasBinding(N)

TheconcreteEnvironmentRecordmethodHasBindingforobjectEnvironmentRecordsdeterminesifitsassociatedbinding
objecthasapropertywhosenameisthevalueoftheargumentN:

1.LetenvRecbetheobjectEnvironmentRecordforwhichthemethodwasinvoked.
2.LetbindingsbethebindingobjectforenvRec.
3.LetfoundBindingbe?HasProperty(bindings,N).
4.IffoundBindingisfalse,returnfalse.
5.IfthewithEnvironmentlagofenvRecisfalse,returntrue.
6.Letunscopablesbe?Get(bindings,@@unscopables).
7.IfType(unscopables)isObject,then
a.LetblockedbeToBoolean(?Get(unscopables,N)).
b.Ifblockedistrue,returnfalse.
8.Returntrue.

8.1.1.2.2 CreateMutableBinding(N,D)

TheconcreteEnvironmentRecordmethodCreateMutableBindingforobjectEnvironmentRecordscreatesinanEnvironment
Record'sassociatedbindingobjectapropertywhosenameistheStringvalueandinitializesittothevalueundeined.If
BooleanargumentDhasthevaluetruethenewproperty's[[Conigurable]]attributeissettotrue;otherwiseitissetto
false.

1.LetenvRecbetheobjectEnvironmentRecordforwhichthemethodwasinvoked.
2.LetbindingsbethebindingobjectforenvRec.
3.IfDistrue,letconigValuebetrue;otherwiseletconigValuebefalse.
4.Return?DeinePropertyOrThrow(bindings,N,PropertyDescriptor{[[Value]]:undeined,[[Writable]]:true,
[[Enumerable]]:true,[[Conigurable]]:conigValue}).

NOTE NormallyenvRecwillnothaveabindingforNbutifitdoes,thesemanticsofDeinePropertyOrThrowmay
resultinanexistingbindingbeingreplacedorshadowedorcauseanabruptcompletiontobereturned.

8.1.1.2.3 CreateImmutableBinding(N,S)

TheconcreteEnvironmentRecordmethodCreateImmutableBindingisneverusedwithinthisspeciicationinassociation
withobjectEnvironmentRecords.

8.1.1.2.4 InitializeBinding(N,V)

TheconcreteEnvironmentRecordmethodInitializeBindingforobjectEnvironmentRecordsisusedtosettheboundvalueof
thecurrentbindingoftheidentiierwhosenameisthevalueoftheargumentNtothevalueofargumentV.Anuninitialized
bindingforNmustalreadyexist.

1.LetenvRecbetheobjectEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRecmusthaveanuninitializedbindingforN.
3.RecordthatthebindingforNinenvRechasbeeninitialized.
4.Return?envRec.SetMutableBinding(N,V,false).

NOTE Inthisspeciication,allusesofCreateMutableBindingforobjectEnvironmentRecordsareimmediately
followedbyacalltoInitializeBindingforthesamename.Hence,implementationsdonotneedtoexplicitly
tracktheinitializationstateofindividualobjectEnvironmentRecordbindings.

8.1.1.2.5 SetMutableBinding(N,V,S)

TheconcreteEnvironmentRecordmethodSetMutableBindingforobjectEnvironmentRecordsattemptstosetthevalueof
theEnvironmentRecord'sassociatedbindingobject'spropertywhosenameisthevalueoftheargumentNtothevalueof
argumentV.ApropertynamedNnormallyalreadyexistsbutifitdoesnotorisnotcurrentlywritable,errorhandlingis
determinedbythevalueoftheBooleanargumentS.
1.LetenvRecbetheobjectEnvironmentRecordforwhichthemethodwasinvoked.
2.LetbindingsbethebindingobjectforenvRec.
3.Return?Set(bindings,N,V,S).

8.1.1.2.6 GetBindingValue(N,S)

TheconcreteEnvironmentRecordmethodGetBindingValueforobjectEnvironmentRecordsreturnsthevalueofits
associatedbindingobject'spropertywhosenameistheStringvalueoftheargumentidentiierN.Thepropertyshould
alreadyexistbutifitdoesnottheresultdependsuponthevalueoftheSargument:

1.LetenvRecbetheobjectEnvironmentRecordforwhichthemethodwasinvoked.
2.LetbindingsbethebindingobjectforenvRec.
3.Letvaluebe?HasProperty(bindings,N).
4.Ifvalueisfalse,then
a.IfSisfalse,returnthevalueundeined;otherwisethrowaReferenceErrorexception.
5.Return?Get(bindings,N).

8.1.1.2.7 DeleteBinding(N)

TheconcreteEnvironmentRecordmethodDeleteBindingforobjectEnvironmentRecordscanonlydeletebindingsthat
correspondtopropertiesoftheenvironmentobjectwhose[[Conigurable]]attributehavethevaluetrue.

1.LetenvRecbetheobjectEnvironmentRecordforwhichthemethodwasinvoked.
2.LetbindingsbethebindingobjectforenvRec.
3.Return?bindings.[[Delete]](N).

8.1.1.2.8 HasThisBinding()

RegularobjectEnvironmentRecordsdonotprovideathisbinding.

1.Returnfalse.

8.1.1.2.9 HasSuperBinding()

RegularobjectEnvironmentRecordsdonotprovideasuperbinding.

1.Returnfalse.

8.1.1.2.10 WithBaseObject()

ObjectEnvironmentRecordsreturnundeinedastheirWithBaseObjectunlesstheirwithEnvironmentlagistrue.

1.LetenvRecbetheobjectEnvironmentRecordforwhichthemethodwasinvoked.
2.IfthewithEnvironmentlagofenvRecistrue,returnthebindingobjectforenvRec.
3.Otherwise,returnundeined.

8.1.1.3 FunctionEnvironmentRecords

AfunctionEnvironmentRecordisadeclarativeEnvironmentRecordthatisusedtorepresentthetoplevelscopeofa
functionand,ifthefunctionisnotanArrowFunction,providesathisbinding.IfafunctionisnotanArrowFunctionfunction
andreferencessuper,itsfunctionEnvironmentRecordalsocontainsthestatethatisusedtoperformsupermethod
invocationsfromwithinthefunction.

FunctionEnvironmentRecordshavetheadditionalstateieldslistedinTable16.
Table16:AdditionalFieldsofFunctionEnvironmentRecords
FieldName Value Meaning

[[ThisValue]] Any Thisisthethisvalueusedforthisinvocationofthefunction.

[[ThisBindingStatus]] "lexical"| Ifthevalueis"lexical",thisisanArrowFunctionanddoesnothavealocal


"initialized"| thisvalue.
"uninitialized"

[[FunctionObject]] Object ThefunctionobjectwhoseinvocationcausedthisEnvironmentRecordtobe


created.

[[HomeObject]] Object|undeined Iftheassociatedfunctionhassuperpropertyaccessesandisnotan


ArrowFunction,[[HomeObject]]istheobjectthatthefunctionisboundtoasa
method.Thedefaultvaluefor[[HomeObject]]isundeined.

[[NewTarget]] Object|undeined IfthisEnvironmentRecordwascreatedbythe[[Construct]]internalmethod,


[[NewTarget]]isthevalueofthe[[Construct]]newTargetparameter.
Otherwise,itsvalueisundeined.

FunctionEnvironmentRecordssupportallofthedeclarativeEnvironmentRecordmethodslistedinTable15andsharethe
samespeciicationsforallofthosemethodsexceptforHasThisBindingandHasSuperBinding.Inaddition,function
EnvironmentRecordssupportthemethodslistedinTable17:

Table17:AdditionalMethodsofFunctionEnvironmentRecords
Method Purpose

BindThisValue(V) Setthe[[ThisValue]]andrecordthatithasbeeninitialized.

GetThisBinding() ReturnthevalueofthisEnvironmentRecord'sthisbinding.ThrowsaReferenceErrorifthethis
bindinghasnotbeeninitialized.

GetSuperBase() ReturntheobjectthatisthebaseforsuperpropertyaccessesboundinthisEnvironmentRecord.The
objectisderivedfromthisEnvironmentRecord's[[HomeObject]]ield.Thevalueundeinedindicates
thatsuperpropertyaccesseswillproduceruntimeerrors.

ThebehaviouroftheadditionalconcretespeciicationmethodsforfunctionEnvironmentRecordsisdeinedbythefollowing
algorithms:

8.1.1.3.1 BindThisValue(V)

1.LetenvRecbethefunctionEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRec.[[ThisBindingStatus]]isnot"lexical".
3.IfenvRec.[[ThisBindingStatus]]is"initialized",throwaReferenceErrorexception.
4.SetenvRec.[[ThisValue]]toV.
5.SetenvRec.[[ThisBindingStatus]]to"initialized".
6.ReturnV.

8.1.1.3.2 HasThisBinding()

1.LetenvRecbethefunctionEnvironmentRecordforwhichthemethodwasinvoked.
2.IfenvRec.[[ThisBindingStatus]]is"lexical",returnfalse;otherwise,returntrue.

8.1.1.3.3 HasSuperBinding()

1.LetenvRecbethefunctionEnvironmentRecordforwhichthemethodwasinvoked.
2.IfenvRec.[[ThisBindingStatus]]is"lexical",returnfalse.
3.IfenvRec.[[HomeObject]]hasthevalueundeined,returnfalse;otherwise,returntrue.

8.1.1.3.4 GetThisBinding()

1.LetenvRecbethefunctionEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRec.[[ThisBindingStatus]]isnot"lexical".
3.IfenvRec.[[ThisBindingStatus]]is"uninitialized",throwaReferenceErrorexception.
4.ReturnenvRec.[[ThisValue]].

8.1.1.3.5 GetSuperBase()

1.LetenvRecbethefunctionEnvironmentRecordforwhichthemethodwasinvoked.
2.LethomebethevalueofenvRec.[[HomeObject]].
3.Ifhomehasthevalueundeined,returnundeined.
4.Assert:Type(home)isObject.
5.Return?home.[[GetPrototypeOf]]().

8.1.1.4 GlobalEnvironmentRecords

AglobalEnvironmentRecordisusedtorepresenttheoutermostscopethatissharedbyalloftheECMAScriptScript
elementsthatareprocessedinacommonrealm.AglobalEnvironmentRecordprovidesthebindingsforbuiltinglobals
(clause18),propertiesoftheglobalobject,andforalltopleveldeclarations(13.2.8,13.2.10)thatoccurwithinaScript.

AglobalEnvironmentRecordislogicallyasinglerecordbutitisspeciiedasacompositeencapsulatinganobject
EnvironmentRecordandadeclarativeEnvironmentRecord.TheobjectEnvironmentRecordhasasitsbaseobjecttheglobal
objectoftheassociatedRealmRecord.ThisglobalobjectisthevaluereturnedbytheglobalEnvironmentRecord's
GetThisBindingconcretemethod.TheobjectEnvironmentRecordcomponentofaglobalEnvironmentRecordcontainsthe
bindingsforallbuiltinglobals(clause18)andallbindingsintroducedbyaFunctionDeclaration,GeneratorDeclaration,or
VariableStatementcontainedinglobalcode.ThebindingsforallotherECMAScriptdeclarationsinglobalcodearecontained
inthedeclarativeEnvironmentRecordcomponentoftheglobalEnvironmentRecord.

Propertiesmaybecreateddirectlyonaglobalobject.Hence,theobjectEnvironmentRecordcomponentofaglobal
EnvironmentRecordmaycontainbothbindingscreatedexplicitlybyFunctionDeclaration,GeneratorDeclaration,or
VariableDeclarationdeclarationsandbindingscreatedimplicitlyaspropertiesoftheglobalobject.Inordertoidentifywhich
bindingswereexplicitlycreatedusingdeclarations,aglobalEnvironmentRecordmaintainsalistofthenamesboundusing
itsCreateGlobalVarBindingandCreateGlobalFunctionBindingconcretemethods.

GlobalEnvironmentRecordshavetheadditionalieldslistedinTable18andtheadditionalmethodslistedinTable19.

Table18:AdditionalFieldsofGlobalEnvironmentRecords
FieldName Value Meaning

[[ObjectRecord]] Object Bindingobjectistheglobalobject.Itcontainsglobalbuiltinbindingsaswellas


Environment FunctionDeclaration,GeneratorDeclaration,andVariableDeclarationbindingsin
Record globalcodefortheassociatedrealm.

[[GlobalThisValue]] Object Thevaluereturnedbythisinglobalscope.HostsmayprovideanyECMAScript


Objectvalue.

[[DeclarativeRecord]] Declarative Containsbindingsforalldeclarationsinglobalcodefortheassociatedrealmcode


Environment exceptforFunctionDeclaration,GeneratorDeclaration,andVariableDeclaration
Record bindings.

[[VarNames]] ListofString ThestringnamesboundbyFunctionDeclaration,GeneratorDeclaration,and


VariableDeclarationdeclarationsinglobalcodefortheassociatedrealm.
Table19:AdditionalMethodsofGlobalEnvironmentRecords
Method Purpose

GetThisBinding() ReturnthevalueofthisEnvironmentRecord'sthisbinding.

HasVarDeclaration(N) DeterminesiftheargumentidentiierhasabindinginthisEnvironmentRecordthatwas
createdusingaVariableDeclaration,FunctionDeclaration,orGeneratorDeclaration.

HasLexicalDeclaration(N) DeterminesiftheargumentidentiierhasabindinginthisEnvironmentRecordthatwas
createdusingalexicaldeclarationsuchasaLexicalDeclarationoraClassDeclaration.

HasRestrictedGlobalProperty Determinesiftheargumentisthenameofaglobalobjectpropertythatmaynotbe
(N) shadowedbyagloballexicallybinding.

CanDeclareGlobalVar(N) DeterminesifacorrespondingCreateGlobalVarBindingcallwouldsucceedifcalledfor
thesameargumentN.

CanDeclareGlobalFunction(N) DeterminesifacorrespondingCreateGlobalFunctionBindingcallwouldsucceedifcalled
forthesameargumentN.

CreateGlobalVarBinding(N,D) Usedtocreateandinitializetoundeinedaglobalvarbindinginthe[[ObjectRecord]]
componentofaglobalEnvironmentRecord.Thebindingwillbeamutablebinding.The
correspondingglobalobjectpropertywillhaveattributevaluesappropriateforavar.
TheStringvalueNistheboundname.IfDistruethebindingmaybedeleted.Logically
equivalenttoCreateMutableBindingfollowedbyaSetMutableBindingbutitallowsvar
declarationstoreceivespecialtreatment.

CreateGlobalFunctionBinding(N, Createandinitializeaglobalfunctionbindinginthe[[ObjectRecord]]componentofa
V,D) globalEnvironmentRecord.Thebindingwillbeamutablebinding.Thecorresponding
globalobjectpropertywillhaveattributevaluesappropriateforafunction.TheString
valueNistheboundname.Vistheinitializationvalue.IftheBooleanargumentDistrue
thebindingmaybedeleted.LogicallyequivalenttoCreateMutableBindingfollowedbya
SetMutableBindingbutitallowsfunctiondeclarationstoreceivespecialtreatment.

ThebehaviouroftheconcretespeciicationmethodsforglobalEnvironmentRecordsisdeinedbythefollowingalgorithms.

8.1.1.4.1 HasBinding(N)

TheconcreteEnvironmentRecordmethodHasBindingforglobalEnvironmentRecordssimplydeterminesiftheargument
identiierisoneoftheidentiiersboundbytherecord:

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.IfDclRec.HasBinding(N)istrue,returntrue.
4.LetObjRecbeenvRec.[[ObjectRecord]].
5.Return?ObjRec.HasBinding(N).

8.1.1.4.2 CreateMutableBinding(N,D)

TheconcreteEnvironmentRecordmethodCreateMutableBindingforglobalEnvironmentRecordscreatesanewmutable
bindingforthenameNthatisuninitialized.ThebindingiscreatedintheassociatedDeclarativeRecord.AbindingforNmust
notalreadyexistintheDeclarativeRecord.IfBooleanargumentDhasthevaluetruethenewbindingismarkedasbeing
subjecttodeletion.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.IfDclRec.HasBinding(N)istrue,throwaTypeErrorexception.
4.ReturnDclRec.CreateMutableBinding(N,D).
8.1.1.4.3 CreateImmutableBinding(N,S)

TheconcreteEnvironmentRecordmethodCreateImmutableBindingforglobalEnvironmentRecordscreatesanew
immutablebindingforthenameNthatisuninitialized.AbindingmustnotalreadyexistinthisEnvironmentRecordforN.If
theBooleanargumentShasthevaluetruethenewbindingismarkedasastrictbinding.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.IfDclRec.HasBinding(N)istrue,throwaTypeErrorexception.
4.ReturnDclRec.CreateImmutableBinding(N,S).

8.1.1.4.4 InitializeBinding(N,V)

TheconcreteEnvironmentRecordmethodInitializeBindingforglobalEnvironmentRecordsisusedtosettheboundvalueof
thecurrentbindingoftheidentiierwhosenameisthevalueoftheargumentNtothevalueofargumentV.Anuninitialized
bindingforNmustalreadyexist.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.IfDclRec.HasBinding(N)istrue,then
a.ReturnDclRec.InitializeBinding(N,V).
4.Assert:Ifthebindingexists,itmustbeintheobjectEnvironmentRecord.
5.LetObjRecbeenvRec.[[ObjectRecord]].
6.Return?ObjRec.InitializeBinding(N,V).

8.1.1.4.5 SetMutableBinding(N,V,S)

TheconcreteEnvironmentRecordmethodSetMutableBindingforglobalEnvironmentRecordsattemptstochangethebound
valueofthecurrentbindingoftheidentiierwhosenameisthevalueoftheargumentNtothevalueofargumentV.Ifthe
bindingisanimmutablebinding,aTypeErroristhrownifSistrue.ApropertynamedNnormallyalreadyexistsbutifit
doesnotorisnotcurrentlywritable,errorhandlingisdeterminedbythevalueoftheBooleanargumentS.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.IfDclRec.HasBinding(N)istrue,then
a.ReturnDclRec.SetMutableBinding(N,V,S).
4.LetObjRecbeenvRec.[[ObjectRecord]].
5.Return?ObjRec.SetMutableBinding(N,V,S).

8.1.1.4.6 GetBindingValue(N,S)

TheconcreteEnvironmentRecordmethodGetBindingValueforglobalEnvironmentRecordsreturnsthevalueofitsbound
identiierwhosenameisthevalueoftheargumentN.IfthebindingisanuninitializedbindingthrowaReferenceError
exception.ApropertynamedNnormallyalreadyexistsbutifitdoesnotorisnotcurrentlywritable,errorhandlingis
determinedbythevalueoftheBooleanargumentS.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.IfDclRec.HasBinding(N)istrue,then
a.ReturnDclRec.GetBindingValue(N,S).
4.LetObjRecbeenvRec.[[ObjectRecord]].
5.Return?ObjRec.GetBindingValue(N,S).

8.1.1.4.7 DeleteBinding(N)

TheconcreteEnvironmentRecordmethodDeleteBindingforglobalEnvironmentRecordscanonlydeletebindingsthathave
beenexplicitlydesignatedasbeingsubjecttodeletion.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.IfDclRec.HasBinding(N)istrue,then
a.ReturnDclRec.DeleteBinding(N).
4.LetObjRecbeenvRec.[[ObjectRecord]].
5.LetglobalObjectbethebindingobjectforObjRec.
6.LetexistingPropbe?HasOwnProperty(globalObject,N).
7.IfexistingPropistrue,then
a.Letstatusbe?ObjRec.DeleteBinding(N).
b.Ifstatusistrue,then
i.LetvarNamesbeenvRec.[[VarNames]].
ii.IfNisanelementofvarNames,removethatelementfromthevarNames.
c.Returnstatus.
8.Returntrue.

8.1.1.4.8 HasThisBinding()

1.Returntrue.

8.1.1.4.9 HasSuperBinding()

1.Returnfalse.

8.1.1.4.10 WithBaseObject()

GlobalEnvironmentRecordsalwaysreturnundeinedastheirWithBaseObject.

1.Returnundeined.

8.1.1.4.11 GetThisBinding()

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.ReturnenvRec.[[GlobalThisValue]].

8.1.1.4.12 HasVarDeclaration(N)

TheconcreteEnvironmentRecordmethodHasVarDeclarationforglobalEnvironmentRecordsdeterminesiftheargument
identiierhasabindinginthisrecordthatwascreatedusingaVariableStatementoraFunctionDeclaration:

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetvarDeclaredNamesbeenvRec.[[VarNames]].
3.IfvarDeclaredNamescontainsthevalueofN,returntrue.
4.Returnfalse.

8.1.1.4.13 HasLexicalDeclaration(N)

TheconcreteEnvironmentRecordmethodHasLexicalDeclarationforglobalEnvironmentRecordsdeterminesifthe
argumentidentiierhasabindinginthisrecordthatwascreatedusingalexicaldeclarationsuchasaLexicalDeclarationora
ClassDeclaration:

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetDclRecbeenvRec.[[DeclarativeRecord]].
3.ReturnDclRec.HasBinding(N).

8.1.1.4.14 HasRestrictedGlobalProperty(N)

TheconcreteEnvironmentRecordmethodHasRestrictedGlobalPropertyforglobalEnvironmentRecordsdeterminesifthe
argumentidentiieristhenameofapropertyoftheglobalobjectthatmustnotbeshadowedbyagloballexicallybinding:

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetObjRecbeenvRec.[[ObjectRecord]].
3.LetglobalObjectbethebindingobjectforObjRec.
4.LetexistingPropbe?globalObject.[[GetOwnProperty]](N).
5.IfexistingPropisundeined,returnfalse.
6.IfexistingProp.[[Conigurable]]istrue,returnfalse.
7.Returntrue.

NOTE Propertiesmayexistuponaglobalobjectthatweredirectlycreatedratherthanbeingdeclaredusingavaror
functiondeclaration.Agloballexicalbindingmaynotbecreatedthathasthesamenameasanonconigurable
propertyoftheglobalobject.Theglobalpropertyundefinedisanexampleofsuchaproperty.

8.1.1.4.15 CanDeclareGlobalVar(N)

TheconcreteEnvironmentRecordmethodCanDeclareGlobalVarforglobalEnvironmentRecordsdeterminesifa
correspondingCreateGlobalVarBindingcallwouldsucceedifcalledforthesameargumentN.Redundantvardeclarations
andvardeclarationsforpreexistingglobalobjectpropertiesareallowed.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetObjRecbeenvRec.[[ObjectRecord]].
3.LetglobalObjectbethebindingobjectforObjRec.
4.LethasPropertybe?HasOwnProperty(globalObject,N).
5.IfhasPropertyistrue,returntrue.
6.Return?IsExtensible(globalObject).

8.1.1.4.16 CanDeclareGlobalFunction(N)

TheconcreteEnvironmentRecordmethodCanDeclareGlobalFunctionforglobalEnvironmentRecordsdeterminesifa
correspondingCreateGlobalFunctionBindingcallwouldsucceedifcalledforthesameargumentN.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetObjRecbeenvRec.[[ObjectRecord]].
3.LetglobalObjectbethebindingobjectforObjRec.
4.LetexistingPropbe?globalObject.[[GetOwnProperty]](N).
5.IfexistingPropisundeined,return?IsExtensible(globalObject).
6.IfexistingProp.[[Conigurable]]istrue,returntrue.
7.IfIsDataDescriptor(existingProp)istrueandexistingProphasattributevalues{[[Writable]]:true,[[Enumerable]]:
true},returntrue.
8.Returnfalse.

8.1.1.4.17 CreateGlobalVarBinding(N,D)

TheconcreteEnvironmentRecordmethodCreateGlobalVarBindingforglobalEnvironmentRecordscreatesandinitializesa
mutablebindingintheassociatedobjectEnvironmentRecordandrecordstheboundnameintheassociated[[VarNames]]
List.Ifabindingalreadyexists,itisreusedandassumedtobeinitialized.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetObjRecbeenvRec.[[ObjectRecord]].
3.LetglobalObjectbethebindingobjectforObjRec.
4.LethasPropertybe?HasOwnProperty(globalObject,N).
5.Letextensiblebe?IsExtensible(globalObject).
6.IfhasPropertyisfalseandextensibleistrue,then
a.Perform?ObjRec.CreateMutableBinding(N,D).
b.Perform?ObjRec.InitializeBinding(N,undeined).
7.LetvarDeclaredNamesbeenvRec.[[VarNames]].
8.IfvarDeclaredNamesdoesnotcontainthevalueofN,then
a.AppendNtovarDeclaredNames.
9.ReturnNormalCompletion(empty).
8.1.1.4.18 CreateGlobalFunctionBinding(N,V,D)

TheconcreteEnvironmentRecordmethodCreateGlobalFunctionBindingforglobalEnvironmentRecordscreatesand
initializesamutablebindingintheassociatedobjectEnvironmentRecordandrecordstheboundnameintheassociated
[[VarNames]]List.Ifabindingalreadyexists,itisreplaced.

1.LetenvRecbetheglobalEnvironmentRecordforwhichthemethodwasinvoked.
2.LetObjRecbeenvRec.[[ObjectRecord]].
3.LetglobalObjectbethebindingobjectforObjRec.
4.LetexistingPropbe?globalObject.[[GetOwnProperty]](N).
5.IfexistingPropisundeinedorexistingProp.[[Conigurable]]istrue,then
a.LetdescbethePropertyDescriptor{[[Value]]:V,[[Writable]]:true,[[Enumerable]]:true,[[Conigurable]]:D}.
6.Else,
a.LetdescbethePropertyDescriptor{[[Value]]:V}.
7.Perform?DeinePropertyOrThrow(globalObject,N,desc).
8.RecordthatthebindingforNinObjRechasbeeninitialized.
9.Perform?Set(globalObject,N,V,false).
10.LetvarDeclaredNamesbeenvRec.[[VarNames]].
11.IfvarDeclaredNamesdoesnotcontainthevalueofN,then
a.AppendNtovarDeclaredNames.
12.ReturnNormalCompletion(empty).

NOTE Globalfunctiondeclarationsarealwaysrepresentedasownpropertiesoftheglobalobject.Ifpossible,an
existingownpropertyisreconiguredtohaveastandardsetofattributevalues.Steps1012areequivalentto
whatcallingtheInitializeBindingconcretemethodwoulddoandifglobalObjectisaProxywillproducethe
samesequenceofProxytrapcalls.

8.1.1.5 ModuleEnvironmentRecords

AmoduleEnvironmentRecordisadeclarativeEnvironmentRecordthatisusedtorepresenttheouterscopeofan
ECMAScriptModule.Inadditionaltonormalmutableandimmutablebindings,moduleEnvironmentRecordsalsoprovide
immutableimportbindingswhicharebindingsthatprovideindirectaccesstoatargetbindingthatexistsinanother
EnvironmentRecord.

ModuleEnvironmentRecordssupportallofthedeclarativeEnvironmentRecordmethodslistedinTable15andsharethe
samespeciicationsforallofthosemethodsexceptforGetBindingValue,DeleteBinding,HasThisBindingandGetThisBinding.
Inaddition,moduleEnvironmentRecordssupportthemethodslistedinTable20:

Table20:AdditionalMethodsofModuleEnvironmentRecords
Method Purpose

CreateImportBinding(N, CreateanimmutableindirectbindinginamoduleEnvironmentRecord.TheStringvalueNisthe
M,N2) textoftheboundname.MisaModuleRecord,andN2isabindingthatexistsinM'smodule
EnvironmentRecord.

GetThisBinding() ReturnthevalueofthisEnvironmentRecord'sthisbinding.

ThebehaviouroftheadditionalconcretespeciicationmethodsformoduleEnvironmentRecordsaredeinedbythe
followingalgorithms:

8.1.1.5.1 GetBindingValue(N,S)

TheconcreteEnvironmentRecordmethodGetBindingValueformoduleEnvironmentRecordsreturnsthevalueofitsbound
identiierwhosenameisthevalueoftheargumentN.However,ifthebindingisanindirectbindingthevalueofthetarget
bindingisreturned.IfthebindingexistsbutisuninitializedaReferenceErroristhrown,regardlessofthevalueofS.
1.LetenvRecbethemoduleEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRechasabindingforN.
3.IfthebindingforNisanindirectbinding,then
a.LetMandN2betheindirectionvaluesprovidedwhenthisbindingforNwascreated.
b.LettargetEnvbeM.[[Environment]].
c.IftargetEnvisundeined,throwaReferenceErrorexception.
d.LettargetERbetargetEnv'sEnvironmentRecord.
e.Return?targetER.GetBindingValue(N2,S).
4.IfthebindingforNinenvRecisanuninitializedbinding,throwaReferenceErrorexception.
5.ReturnthevaluecurrentlyboundtoNinenvRec.

NOTE BecauseaModuleisalwaysstrictmodecode,callstoGetBindingValueshouldalwayspasstrueasthevalueof
S.

8.1.1.5.2 DeleteBinding(N)

TheconcreteEnvironmentRecordmethodDeleteBindingformoduleEnvironmentRecordsrefusestodeletebindings.

1.LetenvRecbethemoduleEnvironmentRecordforwhichthemethodwasinvoked.
2.IfenvRecdoesnothaveabindingforthenamethatisthevalueofN,returntrue.
3.Returnfalse.

NOTE ThebindingsofamoduleEnvironmentRecordarenotdeletable.

8.1.1.5.3 HasThisBinding()

ModuleEnvironmentRecordsprovideathisbinding.

1.Returntrue.

8.1.1.5.4 GetThisBinding()

1.Returnundeined.

8.1.1.5.5 CreateImportBinding(N,M,N2)

TheconcreteEnvironmentRecordmethodCreateImportBindingformoduleEnvironmentRecordscreatesanewinitialized
immutableindirectbindingforthenameN.AbindingmustnotalreadyexistinthisEnvironmentRecordforN.MisaModule
Record,andN2isthenameofabindingthatexistsinM'smoduleEnvironmentRecord.Accessestothevalueofthenew
bindingwillindirectlyaccesstheboundvalueofthetargetbinding.

1.LetenvRecbethemoduleEnvironmentRecordforwhichthemethodwasinvoked.
2.Assert:envRecdoesnotalreadyhaveabindingforN.
3.Assert:MisaModuleRecord.
4.Assert:WhenM.[[Environment]]isinstantiateditwillhaveadirectbindingforN2.
5.CreateanimmutableindirectbindinginenvRecforNthatreferencesMandN2asitstargetbindingandrecordthatthe
bindingisinitialized.
6.ReturnNormalCompletion(empty).

8.1.2 LexicalEnvironmentOperations

Thefollowingabstractoperationsareusedinthisspeciicationtooperateuponlexicalenvironments:

8.1.2.1 GetIdentiierReference(lex,name,strict)

TheabstractoperationGetIdentiierReferenceiscalledwithaLexicalEnvironmentlex,aStringname,andaBooleanlag
strict.Thevalueoflexmaybenull.Whencalled,thefollowingstepsareperformed:

1.Iflexisthevaluenull,then
a.ReturnavalueoftypeReferencewhosebasevalueisundeined,whosereferencednameisname,andwhose
strictreferencelagisstrict.
2.LetenvRecbelex'sEnvironmentRecord.
3.Letexistsbe?envRec.HasBinding(name).
4.Ifexistsistrue,then
a.ReturnavalueoftypeReferencewhosebasevalueisenvRec,whosereferencednameisname,andwhosestrict
referencelagisstrict.
5.Else,
a.Letouterbethevalueoflex'souterenvironmentreference.
b.Return?GetIdentiierReference(outer,name,strict).

8.1.2.2 NewDeclarativeEnvironment(E)

WhentheabstractoperationNewDeclarativeEnvironmentiscalledwithaLexicalEnvironmentasargumentEthefollowing
stepsareperformed:

1.LetenvbeanewLexicalEnvironment.
2.LetenvRecbeanewdeclarativeEnvironmentRecordcontainingnobindings.
3.Setenv'sEnvironmentRecordtoenvRec.
4.SettheouterlexicalenvironmentreferenceofenvtoE.
5.Returnenv.

8.1.2.3 NewObjectEnvironment(O,E)

WhentheabstractoperationNewObjectEnvironmentiscalledwithanObjectOandaLexicalEnvironmentEasarguments,
thefollowingstepsareperformed:

1.LetenvbeanewLexicalEnvironment.
2.LetenvRecbeanewobjectEnvironmentRecordcontainingOasthebindingobject.
3.Setenv'sEnvironmentRecordtoenvRec.
4.SettheouterlexicalenvironmentreferenceofenvtoE.
5.Returnenv.

8.1.2.4 NewFunctionEnvironment(F,newTarget)

WhentheabstractoperationNewFunctionEnvironmentiscalledwithargumentsFandnewTargetthefollowingstepsare
performed:

1.Assert:FisanECMAScriptfunction.
2.Assert:Type(newTarget)isUndeinedorObject.
3.LetenvbeanewLexicalEnvironment.
4.LetenvRecbeanewfunctionEnvironmentRecordcontainingnobindings.
5.SetenvRec.[[FunctionObject]]toF.
6.IfF's[[ThisMode]]internalslotislexical,setenvRec.[[ThisBindingStatus]]to"lexical".
7.Else,setenvRec.[[ThisBindingStatus]]to"uninitialized".
8.LethomebethevalueofF's[[HomeObject]]internalslot.
9.SetenvRec.[[HomeObject]]tohome.
10.SetenvRec.[[NewTarget]]tonewTarget.
11.Setenv'sEnvironmentRecordtoenvRec.
12.SettheouterlexicalenvironmentreferenceofenvtothevalueofF's[[Environment]]internalslot.
13.Returnenv.

8.1.2.5 NewGlobalEnvironment(G,thisValue)

WhentheabstractoperationNewGlobalEnvironmentiscalledwithargumentsGandthisValue,thefollowingstepsare
performed:
1.LetenvbeanewLexicalEnvironment.
2.LetobjRecbeanewobjectEnvironmentRecordcontainingGasthebindingobject.
3.LetdclRecbeanewdeclarativeEnvironmentRecordcontainingnobindings.
4.LetglobalRecbeanewglobalEnvironmentRecord.
5.SetglobalRec.[[ObjectRecord]]toobjRec.
6.SetglobalRec.[[GlobalThisValue]]tothisValue.
7.SetglobalRec.[[DeclarativeRecord]]todclRec.
8.SetglobalRec.[[VarNames]]toanewemptyList.
9.Setenv'sEnvironmentRecordtoglobalRec.
10.Settheouterlexicalenvironmentreferenceofenvtonull.
11.Returnenv.

8.1.2.6 NewModuleEnvironment(E)

WhentheabstractoperationNewModuleEnvironmentiscalledwithaLexicalEnvironmentargumentEthefollowingsteps
areperformed:

1.LetenvbeanewLexicalEnvironment.
2.LetenvRecbeanewmoduleEnvironmentRecordcontainingnobindings.
3.Setenv'sEnvironmentRecordtoenvRec.
4.SettheouterlexicalenvironmentreferenceofenvtoE.
5.Returnenv.

8.2 Realms
Beforeitisevaluated,allECMAScriptcodemustbeassociatedwitharealm.Conceptually,arealmconsistsofasetofintrinsic
objects,anECMAScriptglobalenvironment,alloftheECMAScriptcodethatisloadedwithinthescopeofthatglobal
environment,andotherassociatedstateandresources.

ArealmisrepresentedinthisspeciicationasaRealmRecordwiththeieldsspeciiedinTable21:

Table21:RealmRecordFields
FieldName Value Meaning

[[Intrinsics]] Recordwhose Theintrinsicvaluesusedbycodeassociatedwiththisrealm


ieldnamesare
intrinsickeys
andwhose
valuesare
objects

[[GlobalObject]] Object Theglobalobjectforthisrealm

[[GlobalEnv]] Lexical Theglobalenvironmentforthisrealm


Environment

[[TemplateMap]] AListofRecord{ TemplateobjectsarecanonicalizedseparatelyforeachrealmusingitsRealm


[[Strings]]:List, Record's[[TemplateMap]].Each[[Strings]]valueisaListcontaining,insourcetext
[[Array]]: order,therawStringvaluesofaTemplateLiteralthathasbeenevaluated.The
Object}. associated[[Array]]valueisthecorrespondingtemplateobjectthatispassedtoa
tagfunction.

Animplementationmaydeineother,implementationspeciicields.

8.2.1 CreateRealm()
TheabstractoperationCreateRealmwithnoargumentsperformsthefollowingsteps:

1.LetrealmRecbeanewRealmRecord.
2.PerformCreateIntrinsics(realmRec).
3.SetrealmRec.[[GlobalObject]]toundeined.
4.SetrealmRec.[[GlobalEnv]]toundeined.
5.SetrealmRec.[[TemplateMap]]toanewemptyList.
6.ReturnrealmRec.

8.2.2 CreateIntrinsics(realmRec)

WhentheabstractoperationCreateIntrinsicswithargumentrealmRecperformsthefollowingsteps:

1.LetintrinsicsbeanewRecord.
2.SetrealmRec.[[Intrinsics]]tointrinsics.
3.LetobjProtobeObjectCreate(null).
4.Setintrinsics.[[%ObjectPrototype%]]toobjProto.
5.LetthrowerStepsbethealgorithmstepsspeciiedin9.2.7.1forthe%ThrowTypeError%function.
6.LetthrowerbeCreateBuiltinFunction(realmRec,throwerSteps,null).
7.Setintrinsics.[[%ThrowTypeError%]]tothrower.
8.LetnoStepsbeanemptysequenceofalgorithmsteps.
9.LetfuncProtobeCreateBuiltinFunction(realmRec,noSteps,objProto).
10.Setintrinsics.[[%FunctionPrototype%]]tofuncProto.
11.Callthrower.[[SetPrototypeOf]](funcProto).
12.PerformAddRestrictedFunctionProperties(funcProto,realmRec).
13.SetieldsofintrinsicswiththevalueslistedinTable7thathavenotalreadybeenhandledabove.Theieldnamesarethe
nameslistedincolumnoneofthetable.Thevalueofeachieldisanewobjectvaluefullyandrecursivelypopulated
withpropertyvaluesasdeinedbythespeciicationofeachobjectinclauses1826.Allobjectpropertyvaluesarenewly
createdobjectvalues.Allvaluesthatarebuiltinfunctionobjectsarecreatedbyperforming
CreateBuiltinFunction(realmRec,<steps>,<prototype>,<slots>)where<steps>isthedeinitionofthatfunction
providedbythisspeciication,<prototype>isthespeciiedvalueofthefunction's[[Prototype]]internalslotand<slots>
isalistofthenames,ifany,ofthefunction'sspeciiedinternalslots.Thecreationoftheintrinsicsandtheirproperties
mustbeorderedtoavoidanydependenciesuponobjectsthathavenotyetbeencreated.
14.Returnintrinsics.

8.2.3 SetRealmGlobalObject(realmRec,globalObj,thisValue)

TheabstractoperationSetRealmGlobalObjectwithargumentsrealmRec,globalObj,andthisValueperformsthefollowing
steps:

1.IfglobalObjisundeined,then
a.LetintrinsicsberealmRec.[[Intrinsics]].
b.LetglobalObjbeObjectCreate(intrinsics.[[%ObjectPrototype%]]).
2.Assert:Type(globalObj)isObject.
3.IfthisValueisundeined,letthisValuebeglobalObj.
4.SetrealmRec.[[GlobalObject]]toglobalObj.
5.LetnewGlobalEnvbeNewGlobalEnvironment(globalObj,thisValue).
6.SetrealmRec.[[GlobalEnv]]tonewGlobalEnv.
7.ReturnrealmRec.

8.2.4 SetDefaultGlobalBindings(realmRec)

TheabstractoperationSetDefaultGlobalBindingswithargumentrealmRecperformsthefollowingsteps:

1.LetglobalberealmRec.[[GlobalObject]].
2.ForeachpropertyoftheGlobalObjectspeciiedinclause18,do
a.LetnamebetheStringvalueofthepropertyname.
b.Letdescbethefullypopulateddatapropertydescriptorforthepropertycontainingthespeciiedattributesforthe
property.Forpropertieslistedin18.2,18.3,or18.4thevalueofthe[[Value]]attributeisthecorresponding
intrinsicobjectfromrealmRec.
c.Perform?DeinePropertyOrThrow(global,name,desc).
3.Returnglobal.

8.3 ExecutionContexts
AnexecutioncontextisaspeciicationdevicethatisusedtotracktheruntimeevaluationofcodebyanECMAScript
implementation.Atanypointintime,thereisatmostoneexecutioncontextthatisactuallyexecutingcode.Thisisknownas
therunningexecutioncontext.

Theexecutioncontextstackisusedtotrackexecutioncontexts.Therunningexecutioncontextisalwaysthetopelementof
thisstack.Anewexecutioncontextiscreatedwhenevercontrolistransferredfromtheexecutablecodeassociatedwiththe
currentlyrunningexecutioncontexttoexecutablecodethatisnotassociatedwiththatexecutioncontext.Thenewlycreated
executioncontextispushedontothestackandbecomestherunningexecutioncontext.

Anexecutioncontextcontainswhateverimplementationspeciicstateisnecessarytotracktheexecutionprogressofits
associatedcode.EachexecutioncontexthasatleastthestatecomponentslistedinTable22.

Table22:StateComponentsforAllExecutionContexts
Component Purpose

codeevaluation Anystateneededtoperform,suspend,andresumeevaluationofthecodeassociatedwiththisexecution
state context.

Function Ifthisexecutioncontextisevaluatingthecodeofafunctionobject,thenthevalueofthiscomponentis
thatfunctionobject.IfthecontextisevaluatingthecodeofaScriptorModule,thevalueisnull.

Realm TheRealmRecordfromwhichassociatedcodeaccessesECMAScriptresources.

ScriptOrModule TheModuleRecordorScriptRecordfromwhichassociatedcodeoriginates.Ifthereisnooriginating
scriptormodule,asisthecasefortheoriginalexecutioncontextcreatedinInitializeHostDeinedRealm,
thevalueisnull.

Evaluationofcodebytherunningexecutioncontextmaybesuspendedatvariouspointsdeinedwithinthisspeciication.
Oncetherunningexecutioncontexthasbeensuspendedadifferentexecutioncontextmaybecometherunningexecution
contextandcommenceevaluatingitscode.Atsomelatertimeasuspendedexecutioncontextmayagainbecometherunning
executioncontextandcontinueevaluatingitscodeatthepointwhereithadpreviouslybeensuspended.Transitionofthe
runningexecutioncontextstatusamongexecutioncontextsusuallyoccursinstacklikelastin/irstoutmanner.However,
someECMAScriptfeaturesrequirenonLIFOtransitionsoftherunningexecutioncontext.

ThevalueoftheRealmcomponentoftherunningexecutioncontextisalsocalledthecurrentRealmRecord.Thevalueofthe
Functioncomponentoftherunningexecutioncontextisalsocalledtheactivefunctionobject.

ExecutioncontextsforECMAScriptcodehavetheadditionalstatecomponentslistedinTable23.

Table23:AdditionalStateComponentsforECMAScriptCodeExecutionContexts
Component Purpose

LexicalEnvironment IdentiiestheLexicalEnvironmentusedtoresolveidentiierreferencesmadebycodewithinthis
executioncontext.

VariableEnvironment IdentiiestheLexicalEnvironmentwhoseEnvironmentRecordholdsbindingscreatedby
VariableStatementswithinthisexecutioncontext.
TheLexicalEnvironmentandVariableEnvironmentcomponentsofanexecutioncontextarealwaysLexicalEnvironments.
WhenanexecutioncontextiscreateditsLexicalEnvironmentandVariableEnvironmentcomponentsinitiallyhavethesame
value.

ExecutioncontextsrepresentingtheevaluationofgeneratorobjectshavetheadditionalstatecomponentslistedinTable24.

Table24:AdditionalStateComponentsforGeneratorExecutionContexts
Component Purpose

Generator TheGeneratorObjectthatthisexecutioncontextisevaluating.

Inmostsituationsonlytherunningexecutioncontext(thetopoftheexecutioncontextstack)isdirectlymanipulatedby
algorithmswithinthisspeciication.HencewhenthetermsLexicalEnvironment,andVariableEnvironmentareused
withoutqualiicationtheyareinreferencetothosecomponentsoftherunningexecutioncontext.

Anexecutioncontextispurelyaspeciicationmechanismandneednotcorrespondtoanyparticularartefactofan
ECMAScriptimplementation.ItisimpossibleforECMAScriptcodetodirectlyaccessorobserveanexecutioncontext.

8.3.1 GetActiveScriptOrModule()

TheGetActiveScriptOrModuleabstractoperationisusedtodeterminetherunningscriptormodule,basedontheactive
functionobject.GetActiveScriptOrModuleperformsthefollowingsteps:

1.Iftheexecutioncontextstackisempty,returnnull.
2.LetecbethetopmostexecutioncontextontheexecutioncontextstackwhoseFunctioncomponent's
[[ScriptOrModule]]componentisnotnull.
3.Ifsuchanexecutioncontextexists,returnec'sFunctioncomponent's[[ScriptOrModule]]slot'svalue.
4.Otherwise,letecbetherunningexecutioncontext.
5.Assert:ec'sScriptOrModulecomponentisnotnull.
6.Returnec'sScriptOrModulecomponent.

8.3.2 ResolveBinding(name[,env])

TheResolveBindingabstractoperationisusedtodeterminethebindingofnamepassedasaStringvalue.Theoptional
argumentenvcanbeusedtoexplicitlyprovidetheLexicalEnvironmentthatistobesearchedforthebinding.During
executionofECMAScriptcode,ResolveBindingisperformedusingthefollowingalgorithm:

1.Ifenvwasnotpassedorifenvisundeined,then
a.Letenvbetherunningexecutioncontext'sLexicalEnvironment.
2.Assert:envisaLexicalEnvironment.
3.Ifthecodematchingthesyntacticproductionthatisbeingevaluatediscontainedinstrictmodecode,letstrictbetrue,
elseletstrictbefalse.
4.Return?GetIdentiierReference(env,name,strict).

NOTE TheresultofResolveBindingisalwaysaReferencevaluewithitsreferencednamecomponentequaltothe
nameargument.

8.3.3 GetThisEnvironment()

TheabstractoperationGetThisEnvironmentindstheEnvironmentRecordthatcurrentlysuppliesthebindingofthe
keywordthis.GetThisEnvironmentperformsthefollowingsteps:

1.Letlexbetherunningexecutioncontext'sLexicalEnvironment.
2.Repeat
a.LetenvRecbelex'sEnvironmentRecord.
b.LetexistsbeenvRec.HasThisBinding().
c.Ifexistsistrue,returnenvRec.
d.Letouterbethevalueoflex'souterenvironmentreference.
e.Letlexbeouter.

NOTE Theloopinstep2willalwaysterminatebecausethelistofenvironmentsalwaysendswiththeglobal
environmentwhichhasathisbinding.

8.3.4 ResolveThisBinding()

TheabstractoperationResolveThisBindingdeterminesthebindingofthekeywordthisusingtheLexicalEnvironmentofthe
runningexecutioncontext.ResolveThisBindingperformsthefollowingsteps:

1.LetenvRecbeGetThisEnvironment().
2.Return?envRec.GetThisBinding().

8.3.5 GetNewTarget()

TheabstractoperationGetNewTargetdeterminestheNewTargetvalueusingtheLexicalEnvironmentoftherunning
executioncontext.GetNewTargetperformsthefollowingsteps:

1.LetenvRecbeGetThisEnvironment().
2.Assert:envRechasa[[NewTarget]]ield.
3.ReturnenvRec.[[NewTarget]].

8.3.6 GetGlobalObject()

TheabstractoperationGetGlobalObjectreturnstheglobalobjectusedbythecurrentlyrunningexecutioncontext.
GetGlobalObjectperformsthefollowingsteps:

1.Letctxbetherunningexecutioncontext.
2.LetcurrentRealmbectx'sRealm.
3.ReturncurrentRealm.[[GlobalObject]].

8.4 JobsandJobQueues
AJobisanabstractoperationthatinitiatesanECMAScriptcomputationwhennootherECMAScriptcomputationiscurrently
inprogress.AJobabstractoperationmaybedeinedtoacceptanarbitrarysetofjobparameters.

ExecutionofaJobcanbeinitiatedonlywhenthereisnorunningexecutioncontextandtheexecutioncontextstackisempty.
APendingJobisarequestforthefutureexecutionofaJob.APendingJobisaninternalRecordwhoseieldsarespeciiedin
Table25.OnceexecutionofaJobisinitiated,theJobalwaysexecutestocompletion.NootherJobmaybeinitiateduntilthe
currentlyrunningJobcompletes.However,thecurrentlyrunningJoborexternaleventsmaycausetheenqueuingof
additionalPendingJobsthatmaybeinitiatedsometimeaftercompletionofthecurrentlyrunningJob.
Table25:PendingJobRecordFields
FieldName Value Meaning

[[Job]] Thenameofa ThisistheabstractoperationthatisperformedwhenexecutionofthisPendingJobis


Jobabstract initiated.JobsareabstractoperationsthatuseNextJobratherthanReturnto
operation indicatethattheyhavecompleted.

[[Arguments]] AList TheListofargumentvaluesthataretobepassedto[[Job]]whenitisactivated.

[[Realm]] ARealm TheRealmRecordfortheinitialexecutioncontextwhenthisPendingJobisinitiated.


Record

[[ScriptOrModule]] AScript ThescriptormodulefortheinitialexecutioncontextwhenthisPendingJobis


Recordor initiated.
Module
Record

[[HostDeined]] Any,default Fieldreservedforusebyhostenvironmentsthatneedtoassociateadditional


valueis informationwithapendingJob.
undeined.

AJobQueueisaFIFOqueueofPendingJobrecords.EachJobQueuehasanameandthefullsetofavailableJobQueuesare
deinedbyanECMAScriptimplementation.EveryECMAScriptimplementationhasatleasttheJobQueuesdeinedinTable
26.

Table26:RequiredJobQueues
Name Purpose

ScriptJobs JobsthatvalidateandevaluateECMAScriptScriptandModulesourcetext.Seeclauses10and15.

PromiseJobs JobsthatareresponsestothesettlementofaPromise(see25.4).

ArequestforthefutureexecutionofaJobismadebyenqueueing,onaJobQueue,aPendingJobrecordthatincludesaJob
abstractoperationnameandanynecessaryargumentvalues.Whenthereisnorunningexecutioncontextandtheexecution
contextstackisempty,theECMAScriptimplementationremovestheirstPendingJobfromaJobQueueandusesthe
informationcontainedinittocreateanexecutioncontextandstartsexecutionoftheassociatedJobabstractoperation.

ThePendingJobrecordsfromasingleJobQueuearealwaysinitiatedinFIFOorder.Thisspeciicationdoesnotdeinethe
orderinwhichmultipleJobQueuesareserviced.AnECMAScriptimplementationmayinterweavetheFIFOevaluationofthe
PendingJobrecordsofaJobQueuewiththeevaluationofthePendingJobrecordsofoneormoreotherJobQueues.An
implementationmustdeinewhatoccurswhentherearenorunningexecutioncontextandallJobQueuesareempty.

NOTE TypicallyanECMAScriptimplementationwillhaveitsJobQueuespreinitializedwithatleastonePendingJob
andoneofthoseJobswillbetheirsttobeexecuted.Animplementationmightchoosetofreeallresourcesand
terminateifthecurrentJobcompletesandallJobQueuesareempty.Alternatively,itmightchoosetowaitfora
someimplementationspeciicagentormechanismtoenqueuenewPendingJobrequests.

ThefollowingabstractoperationsareusedtocreateandmanageJobsandJobQueues:

8.4.1 EnqueueJob(queueName,job,arguments)

TheEnqueueJobabstractoperationrequiresthreearguments:queueName,job,andarguments.Itperformsthefollowing
steps:

1.Assert:Type(queueName)isStringanditsvalueisthenameofaJobQueuerecognizedbythisimplementation.
2.Assert:jobisthenameofaJob.
3.Assert:argumentsisaListthathasthesamenumberofelementsasthenumberofparametersrequiredbyjob.
4.LetcallerContextbetherunningexecutioncontext.
5.LetcallerRealmbecallerContext'sRealm.
6.LetcallerScriptOrModulebecallerContext'sScriptOrModule.
7.LetpendingbePendingJob{[[Job]]:job,[[Arguments]]:arguments,[[Realm]]:callerRealm,[[ScriptOrModule]]:
callerScriptOrModule,[[HostDeined]]:undeined}.
8.Performanyimplementationorhostenvironmentdeinedprocessingofpending.Thismayincludemodifyingthe
[[HostDeined]]ieldoranyotherieldofpending.
9.AddpendingatthebackoftheJobQueuenamedbyqueueName.
10.ReturnNormalCompletion(empty).

8.4.2 NextJob

Analgorithmstepsuchas:

1.NextJobresult.

isusedinJobabstractoperationsinplaceof:

1.Returnresult.

JobabstractoperationsmustnotcontainaReturnsteporaReturnIfAbruptstep.TheNextJobresultoperationisequivalent
tothefollowingsteps:

1.Ifresultisanabruptcompletion,performHostReportErrors(result.[[Value]]).
2.Suspendtherunningexecutioncontextandremoveitfromtheexecutioncontextstack.
3.Assert:Theexecutioncontextstackisnowempty.
4.LetnextQueuebeanonemptyJobQueuechoseninanimplementationdeinedmanner.IfallJobQueuesareempty,the
resultisimplementationdeined.
5.LetnextPendingbethePendingJobrecordatthefrontofnextQueue.RemovethatrecordfromnextQueue.
6.LetnewContextbeanewexecutioncontext.
7.SetnewContext'sFunctiontonull.
8.SetnewContext'sRealmtonextPending.[[Realm]].
9.SetnewContext'sScriptOrModuletonextPending.[[ScriptOrModule]].
10.PushnewContextontotheexecutioncontextstack;newContextisnowtherunningexecutioncontext.
11.PerformanyimplementationorhostenvironmentdeinedjobinitializationusingnextPending.
12.PerformtheabstractoperationnamedbynextPending.[[Job]]usingtheelementsofnextPending.[[Arguments]]asits
arguments.

8.5 InitializeHostDeinedRealm()
TheabstractoperationInitializeHostDeinedRealmperformsthefollowingsteps:

1.LetrealmbeCreateRealm().
2.LetnewContextbeanewexecutioncontext.
3.SettheFunctionofnewContexttonull.
4.SettheRealmofnewContexttorealm.
5.SettheScriptOrModuleofnewContexttonull.
6.PushnewContextontotheexecutioncontextstack;newContextisnowtherunningexecutioncontext.
7.Ifthehostrequiresuseofanexoticobjecttoserveasrealm'sglobalobject,letglobalbesuchanobjectcreatedinan
implementationdeinedmanner.Otherwise,letglobalbeundeined,indicatingthatanordinaryobjectshouldbe
createdastheglobalobject.
8.Ifthehostrequiresthatthethisbindinginrealm'sglobalscopereturnanobjectotherthantheglobalobject,let
thisValuebesuchanobjectcreatedinanimplementationdeinedmanner.Otherwise,letthisValuebeundeined,
indicatingthatrealm'sglobalthisbindingshouldbetheglobalobject.
9.PerformSetRealmGlobalObject(realm,global,thisValue).
10.LetglobalObjbe?SetDefaultGlobalBindings(realm).
11.CreateanyimplementationdeinedglobalobjectpropertiesonglobalObj.
12.Inanimplementationdependentmanner,obtaintheECMAScriptsourcetexts(seeclause10)andanyassociatedhost
deinedvaluesforzeroormoreECMAScriptscriptsand/orECMAScriptmodules.ForeachsuchsourceTextand
hostDeined,
a.IfsourceTextisthesourcecodeofascript,then
i.PerformEnqueueJob("ScriptJobs",ScriptEvaluationJob,sourceText,hostDeined).
b.ElsesourceTextisthesourcecodeofamodule,
i.PerformEnqueueJob("ScriptJobs",TopLevelModuleEvaluationJob,sourceText,hostDeined).
13.NextJobNormalCompletion(undeined).

9 OrdinaryandExoticObjectsBehaviours
9.1 OrdinaryObjectInternalMethodsandInternalSlots
Allordinaryobjectshaveaninternalslotcalled[[Prototype]].Thevalueofthisinternalslotiseithernulloranobjectandis
usedforimplementinginheritance.Datapropertiesofthe[[Prototype]]objectareinherited(arevisibleaspropertiesofthe
childobject)forthepurposesofgetaccess,butnotforsetaccess.Accessorpropertiesareinheritedforbothgetaccessand
setaccess.

EveryordinaryobjecthasaBooleanvalued[[Extensible]]internalslotthatcontrolswhetherornotpropertiesmaybeadded
totheobject.Ifthevalueofthe[[Extensible]]internalslotisfalsethenadditionalpropertiesmaynotbeaddedtotheobject.
Inaddition,if[[Extensible]]isfalsethevalueofthe[[Prototype]]internalslotoftheobjectmaynotbemodiied.Oncethe
valueofanobject's[[Extensible]]internalslothasbeensettofalseitmaynotbesubsequentlychangedtotrue.

Inthefollowingalgorithmdescriptions,assumeOisanordinaryobject,Pisapropertykeyvalue,VisanyECMAScript
languagevalue,andDescisaPropertyDescriptorrecord.

Eachordinaryobjectinternalmethoddelegatestoasimilarlynamedabstractoperation.Ifsuchanabstractoperation
dependsonanotherinternalmethod,thentheinternalmethodisinvokedonOratherthancallingthesimilarlynamed
abstractoperationdirectly.Thesesemanticsensurethatexoticobjectshavetheiroverriddeninternalmethodsinvokedwhen
ordinaryobjectinternalmethodsareappliedtothem.

9.1.1 [[GetPrototypeOf]]()

Whenthe[[GetPrototypeOf]]internalmethodofOiscalled,thefollowingstepsaretaken:

1.Return!OrdinaryGetPrototypeOf(O).

9.1.1.1 OrdinaryGetPrototypeOf(O)

WhentheabstractoperationOrdinaryGetPrototypeOfiscalledwithObjectO,thefollowingstepsaretaken:

1.Returnthevalueofthe[[Prototype]]internalslotofO.

9.1.2 [[SetPrototypeOf]](V)

Whenthe[[SetPrototypeOf]]internalmethodofOiscalledwithargumentV,thefollowingstepsaretaken:

1.Return!OrdinarySetPrototypeOf(O,V).

9.1.2.1 OrdinarySetPrototypeOf(O,V)

WhentheabstractoperationOrdinarySetPrototypeOfiscalledwithObjectOandvalueV,thefollowingstepsaretaken:

1.Assert:EitherType(V)isObjectorType(V)isNull.
2.Letextensiblebethevalueofthe[[Extensible]]internalslotofO.
3.Letcurrentbethevalueofthe[[Prototype]]internalslotofO.
4.IfSameValue(V,current)istrue,returntrue.
5.Ifextensibleisfalse,returnfalse.
6.LetpbeV.
7.Letdonebefalse.
8.Repeatwhiledoneisfalse,
a.Ifpisnull,letdonebetrue.
b.Else,ifSameValue(p,O)istrue,returnfalse.
c.Else,
i.Ifthe[[GetPrototypeOf]]internalmethodofpisnottheordinaryobjectinternalmethoddeinedin9.1.1,let
donebetrue.
ii.Else,letpbethevalueofp's[[Prototype]]internalslot.
9.Setthevalueofthe[[Prototype]]internalslotofOtoV.
10.Returntrue.

NOTE Theloopinstep8guaranteesthattherewillbenocircularitiesinanyprototypechainthatonlyincludes
objectsthatusetheordinaryobjectdeinitionsfor[[GetPrototypeOf]]and[[SetPrototypeOf]].

9.1.3 [[IsExtensible]]()

Whenthe[[IsExtensible]]internalmethodofOiscalled,thefollowingstepsaretaken:

1.Return!OrdinaryIsExtensible(O).

9.1.3.1 OrdinaryIsExtensible(O)

WhentheabstractoperationOrdinaryIsExtensibleiscalledwithObjectO,thefollowingstepsaretaken:

1.Returnthevalueofthe[[Extensible]]internalslotofO.

9.1.4 [[PreventExtensions]]()

Whenthe[[PreventExtensions]]internalmethodofOiscalled,thefollowingstepsaretaken:

1.Return!OrdinaryPreventExtensions(O).

9.1.4.1 OrdinaryPreventExtensions(O)

WhentheabstractoperationOrdinaryPreventExtensionsiscalledwithObjectO,thefollowingstepsaretaken:

1.Setthevalueofthe[[Extensible]]internalslotofOtofalse.
2.Returntrue.

9.1.5 [[GetOwnProperty]](P)

Whenthe[[GetOwnProperty]]internalmethodofOiscalledwithpropertykeyP,thefollowingstepsaretaken:

1.Return!OrdinaryGetOwnProperty(O,P).

9.1.5.1 OrdinaryGetOwnProperty(O,P)

WhentheabstractoperationOrdinaryGetOwnPropertyiscalledwithObjectOandwithpropertykeyP,thefollowingsteps
aretaken:

1.Assert:IsPropertyKey(P)istrue.
2.IfOdoesnothaveanownpropertywithkeyP,returnundeined.
3.LetDbeanewlycreatedPropertyDescriptorwithnoields.
4.LetXbeO'sownpropertywhosekeyisP.
5.IfXisadataproperty,then
a.SetD.[[Value]]tothevalueofX's[[Value]]attribute.
b.SetD.[[Writable]]tothevalueofX's[[Writable]]attribute.
6.ElseXisanaccessorproperty,so
a.SetD.[[Get]]tothevalueofX's[[Get]]attribute.
b.SetD.[[Set]]tothevalueofX's[[Set]]attribute.
7.SetD.[[Enumerable]]tothevalueofX's[[Enumerable]]attribute.
8.SetD.[[Conigurable]]tothevalueofX's[[Conigurable]]attribute.
9.ReturnD.

9.1.6 [[DeineOwnProperty]](P,Desc)

Whenthe[[DeineOwnProperty]]internalmethodofOiscalledwithpropertykeyPandPropertyDescriptorDesc,the
followingstepsaretaken:

1.Return?OrdinaryDeineOwnProperty(O,P,Desc).

9.1.6.1 OrdinaryDeineOwnProperty(O,P,Desc)

WhentheabstractoperationOrdinaryDeineOwnPropertyiscalledwithObjectO,propertykeyP,andPropertyDescriptor
Desc,thefollowingstepsaretaken:

1.Letcurrentbe?O.[[GetOwnProperty]](P).
2.Letextensiblebethevalueofthe[[Extensible]]internalslotofO.
3.ReturnValidateAndApplyPropertyDescriptor(O,P,extensible,Desc,current).

9.1.6.2 IsCompatiblePropertyDescriptor(Extensible,Desc,Current)

WhentheabstractoperationIsCompatiblePropertyDescriptoriscalledwithBooleanvalueExtensible,andProperty
DescriptorsDesc,andCurrent,thefollowingstepsaretaken:

1.ReturnValidateAndApplyPropertyDescriptor(undeined,undeined,Extensible,Desc,Current).

9.1.6.3 ValidateAndApplyPropertyDescriptor(O,P,extensible,Desc,current)

WhentheabstractoperationValidateAndApplyPropertyDescriptoriscalledwithObjectO,propertykeyP,Booleanvalue
extensible,andPropertyDescriptorsDesc,andcurrent,thefollowingstepsaretaken:

ThisalgorithmcontainsstepsthattestvariousieldsofthePropertyDescriptorDescforspeciicvalues.Theieldsthatare
testedinthismannerneednotactuallyexistinDesc.Ifaieldisabsentthenitsvalueisconsideredtobefalse.

NOTE1 IfundeinedispassedastheOargumentonlyvalidationisperformedandnoobjectupdatesareperformed.

1.Assert:IfOisnotundeined,thenIsPropertyKey(P)istrue.
2.Ifcurrentisundeined,then
a.Ifextensibleisfalse,returnfalse.
b.Assert:extensibleistrue.
c.IfIsGenericDescriptor(Desc)istrueorIsDataDescriptor(Desc)istrue,then
i.IfOisnotundeined,createanowndatapropertynamedPofobjectOwhose[[Value]],[[Writable]],
[[Enumerable]]and[[Conigurable]]attributevaluesaredescribedbyDesc.Ifthevalueofanattributeieldof
Descisabsent,theattributeofthenewlycreatedpropertyissettoitsdefaultvalue.
d.ElseDescmustbeanaccessorPropertyDescriptor,
i.IfOisnotundeined,createanownaccessorpropertynamedPofobjectOwhose[[Get]],[[Set]],
[[Enumerable]]and[[Conigurable]]attributevaluesaredescribedbyDesc.Ifthevalueofanattributeieldof
Descisabsent,theattributeofthenewlycreatedpropertyissettoitsdefaultvalue.
e.Returntrue.
3.Returntrue,ifeveryieldinDescisabsent.
4.Returntrue,ifeveryieldinDescalsooccursincurrentandthevalueofeveryieldinDescisthesamevalueasthe
correspondingieldincurrentwhencomparedusingtheSameValuealgorithm.
5.Ifthe[[Conigurable]]ieldofcurrentisfalse,then
a.Returnfalse,ifthe[[Conigurable]]ieldofDescistrue.
b.Returnfalse,ifthe[[Enumerable]]ieldofDescispresentandthe[[Enumerable]]ieldsofcurrentandDescarethe
Booleannegationofeachother.
6.IfIsGenericDescriptor(Desc)istrue,nofurthervalidationisrequired.
7.ElseifIsDataDescriptor(current)andIsDataDescriptor(Desc)havedifferentresults,then
a.Returnfalse,ifthe[[Conigurable]]ieldofcurrentisfalse.
b.IfIsDataDescriptor(current)istrue,then
i.IfOisnotundeined,convertthepropertynamedPofobjectOfromadatapropertytoanaccessorproperty.
Preservetheexistingvaluesoftheconvertedproperty's[[Conigurable]]and[[Enumerable]]attributesand
settherestoftheproperty'sattributestotheirdefaultvalues.
c.Else,
i.IfOisnotundeined,convertthepropertynamedPofobjectOfromanaccessorpropertytoadataproperty.
Preservetheexistingvaluesoftheconvertedproperty's[[Conigurable]]and[[Enumerable]]attributesand
settherestoftheproperty'sattributestotheirdefaultvalues.
8.ElseifIsDataDescriptor(current)andIsDataDescriptor(Desc)arebothtrue,then
a.Ifthe[[Conigurable]]ieldofcurrentisfalse,then
i.Returnfalse,ifthe[[Writable]]ieldofcurrentisfalseandthe[[Writable]]ieldofDescistrue.
ii.Ifthe[[Writable]]ieldofcurrentisfalse,then
1.Returnfalse,ifthe[[Value]]ieldofDescispresentandSameValue(Desc.[[Value]],current.[[Value]])is
false.
b.Elsethe[[Conigurable]]ieldofcurrentistrue,soanychangeisacceptable.
9.ElseIsAccessorDescriptor(current)andIsAccessorDescriptor(Desc)arebothtrue,
a.Ifthe[[Conigurable]]ieldofcurrentisfalse,then
i.Returnfalse,ifthe[[Set]]ieldofDescispresentandSameValue(Desc.[[Set]],current.[[Set]])isfalse.
ii.Returnfalse,ifthe[[Get]]ieldofDescispresentandSameValue(Desc.[[Get]],current.[[Get]])isfalse.
10.IfOisnotundeined,then
a.ForeachieldofDescthatispresent,setthecorrespondingattributeofthepropertynamedPofobjectOtothe
valueoftheield.
11.Returntrue.

NOTE2 Step8.ballowsanyieldofDesctobedifferentfromthecorrespondingieldofcurrentifcurrent's
[[Conigurable]]ieldistrue.Thisevenpermitschangingthe[[Value]]ofapropertywhose[[Writable]]
attributeisfalse.Thisisallowedbecauseatrue[[Conigurable]]attributewouldpermitanequivalent
sequenceofcallswhere[[Writable]]isirstsettotrue,anew[[Value]]isset,andthen[[Writable]]issetto
false.

9.1.7 [[HasProperty]](P)

Whenthe[[HasProperty]]internalmethodofOiscalledwithpropertykeyP,thefollowingstepsaretaken:

1.Return?OrdinaryHasProperty(O,P).

9.1.7.1 OrdinaryHasProperty(O,P)

WhentheabstractoperationOrdinaryHasPropertyiscalledwithObjectOandwithpropertykeyP,thefollowingstepsare
taken:

1.Assert:IsPropertyKey(P)istrue.
2.LethasOwnbe?O.[[GetOwnProperty]](P).
3.IfhasOwnisnotundeined,returntrue.
4.Letparentbe?O.[[GetPrototypeOf]]().
5.Ifparentisnotnull,then
a.Return?parent.[[HasProperty]](P).
6.Returnfalse.
9.1.8 [[Get]](P,Receiver)

Whenthe[[Get]]internalmethodofOiscalledwithpropertykeyPandECMAScriptlanguagevalueReceiver,thefollowing
stepsaretaken:

1.Return?OrdinaryGet(O,P,Receiver).

9.1.8.1 OrdinaryGet(O,P,Receiver)

WhentheabstractoperationOrdinaryGetiscalledwithObjectO,propertykeyP,andECMAScriptlanguagevalueReceiver,
thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Letdescbe?O.[[GetOwnProperty]](P).
3.Ifdescisundeined,then
a.Letparentbe?O.[[GetPrototypeOf]]().
b.Ifparentisnull,returnundeined.
c.Return?parent.[[Get]](P,Receiver).
4.IfIsDataDescriptor(desc)istrue,returndesc.[[Value]].
5.Assert:IsAccessorDescriptor(desc)istrue.
6.Letgetterbedesc.[[Get]].
7.Ifgetterisundeined,returnundeined.
8.Return?Call(getter,Receiver).

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

Whenthe[[Set]]internalmethodofOiscalledwithpropertykeyP,valueV,andECMAScriptlanguagevalueReceiver,the
followingstepsaretaken:

1.Return?OrdinarySet(O,P,V,Receiver).

9.1.9.1 OrdinarySet(O,P,V,Receiver)

WhentheabstractoperationOrdinarySetiscalledwithObjectO,propertykeyP,valueV,andECMAScriptlanguagevalue
Receiver,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.LetownDescbe?O.[[GetOwnProperty]](P).
3.IfownDescisundeined,then
a.Letparentbe?O.[[GetPrototypeOf]]().
b.Ifparentisnotnull,then
i.Return?parent.[[Set]](P,V,Receiver).
c.Else,
i.LetownDescbethePropertyDescriptor{[[Value]]:undeined,[[Writable]]:true,[[Enumerable]]:true,
[[Conigurable]]:true}.
4.IfIsDataDescriptor(ownDesc)istrue,then
a.IfownDesc.[[Writable]]isfalse,returnfalse.
b.IfType(Receiver)isnotObject,returnfalse.
c.LetexistingDescriptorbe?Receiver.[[GetOwnProperty]](P).
d.IfexistingDescriptorisnotundeined,then
i.IfIsAccessorDescriptor(existingDescriptor)istrue,returnfalse.
ii.IfexistingDescriptor.[[Writable]]isfalse,returnfalse.
iii.LetvalueDescbethePropertyDescriptor{[[Value]]:V}.
iv.Return?Receiver.[[DeineOwnProperty]](P,valueDesc).
e.ElseReceiverdoesnotcurrentlyhaveapropertyP,
i.Return?CreateDataProperty(Receiver,P,V).
5.Assert:IsAccessorDescriptor(ownDesc)istrue.
6.LetsetterbeownDesc.[[Set]].
7.Ifsetterisundeined,returnfalse.
8.Perform?Call(setter,Receiver,V).
9.Returntrue.

9.1.10 [[Delete]](P)

Whenthe[[Delete]]internalmethodofOiscalledwithpropertykeyP,thefollowingstepsaretaken:

1.Return?OrdinaryDelete(O,P).

9.1.10.1 OrdinaryDelete(O,P)

WhentheabstractoperationOrdinaryDeleteiscalledwithObjectOandpropertykeyP,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Letdescbe?O.[[GetOwnProperty]](P).
3.Ifdescisundeined,returntrue.
4.Ifdesc.[[Conigurable]]istrue,then
a.RemovetheownpropertywithnamePfromO.
b.Returntrue.
5.Returnfalse.

9.1.11 [[OwnPropertyKeys]]()

Whenthe[[OwnPropertyKeys]]internalmethodofOiscalled,thefollowingstepsaretaken:

1.Return!OrdinaryOwnPropertyKeys(O).

9.1.11.1 OrdinaryOwnPropertyKeys(O)

WhentheabstractoperationOrdinaryOwnPropertyKeysiscalledwithObjectO,thefollowingstepsaretaken:

1.LetkeysbeanewemptyList.
2.ForeachownpropertykeyPofOthatisanintegerindex,inascendingnumericindexorder
a.AddPasthelastelementofkeys.
3.ForeachownpropertykeyPofOthatisaStringbutisnotanintegerindex,inascendingchronologicalorderof
propertycreation
a.AddPasthelastelementofkeys.
4.ForeachownpropertykeyPofOthatisaSymbol,inascendingchronologicalorderofpropertycreation
a.AddPasthelastelementofkeys.
5.Returnkeys.

9.1.12 ObjectCreate(proto[,internalSlotsList])

TheabstractoperationObjectCreatewithargumentproto(anobjectornull)isusedtospecifytheruntimecreationofnew
ordinaryobjects.TheoptionalargumentinternalSlotsListisaListofthenamesofadditionalinternalslotsthatmustbe
deinedaspartoftheobject.Ifthelistisnotprovided,anewemptyListisused.Thisabstractoperationperformsthe
followingsteps:

1.IfinternalSlotsListwasnotprovided,letinternalSlotsListbeanewemptyList.
2.LetobjbeanewlycreatedobjectwithaninternalslotforeachnameininternalSlotsList.
3.Setobj'sessentialinternalmethodstothedefaultordinaryobjectdeinitionsspeciiedin9.1.
4.Setthe[[Prototype]]internalslotofobjtoproto.
5.Setthe[[Extensible]]internalslotofobjtotrue.
6.Returnobj.

9.1.13 OrdinaryCreateFromConstructor(constructor,intrinsicDefaultProto[,internalSlotsList])
TheabstractoperationOrdinaryCreateFromConstructorcreatesanordinaryobjectwhose[[Prototype]]valueisretrieved
fromaconstructor'sprototypeproperty,ifitexists.OtherwisetheintrinsicnamedbyintrinsicDefaultProtoisusedfor
[[Prototype]].TheoptionalinternalSlotsListisaListofthenamesofadditionalinternalslotsthatmustbedeinedaspartof
theobject.Ifthelistisnotprovided,anewemptyListisused.Thisabstractoperationperformsthefollowingsteps:

1.Assert:intrinsicDefaultProtoisaStringvaluethatisthisspeciication'snameofanintrinsicobject.Thecorresponding
objectmustbeanintrinsicthatisintendedtobeusedasthe[[Prototype]]valueofanobject.
2.Letprotobe?GetPrototypeFromConstructor(constructor,intrinsicDefaultProto).
3.ReturnObjectCreate(proto,internalSlotsList).

9.1.14 GetPrototypeFromConstructor(constructor,intrinsicDefaultProto)

TheabstractoperationGetPrototypeFromConstructordeterminesthe[[Prototype]]valuethatshouldbeusedtocreatean
objectcorrespondingtoaspeciicconstructor.Thevalueisretrievedfromtheconstructor'sprototypeproperty,ifitexists.
OtherwisetheintrinsicnamedbyintrinsicDefaultProtoisusedfor[[Prototype]].Thisabstractoperationperformsthe
followingsteps:

1.Assert:intrinsicDefaultProtoisaStringvaluethatisthisspeciication'snameofanintrinsicobject.Thecorresponding
objectmustbeanintrinsicthatisintendedtobeusedasthe[[Prototype]]valueofanobject.
2.Assert:IsCallable(constructor)istrue.
3.Letprotobe?Get(constructor,"prototype").
4.IfType(proto)isnotObject,then
a.Letrealmbe?GetFunctionRealm(constructor).
b.Letprotoberealm'sintrinsicobjectnamedintrinsicDefaultProto.
5.Returnproto.

NOTE Ifconstructordoesnotsupplya[[Prototype]]value,thedefaultvaluethatisusedisobtainedfromtherealmof
theconstructorfunctionratherthanfromtherunningexecutioncontext.

9.2 ECMAScriptFunctionObjects
ECMAScriptfunctionobjectsencapsulateparameterizedECMAScriptcodeclosedoveralexicalenvironmentandsupportthe
dynamicevaluationofthatcode.AnECMAScriptfunctionobjectisanordinaryobjectandhasthesameinternalslotsandthe
sameinternalmethodsasotherordinaryobjects.ThecodeofanECMAScriptfunctionobjectmaybeeitherstrictmodecode
(10.2.1)ornonstrictmodecode.AnECMAScriptfunctionobjectwhosecodeisstrictmodecodeiscalledastrictfunction.
Onewhosecodeisnotstrictmodecodeiscalledanonstrictfunction.

ECMAScriptfunctionobjectshavetheadditionalinternalslotslistedinTable27.
Table27:InternalSlotsofECMAScriptFunctionObjects
InternalSlot Type Description

[[Environment]] Lexical TheLexicalEnvironmentthatthefunctionwasclosedover.Usedastheouter


Environment environmentwhenevaluatingthecodeofthefunction.

[[FormalParameters]] ParseNode Therootparsenodeofthesourcetextthatdeinesthefunction'sformalparameter


list.

[[FunctionKind]] String Either"normal","classConstructor"or"generator".

[[ECMAScriptCode]] ParseNode Therootparsenodeofthesourcetextthatdeinesthefunction'sbody.

[[ConstructorKind]] String Either"base"or"derived".

[[Realm]] Realm Therealminwhichthefunctionwascreatedandwhichprovidesanyintrinsic


Record objectsthatareaccessedwhenevaluatingthefunction.

[[ScriptOrModule]] Script Thescriptormoduleinwhichthefunctionwascreated.


Recordor
Module
Record

[[ThisMode]] (lexical, Deineshowthisreferencesareinterpretedwithintheformalparametersand


strict, codebodyofthefunction.lexicalmeansthatthisreferstothethisvalueofa
global) lexicallyenclosingfunction.strictmeansthatthethisvalueisusedexactlyas
providedbyaninvocationofthefunction.globalmeansthatathisvalueof
undeinedisinterpretedasareferencetotheglobalobject.

[[Strict]] Boolean trueifthisisastrictmodefunction,falseifthisisnotastrictmodefunction.

[[HomeObject]] Object Ifthefunctionusessuper,thisistheobjectwhose[[GetPrototypeOf]]providesthe


objectwheresuperpropertylookupsbegin.

AllECMAScriptfunctionobjectshavethe[[Call]]internalmethoddeinedhere.ECMAScriptfunctionsthatarealso
constructorsinadditionhavethe[[Construct]]internalmethod.

9.2.1 [[Call]](thisArgument,argumentsList)

The[[Call]]internalmethodforanECMAScriptfunctionobjectFiscalledwithparametersthisArgumentandargumentsList,a
ListofECMAScriptlanguagevalues.Thefollowingstepsaretaken:

1.Assert:FisanECMAScriptfunctionobject.
2.IfF's[[FunctionKind]]internalslotis"classConstructor",throwaTypeErrorexception.
3.LetcallerContextbetherunningexecutioncontext.
4.LetcalleeContextbePrepareForOrdinaryCall(F,undeined).
5.Assert:calleeContextisnowtherunningexecutioncontext.
6.PerformOrdinaryCallBindThis(F,calleeContext,thisArgument).
7.LetresultbeOrdinaryCallEvaluateBody(F,argumentsList).
8.RemovecalleeContextfromtheexecutioncontextstackandrestorecallerContextastherunningexecutioncontext.
9.Ifresult.[[Type]]isreturn,returnNormalCompletion(result.[[Value]]).
10.ReturnIfAbrupt(result).
11.ReturnNormalCompletion(undeined).

NOTE WhencalleeContextisremovedfromtheexecutioncontextstackinstep8itmustnotbedestroyedifitis
suspendedandretainedforlaterresumptionbyanaccessiblegeneratorobject.

9.2.1.1 PrepareForOrdinaryCall(F,newTarget)
WhentheabstractoperationPrepareForOrdinaryCalliscalledwithfunctionobjectFandECMAScriptlanguagevalue
newTarget,thefollowingstepsaretaken:

1.Assert:Type(newTarget)isUndeinedorObject.
2.LetcallerContextbetherunningexecutioncontext.
3.LetcalleeContextbeanewECMAScriptcodeexecutioncontext.
4.SettheFunctionofcalleeContexttoF.
5.LetcalleeRealmbethevalueofF's[[Realm]]internalslot.
6.SettheRealmofcalleeContexttocalleeRealm.
7.SettheScriptOrModuleofcalleeContexttothevalueofF's[[ScriptOrModule]]internalslot.
8.LetlocalEnvbeNewFunctionEnvironment(F,newTarget).
9.SettheLexicalEnvironmentofcalleeContexttolocalEnv.
10.SettheVariableEnvironmentofcalleeContexttolocalEnv.
11.IfcallerContextisnotalreadysuspended,suspendcallerContext.
12.PushcalleeContextontotheexecutioncontextstack;calleeContextisnowtherunningexecutioncontext.
13.NOTEAnyexceptionobjectsproducedafterthispointareassociatedwithcalleeRealm.
14.ReturncalleeContext.

9.2.1.2 OrdinaryCallBindThis(F,calleeContext,thisArgument)

WhentheabstractoperationOrdinaryCallBindThisiscalledwithfunctionobjectF,executioncontextcalleeContext,and
ECMAScriptvaluethisArgument,thefollowingstepsaretaken:

1.LetthisModebethevalueofF's[[ThisMode]]internalslot.
2.IfthisModeislexical,returnNormalCompletion(undeined).
3.LetcalleeRealmbethevalueofF's[[Realm]]internalslot.
4.LetlocalEnvbetheLexicalEnvironmentofcalleeContext.
5.IfthisModeisstrict,letthisValuebethisArgument.
6.Else,
a.IfthisArgumentisnullorundeined,then
i.LetglobalEnvbecalleeRealm.[[GlobalEnv]].
ii.LetglobalEnvRecbeglobalEnv'sEnvironmentRecord.
iii.LetthisValuebeglobalEnvRec.[[GlobalThisValue]].
b.Else,
i.LetthisValuebe!ToObject(thisArgument).
ii.NOTEToObjectproduceswrapperobjectsusingcalleeRealm.
7.LetenvRecbelocalEnv'sEnvironmentRecord.
8.Assert:ThenextstepneverreturnsanabruptcompletionbecauseenvRec.[[ThisBindingStatus]]isnot"initialized".
9.ReturnenvRec.BindThisValue(thisValue).

9.2.1.3 OrdinaryCallEvaluateBody(F,argumentsList)

WhentheabstractoperationOrdinaryCallEvaluateBodyiscalledwithfunctionobjectFandListargumentsList,thefollowing
stepsaretaken:

1.Perform?FunctionDeclarationInstantiation(F,argumentsList).
2.ReturntheresultofEvaluateBodyoftheparsedcodethatisthevalueofF's[[ECMAScriptCode]]internalslotpassingF
astheargument.

9.2.2 [[Construct]](argumentsList,newTarget)

The[[Construct]]internalmethodforanECMAScriptFunctionobjectFiscalledwithparametersargumentsListand
newTarget.argumentsListisapossiblyemptyListofECMAScriptlanguagevalues.Thefollowingstepsaretaken:

1.Assert:FisanECMAScriptfunctionobject.
2.Assert:Type(newTarget)isObject.
3.LetcallerContextbetherunningexecutioncontext.
4.LetkindbeF's[[ConstructorKind]]internalslot.
5.Ifkindis"base",then
a.LetthisArgumentbe?OrdinaryCreateFromConstructor(newTarget,"%ObjectPrototype%").
6.LetcalleeContextbePrepareForOrdinaryCall(F,newTarget).
7.Assert:calleeContextisnowtherunningexecutioncontext.
8.Ifkindis"base",performOrdinaryCallBindThis(F,calleeContext,thisArgument).
9.LetconstructorEnvbetheLexicalEnvironmentofcalleeContext.
10.LetenvRecbeconstructorEnv'sEnvironmentRecord.
11.LetresultbeOrdinaryCallEvaluateBody(F,argumentsList).
12.RemovecalleeContextfromtheexecutioncontextstackandrestorecallerContextastherunningexecutioncontext.
13.Ifresult.[[Type]]isreturn,then
a.IfType(result.[[Value]])isObject,returnNormalCompletion(result.[[Value]]).
b.Ifkindis"base",returnNormalCompletion(thisArgument).
c.Ifresult.[[Value]]isnotundeined,throwaTypeErrorexception.
14.Else,ReturnIfAbrupt(result).
15.Return?envRec.GetThisBinding().

9.2.3 FunctionAllocate(functionPrototype,strict,functionKind)

TheabstractoperationFunctionAllocaterequiresthethreeargumentsfunctionPrototype,strictandfunctionKind.
FunctionAllocateperformsthefollowingsteps:

1.Assert:Type(functionPrototype)isObject.
2.Assert:functionKindiseither"normal","nonconstructor"or"generator".
3.IffunctionKindis"normal",letneedsConstructbetrue.
4.Else,letneedsConstructbefalse.
5.IffunctionKindis"nonconstructor",letfunctionKindbe"normal".
6.LetFbeanewlycreatedECMAScriptfunctionobjectwiththeinternalslotslistedinTable27.Allofthoseinternalslots
areinitializedtoundeined.
7.SetF'sessentialinternalmethodstothedefaultordinaryobjectdeinitionsspeciiedin9.1.
8.SetF's[[Call]]internalmethodtothedeinitionspeciiedin9.2.1.
9.IfneedsConstructistrue,then
a.SetF's[[Construct]]internalmethodtothedeinitionspeciiedin9.2.2.
b.Setthe[[ConstructorKind]]internalslotofFto"base".
10.Setthe[[Strict]]internalslotofFtostrict.
11.Setthe[[FunctionKind]]internalslotofFtofunctionKind.
12.Setthe[[Prototype]]internalslotofFtofunctionPrototype.
13.Setthe[[Extensible]]internalslotofFtotrue.
14.Setthe[[Realm]]internalslotofFtothecurrentRealmRecord.
15.ReturnF.

9.2.4 FunctionInitialize(F,kind,ParameterList,Body,Scope)

TheabstractoperationFunctionInitializerequiresthearguments:afunctionobjectF,kindwhichisoneof(Normal,Method,
Arrow),aparameterlistproductionspeciiedbyParameterList,abodyproductionspeciiedbyBody,aLexicalEnvironment
speciiedbyScope.FunctionInitializeperformsthefollowingsteps:

1.Assert:Fisanextensibleobjectthatdoesnothavealengthownproperty.
2.LetlenbetheExpectedArgumentCountofParameterList.
3.Perform!DeinePropertyOrThrow(F,"length",PropertyDescriptor{[[Value]]:len,[[Writable]]:false,[[Enumerable]]:
false,[[Conigurable]]:true}).
4.LetStrictbethevalueofthe[[Strict]]internalslotofF.
5.Setthe[[Environment]]internalslotofFtothevalueofScope.
6.Setthe[[FormalParameters]]internalslotofFtoParameterList.
7.Setthe[[ECMAScriptCode]]internalslotofFtoBody.
8.Setthe[[ScriptOrModule]]internalslotofFtoGetActiveScriptOrModule().
9.IfkindisArrow,setthe[[ThisMode]]internalslotofFtolexical.
10.ElseifStrictistrue,setthe[[ThisMode]]internalslotofFtostrict.
11.Elsesetthe[[ThisMode]]internalslotofFtoglobal.
12.ReturnF.

9.2.5 FunctionCreate(kind,ParameterList,Body,Scope,Strict[,prototype])

TheabstractoperationFunctionCreaterequiresthearguments:kindwhichisoneof(Normal,Method,Arrow),aparameter
listproductionspeciiedbyParameterList,abodyproductionspeciiedbyBody,aLexicalEnvironmentspeciiedbyScope,a
BooleanlagStrict,andoptionally,anobjectprototype.FunctionCreateperformsthefollowingsteps:

1.Iftheprototypeargumentwasnotpassed,then
a.Letprototypebetheintrinsicobject%FunctionPrototype%.
2.IfkindisnotNormal,letallocKindbe"nonconstructor".
3.ElseletallocKindbe"normal".
4.LetFbeFunctionAllocate(prototype,Strict,allocKind).
5.ReturnFunctionInitialize(F,kind,ParameterList,Body,Scope).

9.2.6 GeneratorFunctionCreate(kind,ParameterList,Body,Scope,Strict)

TheabstractoperationGeneratorFunctionCreaterequiresthearguments:kindwhichisoneof(Normal,Method),a
parameterlistproductionspeciiedbyParameterList,abodyproductionspeciiedbyBody,aLexicalEnvironmentspeciied
byScope,andaBooleanlagStrict.GeneratorFunctionCreateperformsthefollowingsteps:

1.LetfunctionPrototypebetheintrinsicobject%Generator%.
2.LetFbeFunctionAllocate(functionPrototype,Strict,"generator").
3.ReturnFunctionInitialize(F,kind,ParameterList,Body,Scope).

9.2.7 AddRestrictedFunctionProperties(F,realm)

TheabstractoperationAddRestrictedFunctionPropertiesiscalledwithafunctionobjectFandRealmRecordrealmasits
argument.Itperformsthefollowingsteps:

1.Assert:realm.[[Intrinsics]].[[%ThrowTypeError%]]existsandhasbeeninitialized.
2.Letthrowerberealm.[[Intrinsics]].[[%ThrowTypeError%]].
3.Perform!DeinePropertyOrThrow(F,"caller",PropertyDescriptor{[[Get]]:thrower,[[Set]]:thrower,[[Enumerable]]:
false,[[Conigurable]]:true}).
4.Return!DeinePropertyOrThrow(F,"arguments",PropertyDescriptor{[[Get]]:thrower,[[Set]]:thrower,
[[Enumerable]]:false,[[Conigurable]]:true}).

9.2.7.1 %ThrowTypeError%()

The%ThrowTypeError%intrinsicisananonymousbuiltinfunctionobjectthatisdeinedonceforeachrealm.When
%ThrowTypeError%iscalleditperformsthefollowingsteps:

1.ThrowaTypeErrorexception.

Thevalueofthe[[Extensible]]internalslotofa%ThrowTypeError%functionisfalse.

Thelengthpropertyofa%ThrowTypeError%functionhastheattributes{[[Writable]]:false,[[Enumerable]]:false,
[[Conigurable]]:false}.

9.2.8 MakeConstructor(F[,writablePrototype,prototype])

TheabstractoperationMakeConstructorrequiresaFunctionargumentFandoptionally,aBooleanwritablePrototypeandan
objectprototype.Ifprototypeisprovideditisassumedtoalreadycontain,ifneeded,a"constructor"propertywhosevalue
isF.ThisoperationconvertsFintoaconstructorbyperformingthefollowingsteps:
1.Assert:FisanECMAScriptfunctionobject.
2.Assert:Fhasa[[Construct]]internalmethod.
3.Assert:Fisanextensibleobjectthatdoesnothaveaprototypeownproperty.
4.IfthewritablePrototypeargumentwasnotprovided,letwritablePrototypebetrue.
5.Iftheprototypeargumentwasnotprovided,then
a.LetprototypebeObjectCreate(%ObjectPrototype%).
b.Perform!DeinePropertyOrThrow(prototype,"constructor",PropertyDescriptor{[[Value]]:F,[[Writable]]:
writablePrototype,[[Enumerable]]:false,[[Conigurable]]:true}).
6.Perform!DeinePropertyOrThrow(F,"prototype",PropertyDescriptor{[[Value]]:prototype,[[Writable]]:
writablePrototype,[[Enumerable]]:false,[[Conigurable]]:false}).
7.ReturnNormalCompletion(undeined).

9.2.9 MakeClassConstructor(F)

TheabstractoperationMakeClassConstructorwithargumentFperformsthefollowingsteps:

1.Assert:FisanECMAScriptfunctionobject.
2.Assert:F's[[FunctionKind]]internalslotis"normal".
3.SetF's[[FunctionKind]]internalslotto"classConstructor".
4.ReturnNormalCompletion(undeined).

9.2.10 MakeMethod(F,homeObject)

TheabstractoperationMakeMethodwithargumentsFandhomeObjectconiguresFasamethodbyperformingthefollowing
steps:

1.Assert:FisanECMAScriptfunctionobject.
2.Assert:Type(homeObject)isObject.
3.Setthe[[HomeObject]]internalslotofFtohomeObject.
4.ReturnNormalCompletion(undeined).

9.2.11 SetFunctionName(F,name[,preix])

TheabstractoperationSetFunctionNamerequiresaFunctionargumentF,aStringorSymbolargumentnameandoptionally
aStringargumentpreix.ThisoperationaddsanamepropertytoFbyperformingthefollowingsteps:

1.Assert:Fisanextensibleobjectthatdoesnothaveanameownproperty.
2.Assert:Type(name)iseitherSymbolorString.
3.Assert:Ifpreixwaspassed,thenType(preix)isString.
4.IfType(name)isSymbol,then
a.Letdescriptionbename's[[Description]]value.
b.Ifdescriptionisundeined,letnamebetheemptyString.
c.Else,letnamebetheconcatenationof"[",description,and"]".
5.Ifpreixwaspassed,then
a.Letnamebetheconcatenationofpreix,codeunit0x0020(SPACE),andname.
6.Return!DeinePropertyOrThrow(F,"name",PropertyDescriptor{[[Value]]:name,[[Writable]]:false,[[Enumerable]]:
false,[[Conigurable]]:true}).

9.2.12 FunctionDeclarationInstantiation(func,argumentsList)

NOTE1 WhenanexecutioncontextisestablishedforevaluatinganECMAScriptfunctionanewfunctionEnvironment
RecordiscreatedandbindingsforeachformalparameterareinstantiatedinthatEnvironmentRecord.Each
declarationinthefunctionbodyisalsoinstantiated.Ifthefunction'sformalparametersdonotincludeany
defaultvalueinitializersthenthebodydeclarationsareinstantiatedinthesameEnvironmentRecordasthe
parameters.Ifdefaultvalueparameterinitializersexist,asecondEnvironmentRecordiscreatedforthebody
declarations.FormalparametersandfunctionsareinitializedaspartofFunctionDeclarationInstantiation.All
otherbindingsareinitializedduringevaluationofthefunctionbody.

FunctionDeclarationInstantiationisperformedasfollowsusingargumentsfuncandargumentsList.funcisthefunctionobject
forwhichtheexecutioncontextisbeingestablished.

1.LetcalleeContextbetherunningexecutioncontext.
2.LetenvbetheLexicalEnvironmentofcalleeContext.
3.LetenvRecbeenv'sEnvironmentRecord.
4.Letcodebethevalueofthe[[ECMAScriptCode]]internalslotoffunc.
5.Letstrictbethevalueofthe[[Strict]]internalslotoffunc.
6.Letformalsbethevalueofthe[[FormalParameters]]internalslotoffunc.
7.LetparameterNamesbetheBoundNamesofformals.
8.IfparameterNameshasanyduplicateentries,lethasDuplicatesbetrue.Otherwise,lethasDuplicatesbefalse.
9.LetsimpleParameterListbeIsSimpleParameterListofformals.
10.LethasParameterExpressionsbeContainsExpressionofformals.
11.LetvarNamesbetheVarDeclaredNamesofcode.
12.LetvarDeclarationsbetheVarScopedDeclarationsofcode.
13.LetlexicalNamesbetheLexicallyDeclaredNamesofcode.
14.LetfunctionNamesbeanewemptyList.
15.LetfunctionsToInitializebeanewemptyList.
16.ForeachdinvarDeclarations,inreverselistorderdo
a.IfdisneitheraVariableDeclarationoraForBinding,then
i.Assert:diseitheraFunctionDeclarationoraGeneratorDeclaration.
ii.LetfnbethesoleelementoftheBoundNamesofd.
iii.IffnisnotanelementoffunctionNames,then
1.InsertfnastheirstelementoffunctionNames.
2.NOTEIftherearemultipleFunctionDeclarationsorGeneratorDeclarationsforthesamename,thelast
declarationisused.
3.InsertdastheirstelementoffunctionsToInitialize.
17.LetargumentsObjectNeededbetrue.
18.Ifthevalueofthe[[ThisMode]]internalslotoffuncislexical,then
a.NOTEArrowfunctionsneverhaveanargumentsobjects.
b.LetargumentsObjectNeededbefalse.
19.Elseif"arguments"isanelementofparameterNames,then
a.LetargumentsObjectNeededbefalse.
20.ElseifhasParameterExpressionsisfalse,then
a.If"arguments"isanelementoffunctionNamesorif"arguments"isanelementoflexicalNames,then
i.LetargumentsObjectNeededbefalse.
21.ForeachStringparamNameinparameterNames,do
a.LetalreadyDeclaredbeenvRec.HasBinding(paramName).
b.NOTEEarlyerrorsensurethatduplicateparameternamescanonlyoccurinnonstrictfunctionsthatdonothave
parameterdefaultvaluesorrestparameters.
c.IfalreadyDeclaredisfalse,then
i.Perform!envRec.CreateMutableBinding(paramName,false).
ii.IfhasDuplicatesistrue,then
1.Perform!envRec.InitializeBinding(paramName,undeined).
22.IfargumentsObjectNeededistrue,then
a.IfstrictistrueorifsimpleParameterListisfalse,then
i.LetaobeCreateUnmappedArgumentsObject(argumentsList).
b.Else,
i.NOTEmappedargumentobjectisonlyprovidedfornonstrictfunctionsthatdon'thavearestparameter,any
parameterdefaultvalueinitializers,oranydestructuredparameters.
ii.LetaobeCreateMappedArgumentsObject(func,formals,argumentsList,envRec).
c.Ifstrictistrue,then
i.Perform!envRec.CreateImmutableBinding("arguments",false).
d.Else,
i.Perform!envRec.CreateMutableBinding("arguments",false).
e.CallenvRec.InitializeBinding("arguments",ao).
f.Append"arguments"toparameterNames.
23.LetiteratorRecordbeRecord{[[Iterator]]:CreateListIterator(argumentsList),[[Done]]:false}.
24.IfhasDuplicatesistrue,then
a.Perform?IteratorBindingInitializationforformalswithiteratorRecordandundeinedasarguments.
25.Else,
a.Perform?IteratorBindingInitializationforformalswithiteratorRecordandenvasarguments.
26.IfhasParameterExpressionsisfalse,then
a.NOTEOnlyasinglelexicalenvironmentisneededfortheparametersandtoplevelvars.
b.LetinstantiatedVarNamesbeacopyoftheListparameterNames.
c.ForeachninvarNames,do
i.IfnisnotanelementofinstantiatedVarNames,then
1.AppendntoinstantiatedVarNames.
2.Perform!envRec.CreateMutableBinding(n,false).
3.CallenvRec.InitializeBinding(n,undeined).
d.LetvarEnvbeenv.
e.LetvarEnvRecbeenvRec.
27.Else,
a.NOTEAseparateEnvironmentRecordisneededtoensurethatclosurescreatedbyexpressionsintheformal
parameterlistdonothavevisibilityofdeclarationsinthefunctionbody.
b.LetvarEnvbeNewDeclarativeEnvironment(env).
c.LetvarEnvRecbevarEnv'sEnvironmentRecord.
d.SettheVariableEnvironmentofcalleeContexttovarEnv.
e.LetinstantiatedVarNamesbeanewemptyList.
f.ForeachninvarNames,do
i.IfnisnotanelementofinstantiatedVarNames,then
1.AppendntoinstantiatedVarNames.
2.Perform!varEnvRec.CreateMutableBinding(n,false).
3.IfnisnotanelementofparameterNamesorifnisanelementoffunctionNames,letinitialValuebe
undeined.
4.Else,
a.LetinitialValuebe!envRec.GetBindingValue(n,false).
5.CallvarEnvRec.InitializeBinding(n,initialValue).
6.NOTEvarswhosenamesarethesameasaformalparameter,initiallyhavethesamevalueasthe
correspondinginitializedparameter.
28.NOTE:AnnexB.3.3.1addsadditionalstepsatthispoint.
29.Ifstrictisfalse,then
a.LetlexEnvbeNewDeclarativeEnvironment(varEnv).
b.NOTE:NonstrictfunctionsuseaseparatelexicalEnvironmentRecordfortoplevellexicaldeclarationssothata
directevalcandeterminewhetheranyvarscopeddeclarationsintroducedbytheevalcodeconlictwithpre
existingtoplevellexicallyscopeddeclarations.Thisisnotneededforstrictfunctionsbecauseastrictdirecteval
alwaysplacesalldeclarationsintoanewEnvironmentRecord.
30.Else,letlexEnvbevarEnv.
31.LetlexEnvRecbelexEnv'sEnvironmentRecord.
32.SettheLexicalEnvironmentofcalleeContexttolexEnv.
33.LetlexDeclarationsbetheLexicallyScopedDeclarationsofcode.
34.ForeachelementdinlexDeclarationsdo
a.NOTEAlexicallydeclarednamecannotbethesameasafunction/generatordeclaration,formalparameter,ora
varname.Lexicallydeclarednamesareonlyinstantiatedherebutnotinitialized.
b.ForeachelementdnoftheBoundNamesofddo
i.IfIsConstantDeclarationofdistrue,then
1.Perform!lexEnvRec.CreateImmutableBinding(dn,true).
ii.Else,
1.Perform!lexEnvRec.CreateMutableBinding(dn,false).
35.ForeachparsedgrammarphrasefinfunctionsToInitialize,do
a.LetfnbethesoleelementoftheBoundNamesoff.
b.LetfobetheresultofperformingInstantiateFunctionObjectforfwithargumentlexEnv.
c.Perform!varEnvRec.SetMutableBinding(fn,fo,false).
36.ReturnNormalCompletion(empty).

NOTE2 B.3.3providesanextensiontotheabovealgorithmthatisnecessaryforbackwardscompatibilitywithweb
browserimplementationsofECMAScriptthatpredateECMAScript2015.

NOTE3 ParameterInitializersmaycontaindirectevalexpressions.Anytopleveldeclarationsofsuchevalsareonly
visibletotheevalcode(10.2).Thecreationoftheenvironmentforsuchdeclarationsisdescribedin14.1.19.

9.3 BuiltinFunctionObjects
ThebuiltinfunctionobjectsdeinedinthisspeciicationmaybeimplementedaseitherECMAScriptfunctionobjects(9.2)
whosebehaviourisprovidedusingECMAScriptcodeorasimplementationprovidedexoticfunctionobjectswhosebehaviour
isprovidedinsomeothermanner.Ineithercase,theeffectofcallingsuchfunctionsmustconformtotheirspeciications.An
implementationmayalsoprovideadditionalbuiltinfunctionobjectsthatarenotdeinedinthisspeciication.

Ifabuiltinfunctionobjectisimplementedasanexoticobjectitmusthavetheordinaryobjectbehaviourspeciiedin9.1.All
suchexoticfunctionobjectsalsohave[[Prototype]],[[Extensible]],[[Realm]],and[[ScriptOrModule]]internalslots.

Unlessotherwisespeciiedeverybuiltinfunctionobjecthasthe%FunctionPrototype%objectastheinitialvalueofits
[[Prototype]]internalslot.

Thebehaviourspeciiedforeachbuiltinfunctionviaalgorithmstepsorothermeansisthespeciicationofthefunctionbody
behaviourforboth[[Call]]and[[Construct]]invocationsofthefunction.However,[[Construct]]invocationisnotsupported
byallbuiltinfunctions.Foreachbuiltinfunction,wheninvokedwith[[Call]],the[[Call]]thisArgumentprovidesthethis
value,the[[Call]]argumentsListprovidesthenamedparameters,andtheNewTargetvalueisundeined.Wheninvokedwith
[[Construct]],thethisvalueisuninitialized,the[[Construct]]argumentsListprovidesthenamedparameters,andthe
[[Construct]]newTargetparameterprovidestheNewTargetvalue.IfthebuiltinfunctionisimplementedasanECMAScript
functionobjectthenthisspeciiedbehaviourmustbeimplementedbytheECMAScriptcodethatisthebodyofthefunction.
BuiltinfunctionsthatareECMAScriptfunctionobjectsmustbestrictmodefunctions.Ifabuiltinconstructorhasany[[Call]]
behaviourotherthanthrowingaTypeErrorexception,anECMAScriptimplementationofthefunctionmustbedoneina
mannerthatdoesnotcausethefunction's[[FunctionKind]]internalslottohavethevalue"classConstructor".

Builtinfunctionobjectsthatarenotidentiiedasconstructorsdonotimplementthe[[Construct]]internalmethodunless
otherwisespeciiedinthedescriptionofaparticularfunction.Whenabuiltinconstructoriscalledaspartofanew
expressiontheargumentsListparameteroftheinvoked[[Construct]]internalmethodprovidesthevaluesforthebuiltin
constructor'snamedparameters.

Builtinfunctionsthatarenotconstructorsdonothaveaprototypepropertyunlessotherwisespeciiedinthedescription
ofaparticularfunction.

IfabuiltinfunctionobjectisnotimplementedasanECMAScriptfunctionitmustprovide[[Call]]and[[Construct]]internal
methodsthatconformtothefollowingdeinitions:

9.3.1 [[Call]](thisArgument,argumentsList)

The[[Call]]internalmethodforabuiltinfunctionobjectFiscalledwithparametersthisArgumentandargumentsList,aList
ofECMAScriptlanguagevalues.Thefollowingstepsaretaken:

1.LetcallerContextbetherunningexecutioncontext.
2.IfcallerContextisnotalreadysuspended,suspendcallerContext.
3.LetcalleeContextbeanewECMAScriptcodeexecutioncontext.
4.SettheFunctionofcalleeContexttoF.
5.LetcalleeRealmbethevalueofF's[[Realm]]internalslot.
6.SettheRealmofcalleeContexttocalleeRealm.
7.SettheScriptOrModuleofcalleeContexttothevalueofF's[[ScriptOrModule]]internalslot.
8.PerformanynecessaryimplementationdeinedinitializationofcalleeContext.
9.PushcalleeContextontotheexecutioncontextstack;calleeContextisnowtherunningexecutioncontext.
10.LetresultbetheCompletionRecordthatistheresultofevaluatingFinanimplementationdeinedmannerthat
conformstothespeciicationofF.thisArgumentisthethisvalue,argumentsListprovidesthenamedparameters,and
theNewTargetvalueisundeined.
11.RemovecalleeContextfromtheexecutioncontextstackandrestorecallerContextastherunningexecutioncontext.
12.Returnresult.

NOTE WhencalleeContextisremovedfromtheexecutioncontextstackitmustnotbedestroyedifithasbeen
suspendedandretainedbyanaccessiblegeneratorobjectforlaterresumption.

9.3.2 [[Construct]](argumentsList,newTarget)

The[[Construct]]internalmethodforbuiltinfunctionobjectFiscalledwithparametersargumentsListandnewTarget.The
stepsperformedarethesameas[[Call]](see9.3.1)exceptthatstep10isreplacedby:

10.LetresultbetheCompletionRecordthatistheresultofevaluatingFinanimplementationdeinedmannerthat
conformstothespeciicationofF.Thethisvalueisuninitialized,argumentsListprovidesthenamedparameters,and
newTargetprovidestheNewTargetvalue.

9.3.3 CreateBuiltinFunction(realm,steps,prototype[,internalSlotsList])

TheabstractoperationCreateBuiltinFunctiontakesargumentsrealm,prototype,andsteps.Theoptionalargument
internalSlotsListisaListofthenamesofadditionalinternalslotsthatmustbedeinedaspartoftheobject.Ifthelistisnot
provided,anewemptyListisused.CreateBuiltinFunctionreturnsabuiltinfunctionobjectcreatedbythefollowingsteps:

1.Assert:realmisaRealmRecord.
2.Assert:stepsiseitherasetofalgorithmstepsorotherdeinitionofafunction'sbehaviourprovidedinthisspeciication.
3.Letfuncbeanewbuiltinfunctionobjectthatwhencalledperformstheactiondescribedbysteps.Thenewfunction
objecthasinternalslotswhosenamesaretheelementsofinternalSlotsList.Theinitialvalueofeachofthoseinternal
slotsisundeined.
4.Setthe[[Realm]]internalslotoffunctorealm.
5.Setthe[[Prototype]]internalslotoffunctoprototype.
6.Setthe[[Extensible]]internalslotoffunctotrue.
7.Setthe[[ScriptOrModule]]internalslotoffunctonull.
8.Returnfunc.

EachbuiltinfunctiondeinedinthisspeciicationiscreatedasifbycallingtheCreateBuiltinFunctionabstractoperation,
unlessotherwisespeciied.

9.4 BuiltinExoticObjectInternalMethodsandSlots
Thisspeciicationdeinesseveralkindsofbuiltinexoticobjects.Theseobjectsgenerallybehavesimilartoordinaryobjects
exceptforafewspeciicsituations.Thefollowingexoticobjectsusetheordinaryobjectinternalmethodsexceptwhereitis
explicitlyspeciiedotherwisebelow:

9.4.1 BoundFunctionExoticObjects

Aboundfunctionisanexoticobjectthatwrapsanotherfunctionobject.Aboundfunctioniscallable(ithasa[[Call]]internal
methodandmayhavea[[Construct]]internalmethod).Callingaboundfunctiongenerallyresultsinacallofitswrapped
function.
BoundfunctionobjectsdonothavetheinternalslotsofECMAScriptfunctionobjectsdeinedinTable27.Insteadtheyhave
theinternalslotsdeinedinTable28.

Table28:InternalSlotsofExoticBoundFunctionObjects
InternalSlot Type Description

[[BoundTargetFunction]] Callable Thewrappedfunctionobject.


Object

[[BoundThis]] Any Thevaluethatisalwayspassedasthethisvaluewhencallingthewrapped


function.

[[BoundArguments]] ListofAny Alistofvalueswhoseelementsareusedastheirstargumentstoanycalltothe


wrappedfunction.

Boundfunctionobjectsprovidealloftheessentialinternalmethodsasspeciiedin9.1.However,theyusethefollowing
deinitionsfortheessentialinternalmethodsoffunctionobjects.

9.4.1.1 [[Call]](thisArgument,argumentsList)

Whenthe[[Call]]internalmethodofanexoticboundfunctionobject,F,whichwascreatedusingthebindfunctioniscalled
withparametersthisArgumentandargumentsList,aListofECMAScriptlanguagevalues,thefollowingstepsaretaken:

1.LettargetbethevalueofF's[[BoundTargetFunction]]internalslot.
2.LetboundThisbethevalueofF's[[BoundThis]]internalslot.
3.LetboundArgsbethevalueofF's[[BoundArguments]]internalslot.
4.LetargsbeanewlistcontainingthesamevaluesasthelistboundArgsinthesameorderfollowedbythesamevaluesas
thelistargumentsListinthesameorder.
5.Return?Call(target,boundThis,args).

9.4.1.2 [[Construct]](argumentsList,newTarget)

Whenthe[[Construct]]internalmethodofanexoticboundfunctionobject,Fthatwascreatedusingthebindfunctionis
calledwithalistofargumentsargumentsListandnewTarget,thefollowingstepsaretaken:

1.LettargetbethevalueofF's[[BoundTargetFunction]]internalslot.
2.Assert:targethasa[[Construct]]internalmethod.
3.LetboundArgsbethevalueofF's[[BoundArguments]]internalslot.
4.LetargsbeanewlistcontainingthesamevaluesasthelistboundArgsinthesameorderfollowedbythesamevaluesas
thelistargumentsListinthesameorder.
5.IfSameValue(F,newTarget)istrue,letnewTargetbetarget.
6.Return?Construct(target,args,newTarget).

9.4.1.3 BoundFunctionCreate(targetFunction,boundThis,boundArgs)

TheabstractoperationBoundFunctionCreatewithargumentstargetFunction,boundThisandboundArgsisusedtospecifythe
creationofnewBoundFunctionexoticobjects.Itperformsthefollowingsteps:

1.Assert:Type(targetFunction)isObject.
2.Letprotobe?targetFunction.[[GetPrototypeOf]]().
3.Letobjbeanewlycreatedobject.
4.Setobj'sessentialinternalmethodstothedefaultordinaryobjectdeinitionsspeciiedin9.1.
5.Setthe[[Call]]internalmethodofobjasdescribedin9.4.1.1.
6.IftargetFunctionhasa[[Construct]]internalmethod,then
a.Setthe[[Construct]]internalmethodofobjasdescribedin9.4.1.2.
7.Setthe[[Prototype]]internalslotofobjtoproto.
8.Setthe[[Extensible]]internalslotofobjtotrue.
9.Setthe[[BoundTargetFunction]]internalslotofobjtotargetFunction.
10.Setthe[[BoundThis]]internalslotofobjtothevalueofboundThis.
11.Setthe[[BoundArguments]]internalslotofobjtoboundArgs.
12.Returnobj.

9.4.2 ArrayExoticObjects

AnArrayobjectisanexoticobjectthatgivesspecialtreatmenttoarrayindexpropertykeys(see6.1.7).Apropertywhose
propertynameisanarrayindexisalsocalledanelement.EveryArrayobjecthasalengthpropertywhosevalueisalwaysa
nonnegativeintegerlessthan232.Thevalueofthelengthpropertyisnumericallygreaterthanthenameofeveryown
propertywhosenameisanarrayindex;wheneveranownpropertyofanArrayobjectiscreatedorchanged,otherproperties
areadjustedasnecessarytomaintainthisinvariant.Speciically,wheneveranownpropertyisaddedwhosenameisanarray
index,thevalueofthelengthpropertyischanged,ifnecessary,tobeonemorethanthenumericvalueofthatarrayindex;
andwheneverthevalueofthelengthpropertyischanged,everyownpropertywhosenameisanarrayindexwhosevalueis
notsmallerthanthenewlengthisdeleted.ThisconstraintappliesonlytoownpropertiesofanArrayobjectandisunaffected
bylengthorarrayindexpropertiesthatmaybeinheritedfromitsprototypes.

NOTE AStringpropertynamePisanarrayindexifandonlyifToString(ToUint32(P))isequaltoPandToUint32(P)is
notequalto2321.

Arrayexoticobjectsalwayshaveanonconigurablepropertynamed"length".

Arrayexoticobjectsprovideanalternativedeinitionforthe[[DeineOwnProperty]]internalmethod.Exceptforthatinternal
method,Arrayexoticobjectsprovidealloftheotheressentialinternalmethodsasspeciiedin9.1.

9.4.2.1 [[DeineOwnProperty]](P,Desc)

Whenthe[[DeineOwnProperty]]internalmethodofanArrayexoticobjectAiscalledwithpropertykeyP,andProperty
DescriptorDesc,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.IfPis"length",then
a.Return?ArraySetLength(A,Desc).
3.ElseifPisanarrayindex,then
a.LetoldLenDescbeOrdinaryGetOwnProperty(A,"length").
b.Assert:oldLenDescwillneverbeundeinedoranaccessordescriptorbecauseArrayobjectsarecreatedwitha
lengthdatapropertythatcannotbedeletedorreconigured.
c.LetoldLenbeoldLenDesc.[[Value]].
d.Letindexbe!ToUint32(P).
e.IfindexoldLenandoldLenDesc.[[Writable]]isfalse,returnfalse.
f.Letsucceededbe!OrdinaryDeineOwnProperty(A,P,Desc).
g.Ifsucceededisfalse,returnfalse.
h.IfindexoldLen,then
i.SetoldLenDesc.[[Value]]toindex+1.
ii.LetsucceededbeOrdinaryDeineOwnProperty(A,"length",oldLenDesc).
iii.Assert:succeededistrue.
i.Returntrue.
4.ReturnOrdinaryDeineOwnProperty(A,P,Desc).

9.4.2.2 ArrayCreate(length[,proto])

TheabstractoperationArrayCreatewithargumentlength(either0orapositiveinteger)andoptionalargumentprotoisused
tospecifythecreationofnewArrayexoticobjects.Itperformsthefollowingsteps:

1.Assert:lengthisanintegerNumber0.
2.Iflengthis0,letlengthbe+0.
3.Iflength>2321,throwaRangeErrorexception.
4.Iftheprotoargumentwasnotpassed,letprotobetheintrinsicobject%ArrayPrototype%.
5.LetAbeanewlycreatedArrayexoticobject.
6.SetA'sessentialinternalmethodsexceptfor[[DeineOwnProperty]]tothedefaultordinaryobjectdeinitionsspeciied
in9.1.
7.Setthe[[DeineOwnProperty]]internalmethodofAasspeciiedin9.4.2.1.
8.Setthe[[Prototype]]internalslotofAtoproto.
9.Setthe[[Extensible]]internalslotofAtotrue.
10.Perform!OrdinaryDeineOwnProperty(A,"length",PropertyDescriptor{[[Value]]:length,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:false}).
11.ReturnA.

9.4.2.3 ArraySpeciesCreate(originalArray,length)

TheabstractoperationArraySpeciesCreatewithargumentsoriginalArrayandlengthisusedtospecifythecreationofanew
ArrayobjectusingaconstructorfunctionthatisderivedfromoriginalArray.Itperformsthefollowingsteps:

1.Assert:lengthisanintegerNumber0.
2.Iflengthis0,letlengthbe+0.
3.LetCbeundeined.
4.LetisArraybe?IsArray(originalArray).
5.IfisArrayistrue,then
a.LetCbe?Get(originalArray,"constructor").
b.IfIsConstructor(C)istrue,then
i.LetthisRealmbethecurrentRealmRecord.
ii.LetrealmCbe?GetFunctionRealm(C).
iii.IfthisRealmandrealmCarenotthesameRealmRecord,then
1.IfSameValue(C,realmC.[[Intrinsics]].[[%Array%]])istrue,letCbeundeined.
c.IfType(C)isObject,then
i.LetCbe?Get(C,@@species).
ii.IfCisnull,letCbeundeined.
6.IfCisundeined,return?ArrayCreate(length).
7.IfIsConstructor(C)isfalse,throwaTypeErrorexception.
8.Return?Construct(C,length).

NOTE IforiginalArraywascreatedusingthestandardbuiltinArrayconstructorforarealmthatisnottherealmof
therunningexecutioncontext,thenanewArrayiscreatedusingtherealmoftherunningexecutioncontext.
ThismaintainscompatibilitywithWebbrowsersthathavehistoricallyhadthatbehaviourforthe
Array.prototypemethodsthatnowaredeinedusingArraySpeciesCreate.

9.4.2.4 ArraySetLength(A,Desc)

WhentheabstractoperationArraySetLengthiscalledwithanArrayexoticobjectA,andPropertyDescriptorDesc,the
followingstepsaretaken:

1.Ifthe[[Value]]ieldofDescisabsent,then
a.ReturnOrdinaryDeineOwnProperty(A,"length",Desc).
2.LetnewLenDescbeacopyofDesc.
3.LetnewLenbe?ToUint32(Desc.[[Value]]).
4.LetnumberLenbe?ToNumber(Desc.[[Value]]).
5.IfnewLennumberLen,throwaRangeErrorexception.
6.SetnewLenDesc.[[Value]]tonewLen.
7.LetoldLenDescbeOrdinaryGetOwnProperty(A,"length").
8.Assert:oldLenDescwillneverbeundeinedoranaccessordescriptorbecauseArrayobjectsarecreatedwithalength
datapropertythatcannotbedeletedorreconigured.
9.LetoldLenbeoldLenDesc.[[Value]].
10.IfnewLenoldLen,then
a.ReturnOrdinaryDeineOwnProperty(A,"length",newLenDesc).
11.IfoldLenDesc.[[Writable]]isfalse,returnfalse.
12.IfnewLenDesc.[[Writable]]isabsentorhasthevaluetrue,letnewWritablebetrue.
13.Else,
a.Needtodefersettingthe[[Writable]]attributetofalseincaseanyelementscannotbedeleted.
b.LetnewWritablebefalse.
c.SetnewLenDesc.[[Writable]]totrue.
14.Letsucceededbe!OrdinaryDeineOwnProperty(A,"length",newLenDesc).
15.Ifsucceededisfalse,returnfalse.
16.WhilenewLen<oldLenrepeat,
a.SetoldLentooldLen1.
b.LetdeleteSucceededbe!A.[[Delete]](!ToString(oldLen)).
c.IfdeleteSucceededisfalse,then
i.SetnewLenDesc.[[Value]]tooldLen+1.
ii.IfnewWritableisfalse,setnewLenDesc.[[Writable]]tofalse.
iii.Letsucceededbe!OrdinaryDeineOwnProperty(A,"length",newLenDesc).
iv.Returnfalse.
17.IfnewWritableisfalse,then
a.ReturnOrdinaryDeineOwnProperty(A,"length",PropertyDescriptor{[[Writable]]:false}).Thiscallwillalways
returntrue.
18.Returntrue.

NOTE Insteps3and4,ifDesc.[[Value]]isanobjectthenitsvalueOfmethodiscalledtwice.Thisislegacybehaviour
thatwasspeciiedwiththiseffectstartingwiththe2ndEditionofthisspeciication.

9.4.3 StringExoticObjects

AStringobjectisanexoticobjectthatencapsulatesaStringvalueandexposesvirtualintegerindexeddataproperties
correspondingtotheindividualcodeunitelementsoftheStringvalue.ExoticStringobjectsalwayshaveadataproperty
named"length"whosevalueisthenumberofcodeunitelementsintheencapsulatedStringvalue.Boththecodeunitdata
propertiesandthe"length"propertyarenonwritableandnonconigurable.

ExoticStringobjectshavethesameinternalslotsasordinaryobjects.Theyalsohavea[[StringData]]internalslot.

ExoticStringobjectsprovidealternativedeinitionsforthefollowinginternalmethods.AlloftheotherexoticStringobject
essentialinternalmethodsthatarenotdeinedbelowareasspeciiedin9.1.

9.4.3.1 [[GetOwnProperty]](P)

Whenthe[[GetOwnProperty]]internalmethodofanexoticStringobjectSiscalledwithpropertykeyP,thefollowingsteps
aretaken:

1.Assert:IsPropertyKey(P)istrue.
2.LetdescbeOrdinaryGetOwnProperty(S,P).
3.Ifdescisnotundeined,returndesc.
4.IfType(P)isnotString,returnundeined.
5.Letindexbe!CanonicalNumericIndexString(P).
6.Ifindexisundeined,returnundeined.
7.IfIsInteger(index)isfalse,returnundeined.
8.Ifindex=0,returnundeined.
9.LetstrbetheStringvalueofthe[[StringData]]internalslotofS.
10.Letlenbethenumberofelementsinstr.
11.Ifindex<0orlenindex,returnundeined.
12.LetresultStrbeaStringvalueoflength1,containingonecodeunitfromstr,speciicallythecodeunitatindexindex.
13.ReturnaPropertyDescriptor{[[Value]]:resultStr,[[Writable]]:false,[[Enumerable]]:true,[[Conigurable]]:false}.
9.4.3.2 [[OwnPropertyKeys]]()

Whenthe[[OwnPropertyKeys]]internalmethodofaStringexoticobjectOiscalled,thefollowingstepsaretaken:

1.LetkeysbeanewemptyList.
2.LetstrbetheStringvalueofthe[[StringData]]internalslotofO.
3.Letlenbethenumberofelementsinstr.
4.Foreachintegeristartingwith0suchthati<len,inascendingorder,
a.Add!ToString(i)asthelastelementofkeys.
5.ForeachownpropertykeyPofOsuchthatPisanintegerindexandToInteger(P)len,inascendingnumericindex
order,
a.AddPasthelastelementofkeys.
6.ForeachownpropertykeyPofOsuchthatType(P)isStringandPisnotanintegerindex,inascendingchronological
orderofpropertycreation,
a.AddPasthelastelementofkeys.
7.ForeachownpropertykeyPofOsuchthatType(P)isSymbol,inascendingchronologicalorderofpropertycreation,
a.AddPasthelastelementofkeys.
8.Returnkeys.

9.4.3.3 StringCreate(value,prototype)

TheabstractoperationStringCreatewithargumentsvalueandprototypeisusedtospecifythecreationofnewexoticString
objects.Itperformsthefollowingsteps:

1.Assert:Type(value)isString.
2.LetSbeanewlycreatedStringexoticobject.
3.Setthe[[StringData]]internalslotofStovalue.
4.SetS'sessentialinternalmethodstothedefaultordinaryobjectdeinitionsspeciiedin9.1.
5.Setthe[[GetOwnProperty]]internalmethodofSasspeciiedin9.4.3.1.
6.Setthe[[OwnPropertyKeys]]internalmethodofSasspeciiedin9.4.3.2.
7.Setthe[[Prototype]]internalslotofStoprototype.
8.Setthe[[Extensible]]internalslotofStotrue.
9.Letlengthbethenumberofcodeunitelementsinvalue.
10.Perform!DeinePropertyOrThrow(S,"length",PropertyDescriptor{[[Value]]:length,[[Writable]]:false,
[[Enumerable]]:false,[[Conigurable]]:false}).
11.ReturnS.

9.4.4 ArgumentsExoticObjects

MostECMAScriptfunctionsmakeanargumentsobjectavailabletotheircode.Dependinguponthecharacteristicsofthe
functiondeinition,itsargumentsobjectiseitheranordinaryobjectoranargumentsexoticobject.Anargumentsexotic
objectisanexoticobjectwhosearrayindexpropertiesmaptotheformalparametersbindingsofaninvocationofits
associatedECMAScriptfunction.

Argumentsexoticobjectshavethesameinternalslotsasordinaryobjects.Theyalsohavea[[ParameterMap]]internalslot.
Ordinaryargumentsobjectsalsohavea[[ParameterMap]]internalslotwhosevalueisalwaysundeined.Forordinary
argumentobjectsthe[[ParameterMap]]internalslotisonlyusedbyObject.prototype.toString(19.1.3.6)toidentify
themassuch.

Argumentsexoticobjectsprovidealternativedeinitionsforthefollowinginternalmethods.Alloftheotherexoticarguments
objectessentialinternalmethodsthatarenotdeinedbelowareasspeciiedin9.1

NOTE1 Fornonstrictfunctionstheintegerindexeddatapropertiesofanargumentsobjectwhosenumericname
valuesarelessthanthenumberofformalparametersofthecorrespondingfunctionobjectinitiallysharetheir
valueswiththecorrespondingargumentbindingsinthefunction'sexecutioncontext.Thismeansthat
changingthepropertychangesthecorrespondingvalueoftheargumentbindingandviceversa.This
correspondenceisbrokenifsuchapropertyisdeletedandthenredeinedorifthepropertyischangedintoan
accessorproperty.Forstrictmodefunctions,thevaluesoftheargumentsobject'spropertiesaresimplyacopy
oftheargumentspassedtothefunctionandthereisnodynamiclinkagebetweenthepropertyvaluesandthe
formalparametervalues.

NOTE2 TheParameterMapobjectanditspropertyvaluesareusedasadeviceforspecifyingtheargumentsobject
correspondencetoargumentbindings.TheParameterMapobjectandtheobjectsthatarethevaluesofits
propertiesarenotdirectlyobservablefromECMAScriptcode.AnECMAScriptimplementationdoesnotneedto
actuallycreateorusesuchobjectstoimplementthespeciiedsemantics.

NOTE3 Argumentsobjectsforstrictmodefunctionsdeinenonconigurableaccessorpropertiesnamed"caller"
and"callee"whichthrowaTypeErrorexceptiononaccess.The"callee"propertyhasamorespeciic
meaningfornonstrictfunctionsanda"caller"propertyhashistoricallybeenprovidedasan
implementationdeinedextensionbysomeECMAScriptimplementations.Thestrictmodedeinitionofthese
propertiesexiststoensurethatneitherofthemisdeinedinanyothermannerbyconformingECMAScript
implementations.

9.4.4.1 [[GetOwnProperty]](P)

The[[GetOwnProperty]]internalmethodofanargumentsexoticobjectwhencalledwithapropertykeyPperformsthe
followingsteps:

1.Letargsbetheargumentsobject.
2.LetdescbeOrdinaryGetOwnProperty(args,P).
3.Ifdescisundeined,returndesc.
4.Letmapbethevalueofthe[[ParameterMap]]internalslotoftheargumentsobject.
5.LetisMappedbe!HasOwnProperty(map,P).
6.IfthevalueofisMappedistrue,then
a.Setdesc.[[Value]]toGet(map,P).
7.IfIsDataDescriptor(desc)istrueandPis"caller"anddesc.[[Value]]isastrictmodeFunctionobject,throwa
TypeErrorexception.
8.Returndesc.

Ifanimplementationdoesnotprovideabuiltincallerpropertyforargumentexoticobjectsthenstep7ofthisalgorithm
mustbeskipped.

9.4.4.2 [[DeineOwnProperty]](P,Desc)

The[[DeineOwnProperty]]internalmethodofanargumentsexoticobjectwhencalledwithapropertykeyPandProperty
DescriptorDescperformsthefollowingsteps:

1.Letargsbetheargumentsobject.
2.Letmapbethevalueofthe[[ParameterMap]]internalslotoftheargumentsobject.
3.LetisMappedbeHasOwnProperty(map,P).
4.LetnewArgDescbeDesc.
5.IfisMappedistrueandIsDataDescriptor(Desc)istrue,then
a.IfDesc.[[Value]]isnotpresentandDesc.[[Writable]]ispresentanditsvalueisfalse,then
i.LetnewArgDescbeacopyofDesc.
ii.SetnewArgDesc.[[Value]]toGet(map,P).
6.Letallowedbe?OrdinaryDeineOwnProperty(args,P,newArgDesc).
7.Ifallowedisfalse,returnfalse.
8.IfthevalueofisMappedistrue,then
a.IfIsAccessorDescriptor(Desc)istrue,then
i.Callmap.[[Delete]](P).
b.Else,
i.IfDesc.[[Value]]ispresent,then
1.LetsetStatusbeSet(map,P,Desc.[[Value]],false).
2.Assert:setStatusistruebecauseformalparametersmappedbyargumentobjectsarealwayswritable.
ii.IfDesc.[[Writable]]ispresentanditsvalueisfalse,then
1.Callmap.[[Delete]](P).
9.Returntrue.

9.4.4.3 [[Get]](P,Receiver)

The[[Get]]internalmethodofanargumentsexoticobjectwhencalledwithapropertykeyPandECMAScriptlanguagevalue
Receiverperformsthefollowingsteps:

1.Letargsbetheargumentsobject.
2.Letmapbethevalueofthe[[ParameterMap]]internalslotoftheargumentsobject.
3.LetisMappedbe!HasOwnProperty(map,P).
4.IfthevalueofisMappedisfalse,then
a.Return?OrdinaryGet(args,P,Receiver).
5.ElsemapcontainsaformalparametermappingforP,
a.ReturnGet(map,P).

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

The[[Set]]internalmethodofanargumentsexoticobjectwhencalledwithpropertykeyP,valueV,andECMAScript
languagevalueReceiverperformsthefollowingsteps:

1.Letargsbetheargumentsobject.
2.IfSameValue(args,Receiver)isfalse,then
a.LetisMappedbefalse.
3.Else,
a.Letmapbethevalueofthe[[ParameterMap]]internalslotoftheargumentsobject.
b.LetisMappedbe!HasOwnProperty(map,P).
4.IfisMappedistrue,then
a.LetsetStatusbeSet(map,P,V,false).
b.Assert:setStatusistruebecauseformalparametersmappedbyargumentobjectsarealwayswritable.
5.Return?OrdinarySet(args,P,V,Receiver).

9.4.4.5 [[HasProperty]](P)

The[[HasProperty]]internalmethodofanargumentsexoticobjectwhencalledwithpropertykeyP,performsthefollowing
steps:

1.Letargsbetheargumentsobject.
2.IfPis"caller",then
a.Letdescbe!OrdinaryGetOwnProperty(args,P).
b.IfIsDataDescriptor(desc)istrue,returntrue.
3.Return?OrdinaryHasProperty(args,P).

Ifanimplementationdoesnotprovideabuiltincallerpropertyforargumentexoticobjectsthenstep2ofthisalgorithm
mustbeskipped.

9.4.4.6 [[Delete]](P)

The[[Delete]]internalmethodofanargumentsexoticobjectwhencalledwithapropertykeyPperformsthefollowingsteps:

1.Letargsbetheargumentsobject.
2.Letmapbethevalueofthe[[ParameterMap]]internalslotofargs.
3.LetisMappedbe!HasOwnProperty(map,P).
4.Letresultbe?OrdinaryDelete(args,P).
5.IfresultistrueandthevalueofisMappedistrue,then
a.Callmap.[[Delete]](P).
6.Returnresult.
9.4.4.7 CreateUnmappedArgumentsObject(argumentsList)

TheabstractoperationCreateUnmappedArgumentsObjectcalledwithanargumentargumentsListperformsthefollowing
steps:

1.LetlenbethenumberofelementsinargumentsList.
2.LetobjbeObjectCreate(%ObjectPrototype%,[[ParameterMap]]).
3.Setobj's[[ParameterMap]]internalslottoundeined.
4.PerformDeinePropertyOrThrow(obj,"length",PropertyDescriptor{[[Value]]:len,[[Writable]]:true,[[Enumerable]]:
false,[[Conigurable]]:true}).
5.Letindexbe0.
6.Repeatwhileindex<len,
a.LetvalbeargumentsList[index].
b.PerformCreateDataProperty(obj,!ToString(index),val).
c.Letindexbeindex+1.
7.Perform!DeinePropertyOrThrow(obj,@@iterator,PropertyDescriptor{[[Value]]:%ArrayProto_values%,[[Writable]]:
true,[[Enumerable]]:false,[[Conigurable]]:true}).
8.Perform!DeinePropertyOrThrow(obj,"callee",PropertyDescriptor{[[Get]]:%ThrowTypeError%,[[Set]]:
%ThrowTypeError%,[[Enumerable]]:false,[[Conigurable]]:false}).
9.Perform!DeinePropertyOrThrow(obj,"caller",PropertyDescriptor{[[Get]]:%ThrowTypeError%,[[Set]]:
%ThrowTypeError%,[[Enumerable]]:false,[[Conigurable]]:false}).
10.Returnobj.

9.4.4.8 CreateMappedArgumentsObject(func,formals,argumentsList,env)

TheabstractoperationCreateMappedArgumentsObjectiscalledwithobjectfunc,parsedgrammarphraseformals,List
argumentsList,andEnvironmentRecordenv.Thefollowingstepsareperformed:

1.Assert:formalsdoesnotcontainarestparameter,anybindingpatterns,oranyinitializers.Itmaycontainduplicate
identiiers.
2.LetlenbethenumberofelementsinargumentsList.
3.Letobjbeanewlycreatedargumentsexoticobjectwitha[[ParameterMap]]internalslot.
4.Setthe[[GetOwnProperty]]internalmethodofobjasspeciiedin9.4.4.1.
5.Setthe[[DeineOwnProperty]]internalmethodofobjasspeciiedin9.4.4.2.
6.Setthe[[Get]]internalmethodofobjasspeciiedin9.4.4.3.
7.Setthe[[Set]]internalmethodofobjasspeciiedin9.4.4.4.
8.Setthe[[HasProperty]]internalmethodofobjasspeciiedin9.4.4.5.
9.Setthe[[Delete]]internalmethodofobjasspeciiedin9.4.4.6.
10.Settheremainderofobj'sessentialinternalmethodstothedefaultordinaryobjectdeinitionsspeciiedin9.1.
11.Setthe[[Prototype]]internalslotofobjto%ObjectPrototype%.
12.Setthe[[Extensible]]internalslotofobjtotrue.
13.LetmapbeObjectCreate(null).
14.Setthe[[ParameterMap]]internalslotofobjtomap.
15.LetparameterNamesbetheBoundNamesofformals.
16.LetnumberOfParametersbethenumberofelementsinparameterNames.
17.Letindexbe0.
18.Repeatwhileindex<len,
a.LetvalbeargumentsList[index].
b.PerformCreateDataProperty(obj,!ToString(index),val).
c.Letindexbeindex+1.
19.PerformDeinePropertyOrThrow(obj,"length",PropertyDescriptor{[[Value]]:len,[[Writable]]:true,[[Enumerable]]:
false,[[Conigurable]]:true}).
20.LetmappedNamesbeanewemptyList.
21.LetindexbenumberOfParameters1.
22.Repeatwhileindex0,
a.LetnamebeparameterNames[index].
b.IfnameisnotanelementofmappedNames,then
i.AddnameasanelementofthelistmappedNames.
ii.Ifindex<len,then
1.LetgbeMakeArgGetter(name,env).
2.LetpbeMakeArgSetter(name,env).
3.Performmap.[[DeineOwnProperty]](!ToString(index),PropertyDescriptor{[[Set]]:p,[[Get]]:g,
[[Enumerable]]:false,[[Conigurable]]:true}).
c.Letindexbeindex1.
23.Perform!DeinePropertyOrThrow(obj,@@iterator,PropertyDescriptor{[[Value]]:%ArrayProto_values%,[[Writable]]:
true,[[Enumerable]]:false,[[Conigurable]]:true}).
24.Perform!DeinePropertyOrThrow(obj,"callee",PropertyDescriptor{[[Value]]:func,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:true}).
25.Returnobj.

9.4.4.8.1 MakeArgGetter(name,env)

TheabstractoperationMakeArgGettercalledwithStringnameandEnvironmentRecordenvcreatesabuiltinfunctionobject
thatwhenexecutedreturnsthevalueboundfornameinenv.Itperformsthefollowingsteps:

1.LetrealmbethecurrentRealmRecord.
2.LetstepsbethestepsofanArgGetterfunctionasspeciiedbelow.
3.LetgetterbeCreateBuiltinFunction(realm,steps,%FunctionPrototype%,[[Name]],[[Env]]).
4.Setgetter's[[Name]]internalslottoname.
5.Setgetter's[[Env]]internalslottoenv.
6.Returngetter.

AnArgGetterfunctionisananonymousbuiltinfunctionwith[[Name]]and[[Env]]internalslots.WhenanArgGetter
functionfthatexpectsnoargumentsiscalleditperformsthefollowingsteps:

1.Letnamebethevalueoff's[[Name]]internalslot.
2.Letenvbethevalueoff's[[Env]]internalslot.
3.Returnenv.GetBindingValue(name,false).

NOTE ArgGetterfunctionsareneverdirectlyaccessibletoECMAScriptcode.

9.4.4.8.2 MakeArgSetter(name,env)

TheabstractoperationMakeArgSettercalledwithStringnameandEnvironmentRecordenvcreatesabuiltinfunctionobject
thatwhenexecutedsetsthevalueboundfornameinenv.Itperformsthefollowingsteps:

1.LetrealmbethecurrentRealmRecord.
2.LetstepsbethestepsofanArgSetterfunctionasspeciiedbelow.
3.LetsetterbeCreateBuiltinFunction(realm,steps,%FunctionPrototype%,[[Name]],[[Env]]).
4.Setsetter's[[Name]]internalslottoname.
5.Setsetter's[[Env]]internalslottoenv.
6.Returnsetter.

AnArgSetterfunctionisananonymousbuiltinfunctionwith[[Name]]and[[Env]]internalslots.WhenanArgSetter
functionfiscalledwithargumentvalueitperformsthefollowingsteps:

1.Letnamebethevalueoff's[[Name]]internalslot.
2.Letenvbethevalueoff's[[Env]]internalslot.
3.Returnenv.SetMutableBinding(name,value,false).

NOTE ArgSetterfunctionsareneverdirectlyaccessibletoECMAScriptcode.

9.4.5 IntegerIndexedExoticObjects
AnIntegerIndexedobjectisanexoticobjectthatperformsspecialhandlingofintegerindexpropertykeys.

IntegerIndexedexoticobjectshavethesameinternalslotsasordinaryobjectsandadditionally[[ViewedArrayBuffer]],
[[ArrayLength]],[[ByteOffset]],and[[TypedArrayName]]internalslots.

IntegerIndexedexoticobjectsprovidealternativedeinitionsforthefollowinginternalmethods.AlloftheotherInteger
Indexedexoticobjectessentialinternalmethodsthatarenotdeinedbelowareasspeciiedin9.1.

9.4.5.1 [[GetOwnProperty]](P)

Whenthe[[GetOwnProperty]]internalmethodofanIntegerIndexedexoticobjectOiscalledwithpropertykeyP,the
followingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Assert:OisanObjectthathasa[[ViewedArrayBuffer]]internalslot.
3.IfType(P)isString,then
a.LetnumericIndexbe!CanonicalNumericIndexString(P).
b.IfnumericIndexisnotundeined,then
i.Letvaluebe?IntegerIndexedElementGet(O,numericIndex).
ii.Ifvalueisundeined,returnundeined.
iii.ReturnaPropertyDescriptor{[[Value]]:value,[[Writable]]:true,[[Enumerable]]:true,[[Conigurable]]:
false}.
4.ReturnOrdinaryGetOwnProperty(O,P).

9.4.5.2 [[HasProperty]](P)

Whenthe[[HasProperty]]internalmethodofanIntegerIndexedexoticobjectOiscalledwithpropertykeyP,thefollowing
stepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Assert:OisanObjectthathasa[[ViewedArrayBuffer]]internalslot.
3.IfType(P)isString,then
a.LetnumericIndexbe!CanonicalNumericIndexString(P).
b.IfnumericIndexisnotundeined,then
i.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
ii.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
iii.IfIsInteger(numericIndex)isfalse,returnfalse.
iv.IfnumericIndex=0,returnfalse.
v.IfnumericIndex<0,returnfalse.
vi.IfnumericIndexthevalueofO's[[ArrayLength]]internalslot,returnfalse.
vii.Returntrue.
4.Return?OrdinaryHasProperty(O,P).

9.4.5.3 [[DeineOwnProperty]](P,Desc)

Whenthe[[DeineOwnProperty]]internalmethodofanIntegerIndexedexoticobjectOiscalledwithpropertykeyP,and
PropertyDescriptorDesc,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Assert:OisanObjectthathasa[[ViewedArrayBuffer]]internalslot.
3.IfType(P)isString,then
a.LetnumericIndexbe!CanonicalNumericIndexString(P).
b.IfnumericIndexisnotundeined,then
i.IfIsInteger(numericIndex)isfalse,returnfalse.
ii.LetintIndexbenumericIndex.
iii.IfintIndex=0,returnfalse.
iv.IfintIndex<0,returnfalse.
v.LetlengthbethevalueofO's[[ArrayLength]]internalslot.
vi.IfintIndexlength,returnfalse.
vii.IfIsAccessorDescriptor(Desc)istrue,returnfalse.
viii.IfDeschasa[[Conigurable]]ieldandifDesc.[[Conigurable]]istrue,returnfalse.
ix.IfDeschasan[[Enumerable]]ieldandifDesc.[[Enumerable]]isfalse,returnfalse.
x.IfDeschasa[[Writable]]ieldandifDesc.[[Writable]]isfalse,returnfalse.
xi.IfDeschasa[[Value]]ield,then
1.LetvaluebeDesc.[[Value]].
2.Return?IntegerIndexedElementSet(O,intIndex,value).
xii.Returntrue.
4.ReturnOrdinaryDeineOwnProperty(O,P,Desc).

9.4.5.4 [[Get]](P,Receiver)

Whenthe[[Get]]internalmethodofanIntegerIndexedexoticobjectOiscalledwithpropertykeyPandECMAScript
languagevalueReceiver,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.IfType(P)isString,then
a.LetnumericIndexbe!CanonicalNumericIndexString(P).
b.IfnumericIndexisnotundeined,then
i.Return?IntegerIndexedElementGet(O,numericIndex).
3.Return?OrdinaryGet(O,P,Receiver).

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

Whenthe[[Set]]internalmethodofanIntegerIndexedexoticobjectOiscalledwithpropertykeyP,valueV,andECMAScript
languagevalueReceiver,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.IfType(P)isString,then
a.LetnumericIndexbe!CanonicalNumericIndexString(P).
b.IfnumericIndexisnotundeined,then
i.Return?IntegerIndexedElementSet(O,numericIndex,V).
3.Return?OrdinarySet(O,P,V,Receiver).

9.4.5.6 [[OwnPropertyKeys]]()

Whenthe[[OwnPropertyKeys]]internalmethodofanIntegerIndexedexoticobjectOiscalled,thefollowingstepsaretaken:

1.LetkeysbeanewemptyList.
2.Assert:OisanObjectthathas[[ViewedArrayBuffer]],[[ArrayLength]],[[ByteOffset]],and[[TypedArrayName]]internal
slots.
3.LetlenbethevalueofO's[[ArrayLength]]internalslot.
4.Foreachintegeristartingwith0suchthati<len,inascendingorder,
a.Add!ToString(i)asthelastelementofkeys.
5.ForeachownpropertykeyPofOsuchthatType(P)isStringandPisnotanintegerindex,inascendingchronological
orderofpropertycreation
a.AddPasthelastelementofkeys.
6.ForeachownpropertykeyPofOsuchthatType(P)isSymbol,inascendingchronologicalorderofpropertycreation
a.AddPasthelastelementofkeys.
7.Returnkeys.

9.4.5.7 IntegerIndexedObjectCreate(prototype,internalSlotsList)

TheabstractoperationIntegerIndexedObjectCreatewithargumentsprototypeandinternalSlotsListisusedtospecifythe
creationofnewIntegerIndexedexoticobjects.TheargumentinternalSlotsListisaListofthenamesofadditionalinternal
slotsthatmustbedeinedaspartoftheobject.IntegerIndexedObjectCreateperformsthefollowingsteps:

1.Assert:internalSlotsListcontainsthenames[[ViewedArrayBuffer]],[[ArrayLength]],[[ByteOffset]],and
[[TypedArrayName]].
2.LetAbeanewlycreatedobjectwithaninternalslotforeachnameininternalSlotsList.
3.SetA'sessentialinternalmethodstothedefaultordinaryobjectdeinitionsspeciiedin9.1.
4.Setthe[[GetOwnProperty]]internalmethodofAasspeciiedin9.4.5.1.
5.Setthe[[HasProperty]]internalmethodofAasspeciiedin9.4.5.2.
6.Setthe[[DeineOwnProperty]]internalmethodofAasspeciiedin9.4.5.3.
7.Setthe[[Get]]internalmethodofAasspeciiedin9.4.5.4.
8.Setthe[[Set]]internalmethodofAasspeciiedin9.4.5.5.
9.Setthe[[OwnPropertyKeys]]internalmethodofAasspeciiedin9.4.5.6.
10.Setthe[[Prototype]]internalslotofAtoprototype.
11.Setthe[[Extensible]]internalslotofAtotrue.
12.ReturnA.

9.4.5.8 IntegerIndexedElementGet(O,index)

TheabstractoperationIntegerIndexedElementGetwithargumentsOandindexperformsthefollowingsteps:

1.Assert:Type(index)isNumber.
2.Assert:OisanObjectthathas[[ViewedArrayBuffer]],[[ArrayLength]],[[ByteOffset]],and[[TypedArrayName]]internal
slots.
3.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
4.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
5.IfIsInteger(index)isfalse,returnundeined.
6.Ifindex=0,returnundeined.
7.LetlengthbethevalueofO's[[ArrayLength]]internalslot.
8.Ifindex<0orindexlength,returnundeined.
9.LetoffsetbethevalueofO's[[ByteOffset]]internalslot.
10.LetarrayTypeNamebetheStringvalueofO's[[TypedArrayName]]internalslot.
11.LetelementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forarrayTypeName.
12.LetindexedPositionbe(indexelementSize)+offset.
13.LetelementTypebetheStringvalueoftheElementTypevalueinTable50forarrayTypeName.
14.ReturnGetValueFromBuffer(buffer,indexedPosition,elementType).

9.4.5.9 IntegerIndexedElementSet(O,index,value)

TheabstractoperationIntegerIndexedElementSetwithargumentsO,index,andvalueperformsthefollowingsteps:

1.Assert:Type(index)isNumber.
2.Assert:OisanObjectthathas[[ViewedArrayBuffer]],[[ArrayLength]],[[ByteOffset]],and[[TypedArrayName]]internal
slots.
3.LetnumValuebe?ToNumber(value).
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
6.IfIsInteger(index)isfalse,returnfalse.
7.Ifindex=0,returnfalse.
8.LetlengthbethevalueofO's[[ArrayLength]]internalslot.
9.Ifindex<0orindexlength,returnfalse.
10.LetoffsetbethevalueofO's[[ByteOffset]]internalslot.
11.LetarrayTypeNamebetheStringvalueofO's[[TypedArrayName]]internalslot.
12.LetelementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forarrayTypeName.
13.LetindexedPositionbe(indexelementSize)+offset.
14.LetelementTypebetheStringvalueoftheElementTypevalueinTable50forarrayTypeName.
15.PerformSetValueInBuffer(buffer,indexedPosition,elementType,numValue).
16.Returntrue.

9.4.6 ModuleNamespaceExoticObjects

AmodulenamespaceobjectisanexoticobjectthatexposesthebindingsexportedfromanECMAScriptModule(See15.2.3).
ThereisaonetoonecorrespondencebetweentheStringkeyedownpropertiesofamodulenamespaceexoticobjectand
thebindingnamesexportedbytheModule.Theexportedbindingsincludeanybindingsthatareindirectlyexportedusing
export*exportitems.EachStringvaluedownpropertykeyistheStringValueofthecorrespondingexportedbinding
name.ThesearetheonlyStringkeyedpropertiesofamodulenamespaceexoticobject.Eachsuchpropertyhastheattributes
{[[Writable]]:true,[[Enumerable]]:true,[[Conigurable]]:false}.Modulenamespaceobjectsarenotextensible.

ModulenamespaceobjectshavetheinternalslotsdeinedinTable29.

Table29:InternalSlotsofModuleNamespaceExoticObjects
Internal Type Description
Slot

[[Module]] Module TheModuleRecordwhoseexportsthisnamespaceexposes.


Record

[[Exports]] Listof AListcontainingtheStringvaluesoftheexportednamesexposedasownpropertiesofthisobject.


String ThelistisorderedasifanArrayofthoseStringvalueshadbeensortedusing
Array.prototype.sortusingSortCompareascomparefn.

Modulenamespaceexoticobjectsprovidealternativedeinitionsforalloftheinternalmethods.

9.4.6.1 [[GetPrototypeOf]]()

Whenthe[[GetPrototypeOf]]internalmethodofamodulenamespaceexoticobjectOiscalled,thefollowingstepsaretaken:

1.Returnnull.

9.4.6.2 [[SetPrototypeOf]](V)

Whenthe[[SetPrototypeOf]]internalmethodofamodulenamespaceexoticobjectOiscalledwithargumentV,thefollowing
stepsaretaken:

1.Assert:EitherType(V)isObjectorType(V)isNull.
2.Returnfalse.

9.4.6.3 [[IsExtensible]]()

Whenthe[[IsExtensible]]internalmethodofamodulenamespaceexoticobjectOiscalled,thefollowingstepsaretaken:

1.Returnfalse.

9.4.6.4 [[PreventExtensions]]()

Whenthe[[PreventExtensions]]internalmethodofamodulenamespaceexoticobjectOiscalled,thefollowingstepsare
taken:

1.Returntrue.

9.4.6.5 [[GetOwnProperty]](P)

Whenthe[[GetOwnProperty]]internalmethodofamodulenamespaceexoticobjectOiscalledwithpropertykeyP,the
followingstepsaretaken:

1.IfType(P)isSymbol,returnOrdinaryGetOwnProperty(O,P).
2.LetexportsbethevalueofO's[[Exports]]internalslot.
3.IfPisnotanelementofexports,returnundeined.
4.Letvaluebe?O.[[Get]](P,O).
5.ReturnPropertyDescriptor{[[Value]]:value,[[Writable]]:true,[[Enumerable]]:true,[[Conigurable]]:false}.

9.4.6.6 [[DeineOwnProperty]](P,Desc)

Whenthe[[DeineOwnProperty]]internalmethodofamodulenamespaceexoticobjectOiscalledwithpropertykeyPand
PropertyDescriptorDesc,thefollowingstepsaretaken:

1.Returnfalse.

9.4.6.7 [[HasProperty]](P)

Whenthe[[HasProperty]]internalmethodofamodulenamespaceexoticobjectOiscalledwithpropertykeyP,thefollowing
stepsaretaken:

1.IfType(P)isSymbol,returnOrdinaryHasProperty(O,P).
2.LetexportsbethevalueofO's[[Exports]]internalslot.
3.IfPisanelementofexports,returntrue.
4.Returnfalse.

9.4.6.8 [[Get]](P,Receiver)

Whenthe[[Get]]internalmethodofamodulenamespaceexoticobjectOiscalledwithpropertykeyPandECMAScript
languagevalueReceiver,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.IfType(P)isSymbol,then
a.Return?OrdinaryGet(O,P,Receiver).
3.LetexportsbethevalueofO's[[Exports]]internalslot.
4.IfPisnotanelementofexports,returnundeined.
5.LetmbethevalueofO's[[Module]]internalslot.
6.Letbindingbe?m.ResolveExport(P,,).
7.Assert:bindingisneithernullnor"ambiguous".
8.LettargetModulebebinding.[[Module]].
9.Assert:targetModuleisnotundeined.
10.LettargetEnvbetargetModule.[[Environment]].
11.IftargetEnvisundeined,throwaReferenceErrorexception.
12.LettargetEnvRecbetargetEnv'sEnvironmentRecord.
13.Return?targetEnvRec.GetBindingValue(binding.[[BindingName]],true).

NOTE ResolveExportisidempotentandsideeffectfree.Animplementationmightchoosetoprecomputeorcache
theResolveExportresultsforthe[[Exports]]ofeachmodulenamespaceexoticobject.

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

Whenthe[[Set]]internalmethodofamodulenamespaceexoticobjectOiscalledwithpropertykeyP,valueV,and
ECMAScriptlanguagevalueReceiver,thefollowingstepsaretaken:

1.Returnfalse.

9.4.6.10 [[Delete]](P)

Whenthe[[Delete]]internalmethodofamodulenamespaceexoticobjectOiscalledwithpropertykeyP,thefollowingsteps
aretaken:

1.Assert:IsPropertyKey(P)istrue.
2.LetexportsbethevalueofO's[[Exports]]internalslot.
3.IfPisanelementofexports,returnfalse.
4.Returntrue.

9.4.6.11 [[OwnPropertyKeys]]()

Whenthe[[OwnPropertyKeys]]internalmethodofamodulenamespaceexoticobjectOiscalled,thefollowingstepsare
taken:

1.LetexportsbeacopyofthevalueofO's[[Exports]]internalslot.
2.LetsymbolKeysbe!OrdinaryOwnPropertyKeys(O).
3.AppendalltheentriesofsymbolKeystotheendofexports.
4.Returnexports.

9.4.6.12 ModuleNamespaceCreate(module,exports)

TheabstractoperationModuleNamespaceCreatewithargumentsmodule,andexportsisusedtospecifythecreationofnew
modulenamespaceexoticobjects.Itperformsthefollowingsteps:

1.Assert:moduleisaModuleRecord.
2.Assert:module.[[Namespace]]isundeined.
3.Assert:exportsisaListofStringvalues.
4.LetMbeanewlycreatedobject.
5.SetM'sessentialinternalmethodstothedeinitionsspeciiedin9.4.6.
6.SetM's[[Module]]internalslottomodule.
7.SetM's[[Exports]]internalslottoexports.
8.CreateownpropertiesofMcorrespondingtothedeinitionsin26.3.
9.Setmodule.[[Namespace]]toM.
10.ReturnM.

9.4.7 ImmutablePrototypeExoticObjects

Animmutableprototypeexoticobjectisanexoticobjectthathasanimmutable[[Prototype]]internalslot.

9.4.7.1 [[SetPrototypeOf]](V)

Whenthe[[SetPrototypeOf]]internalmethodofanimmutableprototypeexoticobjectOiscalledwithargumentV,the
followingstepsaretaken:

1.Assert:EitherType(V)isObjectorType(V)isNull.
2.Letcurrentbethevalueofthe[[Prototype]]internalslotofO.
3.IfSameValue(V,current)istrue,returntrue.
4.Returnfalse.

9.5 ProxyObjectInternalMethodsandInternalSlots
AproxyobjectisanexoticobjectwhoseessentialinternalmethodsarepartiallyimplementedusingECMAScriptcode.Every
proxyobjectshasaninternalslotcalled[[ProxyHandler]].Thevalueof[[ProxyHandler]]isanobject,calledtheproxy's
handlerobject,ornull.Methods(seeTable30)ofahandlerobjectmaybeusedtoaugmenttheimplementationforoneor
moreoftheproxyobject'sinternalmethods.Everyproxyobjectalsohasaninternalslotcalled[[ProxyTarget]]whosevalue
iseitheranobjectorthenullvalue.Thisobjectiscalledtheproxy'stargetobject.
Table30:ProxyHandlerMethods
InternalMethod HandlerMethod

[[GetPrototypeOf]] getPrototypeOf

[[SetPrototypeOf]] setPrototypeOf

[[IsExtensible]] isExtensible

[[PreventExtensions]] preventExtensions

[[GetOwnProperty]] getOwnPropertyDescriptor

[[HasProperty]] has

[[Get]] get

[[Set]] set

[[Delete]] deleteProperty

[[DeineOwnProperty]] defineProperty

[[OwnPropertyKeys]] ownKeys

[[Call]] apply

[[Construct]] construct

Whenahandlermethodiscalledtoprovidetheimplementationofaproxyobjectinternalmethod,thehandlermethodis
passedtheproxy'stargetobjectasaparameter.Aproxy'shandlerobjectdoesnotnecessarilyhaveamethodcorresponding
toeveryessentialinternalmethod.Invokinganinternalmethodontheproxyresultsintheinvocationofthecorresponding
internalmethodontheproxy'stargetobjectifthehandlerobjectdoesnothaveamethodcorrespondingtotheinternaltrap.

The[[ProxyHandler]]and[[ProxyTarget]]internalslotsofaproxyobjectarealwaysinitializedwhentheobjectiscreated
andtypicallymaynotbemodiied.Someproxyobjectsarecreatedinamannerthatpermitsthemtobesubsequently
revoked.Whenaproxyisrevoked,its[[ProxyHandler]]and[[ProxyTarget]]internalslotsaresettonullcausingsubsequent
invocationsofinternalmethodsonthatproxyobjecttothrowaTypeErrorexception.

BecauseproxyobjectspermittheimplementationofinternalmethodstobeprovidedbyarbitraryECMAScriptcode,itis
possibletodeineaproxyobjectwhosehandlermethodsviolatestheinvariantsdeinedin6.1.7.3.Someoftheinternal
methodinvariantsdeinedin6.1.7.3areessentialintegrityinvariants.Theseinvariantsareexplicitlyenforcedbytheproxy
objectinternalmethodsspeciiedinthissection.AnECMAScriptimplementationmustberobustinthepresenceofall
possibleinvariantviolations.

Inthefollowingalgorithmdescriptions,assumeOisanECMAScriptproxyobject,Pisapropertykeyvalue,Visany
ECMAScriptlanguagevalueandDescisaPropertyDescriptorrecord.

9.5.1 [[GetPrototypeOf]]()

Whenthe[[GetPrototypeOf]]internalmethodofaProxyexoticobjectOiscalled,thefollowingstepsaretaken:

1.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
2.Ifhandlerisnull,throwaTypeErrorexception.
3.Assert:Type(handler)isObject.
4.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
5.Lettrapbe?GetMethod(handler,"getPrototypeOf").
6.Iftrapisundeined,then
a.Return?target.[[GetPrototypeOf]]().
7.LethandlerProtobe?Call(trap,handler,target).
8.IfType(handlerProto)isneitherObjectnorNull,throwaTypeErrorexception.
9.LetextensibleTargetbe?IsExtensible(target).
10.IfextensibleTargetistrue,returnhandlerProto.
11.LettargetProtobe?target.[[GetPrototypeOf]]().
12.IfSameValue(handlerProto,targetProto)isfalse,throwaTypeErrorexception.
13.ReturnhandlerProto.

NOTE [[GetPrototypeOf]]forproxyobjectsenforcesthefollowinginvariant:

Theresultof[[GetPrototypeOf]]mustbeeitheranObjectornull.
Ifthetargetobjectisnotextensible,[[GetPrototypeOf]]appliedtotheproxyobjectmustreturnthesame
valueas[[GetPrototypeOf]]appliedtotheproxyobject'stargetobject.

9.5.2 [[SetPrototypeOf]](V)

Whenthe[[SetPrototypeOf]]internalmethodofaProxyexoticobjectOiscalledwithargumentV,thefollowingstepsare
taken:

1.Assert:EitherType(V)isObjectorType(V)isNull.
2.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
3.Ifhandlerisnull,throwaTypeErrorexception.
4.Assert:Type(handler)isObject.
5.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
6.Lettrapbe?GetMethod(handler,"setPrototypeOf").
7.Iftrapisundeined,then
a.Return?target.[[SetPrototypeOf]](V).
8.LetbooleanTrapResultbeToBoolean(?Call(trap,handler,target,V)).
9.IfbooleanTrapResultisfalse,returnfalse.
10.LetextensibleTargetbe?IsExtensible(target).
11.IfextensibleTargetistrue,returntrue.
12.LettargetProtobe?target.[[GetPrototypeOf]]().
13.IfSameValue(V,targetProto)isfalse,throwaTypeErrorexception.
14.Returntrue.

NOTE [[SetPrototypeOf]]forproxyobjectsenforcesthefollowinginvariant:

Theresultof[[SetPrototypeOf]]isaBooleanvalue.
Ifthetargetobjectisnotextensible,theargumentvaluemustbethesameastheresultof
[[GetPrototypeOf]]appliedtotargetobject.

9.5.3 [[IsExtensible]]()

Whenthe[[IsExtensible]]internalmethodofaProxyexoticobjectOiscalled,thefollowingstepsaretaken:

1.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
2.Ifhandlerisnull,throwaTypeErrorexception.
3.Assert:Type(handler)isObject.
4.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
5.Lettrapbe?GetMethod(handler,"isExtensible").
6.Iftrapisundeined,then
a.Return?target.[[IsExtensible]]().
7.LetbooleanTrapResultbeToBoolean(?Call(trap,handler,target)).
8.LettargetResultbe?target.[[IsExtensible]]().
9.IfSameValue(booleanTrapResult,targetResult)isfalse,throwaTypeErrorexception.
10.ReturnbooleanTrapResult.
NOTE [[IsExtensible]]forproxyobjectsenforcesthefollowinginvariant:

Theresultof[[IsExtensible]]isaBooleanvalue.
[[IsExtensible]]appliedtotheproxyobjectmustreturnthesamevalueas[[IsExtensible]]appliedtothe
proxyobject'stargetobjectwiththesameargument.

9.5.4 [[PreventExtensions]]()

Whenthe[[PreventExtensions]]internalmethodofaProxyexoticobjectOiscalled,thefollowingstepsaretaken:

1.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
2.Ifhandlerisnull,throwaTypeErrorexception.
3.Assert:Type(handler)isObject.
4.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
5.Lettrapbe?GetMethod(handler,"preventExtensions").
6.Iftrapisundeined,then
a.Return?target.[[PreventExtensions]]().
7.LetbooleanTrapResultbeToBoolean(?Call(trap,handler,target)).
8.IfbooleanTrapResultistrue,then
a.LettargetIsExtensiblebe?target.[[IsExtensible]]().
b.IftargetIsExtensibleistrue,throwaTypeErrorexception.
9.ReturnbooleanTrapResult.

NOTE [[PreventExtensions]]forproxyobjectsenforcesthefollowinginvariant:

Theresultof[[PreventExtensions]]isaBooleanvalue.
[[PreventExtensions]]appliedtotheproxyobjectonlyreturnstrueif[[IsExtensible]]appliedtothe
proxyobject'stargetobjectisfalse.

9.5.5 [[GetOwnProperty]](P)

Whenthe[[GetOwnProperty]]internalmethodofaProxyexoticobjectOiscalledwithpropertykeyP,thefollowingsteps
aretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
3.Ifhandlerisnull,throwaTypeErrorexception.
4.Assert:Type(handler)isObject.
5.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
6.Lettrapbe?GetMethod(handler,"getOwnPropertyDescriptor").
7.Iftrapisundeined,then
a.Return?target.[[GetOwnProperty]](P).
8.LettrapResultObjbe?Call(trap,handler,target,P).
9.IfType(trapResultObj)isneitherObjectnorUndeined,throwaTypeErrorexception.
10.LettargetDescbe?target.[[GetOwnProperty]](P).
11.IftrapResultObjisundeined,then
a.IftargetDescisundeined,returnundeined.
b.IftargetDesc.[[Conigurable]]isfalse,throwaTypeErrorexception.
c.LetextensibleTargetbe?IsExtensible(target).
d.Assert:Type(extensibleTarget)isBoolean.
e.IfextensibleTargetisfalse,throwaTypeErrorexception.
f.Returnundeined.
12.LetextensibleTargetbe?IsExtensible(target).
13.LetresultDescbe?ToPropertyDescriptor(trapResultObj).
14.CallCompletePropertyDescriptor(resultDesc).
15.LetvalidbeIsCompatiblePropertyDescriptor(extensibleTarget,resultDesc,targetDesc).
16.Ifvalidisfalse,throwaTypeErrorexception.
17.IfresultDesc.[[Conigurable]]isfalse,then
a.IftargetDescisundeinedortargetDesc.[[Conigurable]]istrue,then
i.ThrowaTypeErrorexception.
18.ReturnresultDesc.

NOTE [[GetOwnProperty]]forproxyobjectsenforcesthefollowinginvariants:

Theresultof[[GetOwnProperty]]mustbeeitheranObjectorundeined.
Apropertycannotbereportedasnonexistent,ifitexistsasanonconigurableownpropertyofthe
targetobject.
Apropertycannotbereportedasnonexistent,ifitexistsasanownpropertyofthetargetobjectandthe
targetobjectisnotextensible.
Apropertycannotbereportedasexistent,ifitdoesnotexistsasanownpropertyofthetargetobjectand
thetargetobjectisnotextensible.
Apropertycannotbereportedasnonconigurable,ifitdoesnotexistsasanownpropertyofthetarget
objectorifitexistsasaconigurableownpropertyofthetargetobject.

9.5.6 [[DeineOwnProperty]](P,Desc)

Whenthe[[DeineOwnProperty]]internalmethodofaProxyexoticobjectOiscalledwithpropertykeyPandProperty
DescriptorDesc,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
3.Ifhandlerisnull,throwaTypeErrorexception.
4.Assert:Type(handler)isObject.
5.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
6.Lettrapbe?GetMethod(handler,"defineProperty").
7.Iftrapisundeined,then
a.Return?target.[[DeineOwnProperty]](P,Desc).
8.LetdescObjbeFromPropertyDescriptor(Desc).
9.LetbooleanTrapResultbeToBoolean(?Call(trap,handler,target,P,descObj)).
10.IfbooleanTrapResultisfalse,returnfalse.
11.LettargetDescbe?target.[[GetOwnProperty]](P).
12.LetextensibleTargetbe?IsExtensible(target).
13.IfDeschasa[[Conigurable]]ieldandifDesc.[[Conigurable]]isfalse,then
a.LetsettingConigFalsebetrue.
14.ElseletsettingConigFalsebefalse.
15.IftargetDescisundeined,then
a.IfextensibleTargetisfalse,throwaTypeErrorexception.
b.IfsettingConigFalseistrue,throwaTypeErrorexception.
16.ElsetargetDescisnotundeined,
a.IfIsCompatiblePropertyDescriptor(extensibleTarget,Desc,targetDesc)isfalse,throwaTypeErrorexception.
b.IfsettingConigFalseistrueandtargetDesc.[[Conigurable]]istrue,throwaTypeErrorexception.
17.Returntrue.

NOTE [[DeineOwnProperty]]forproxyobjectsenforcesthefollowinginvariants:

Theresultof[[DeineOwnProperty]]isaBooleanvalue.
Apropertycannotbeadded,ifthetargetobjectisnotextensible.
Apropertycannotbenonconigurable,unlessthereexistsacorrespondingnonconigurableown
propertyofthetargetobject.
IfapropertyhasacorrespondingtargetobjectpropertythenapplyingthePropertyDescriptorofthe
propertytothetargetobjectusing[[DeineOwnProperty]]willnotthrowanexception.
9.5.7 [[HasProperty]](P)

Whenthe[[HasProperty]]internalmethodofaProxyexoticobjectOiscalledwithpropertykeyP,thefollowingstepsare
taken:

1.Assert:IsPropertyKey(P)istrue.
2.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
3.Ifhandlerisnull,throwaTypeErrorexception.
4.Assert:Type(handler)isObject.
5.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
6.Lettrapbe?GetMethod(handler,"has").
7.Iftrapisundeined,then
a.Return?target.[[HasProperty]](P).
8.LetbooleanTrapResultbeToBoolean(?Call(trap,handler,target,P)).
9.IfbooleanTrapResultisfalse,then
a.LettargetDescbe?target.[[GetOwnProperty]](P).
b.IftargetDescisnotundeined,then
i.IftargetDesc.[[Conigurable]]isfalse,throwaTypeErrorexception.
ii.LetextensibleTargetbe?IsExtensible(target).
iii.IfextensibleTargetisfalse,throwaTypeErrorexception.
10.ReturnbooleanTrapResult.

NOTE [[HasProperty]]forproxyobjectsenforcesthefollowinginvariants:

Theresultof[[HasProperty]]isaBooleanvalue.
Apropertycannotbereportedasnonexistent,ifitexistsasanonconigurableownpropertyofthe
targetobject.
Apropertycannotbereportedasnonexistent,ifitexistsasanownpropertyofthetargetobjectandthe
targetobjectisnotextensible.

9.5.8 [[Get]](P,Receiver)

Whenthe[[Get]]internalmethodofaProxyexoticobjectOiscalledwithpropertykeyPandECMAScriptlanguagevalue
Receiver,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
3.Ifhandlerisnull,throwaTypeErrorexception.
4.Assert:Type(handler)isObject.
5.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
6.Lettrapbe?GetMethod(handler,"get").
7.Iftrapisundeined,then
a.Return?target.[[Get]](P,Receiver).
8.LettrapResultbe?Call(trap,handler,target,P,Receiver).
9.LettargetDescbe?target.[[GetOwnProperty]](P).
10.IftargetDescisnotundeined,then
a.IfIsDataDescriptor(targetDesc)istrueandtargetDesc.[[Conigurable]]isfalseandtargetDesc.[[Writable]]isfalse,
then
i.IfSameValue(trapResult,targetDesc.[[Value]])isfalse,throwaTypeErrorexception.
b.IfIsAccessorDescriptor(targetDesc)istrueandtargetDesc.[[Conigurable]]isfalseandtargetDesc.[[Get]]is
undeined,then
i.IftrapResultisnotundeined,throwaTypeErrorexception.
11.ReturntrapResult.

NOTE [[Get]]forproxyobjectsenforcesthefollowinginvariants:
Thevaluereportedforapropertymustbethesameasthevalueofthecorrespondingtargetobject
propertyifthetargetobjectpropertyisanonwritable,nonconigurableowndataproperty.
Thevaluereportedforapropertymustbeundeinedifthecorrespondingtargetobjectpropertyisa
nonconigurableownaccessorpropertythathasundeinedasits[[Get]]attribute.

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

Whenthe[[Set]]internalmethodofaProxyexoticobjectOiscalledwithpropertykeyP,valueV,andECMAScriptlanguage
valueReceiver,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
3.Ifhandlerisnull,throwaTypeErrorexception.
4.Assert:Type(handler)isObject.
5.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
6.Lettrapbe?GetMethod(handler,"set").
7.Iftrapisundeined,then
a.Return?target.[[Set]](P,V,Receiver).
8.LetbooleanTrapResultbeToBoolean(?Call(trap,handler,target,P,V,Receiver)).
9.IfbooleanTrapResultisfalse,returnfalse.
10.LettargetDescbe?target.[[GetOwnProperty]](P).
11.IftargetDescisnotundeined,then
a.IfIsDataDescriptor(targetDesc)istrueandtargetDesc.[[Conigurable]]isfalseandtargetDesc.[[Writable]]isfalse,
then
i.IfSameValue(V,targetDesc.[[Value]])isfalse,throwaTypeErrorexception.
b.IfIsAccessorDescriptor(targetDesc)istrueandtargetDesc.[[Conigurable]]isfalse,then
i.IftargetDesc.[[Set]]isundeined,throwaTypeErrorexception.
12.Returntrue.

NOTE [[Set]]forproxyobjectsenforcesthefollowinginvariants:

Theresultof[[Set]]isaBooleanvalue.
Cannotchangethevalueofapropertytobedifferentfromthevalueofthecorrespondingtargetobject
propertyifthecorrespondingtargetobjectpropertyisanonwritable,nonconigurableowndata
property.
Cannotsetthevalueofapropertyifthecorrespondingtargetobjectpropertyisanonconigurableown
accessorpropertythathasundeinedasits[[Set]]attribute.

9.5.10 [[Delete]](P)

Whenthe[[Delete]]internalmethodofaProxyexoticobjectOiscalledwithpropertykeyP,thefollowingstepsaretaken:

1.Assert:IsPropertyKey(P)istrue.
2.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
3.Ifhandlerisnull,throwaTypeErrorexception.
4.Assert:Type(handler)isObject.
5.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
6.Lettrapbe?GetMethod(handler,"deleteProperty").
7.Iftrapisundeined,then
a.Return?target.[[Delete]](P).
8.LetbooleanTrapResultbeToBoolean(?Call(trap,handler,target,P)).
9.IfbooleanTrapResultisfalse,returnfalse.
10.LettargetDescbe?target.[[GetOwnProperty]](P).
11.IftargetDescisundeined,returntrue.
12.IftargetDesc.[[Conigurable]]isfalse,throwaTypeErrorexception.
13.Returntrue.
NOTE [[Delete]]forproxyobjectsenforcesthefollowinginvariant:

Theresultof[[Delete]]isaBooleanvalue.
Apropertycannotbereportedasdeleted,ifitexistsasanonconigurableownpropertyofthetarget
object.

9.5.11 [[OwnPropertyKeys]]()

Whenthe[[OwnPropertyKeys]]internalmethodofaProxyexoticobjectOiscalled,thefollowingstepsaretaken:

1.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
2.Ifhandlerisnull,throwaTypeErrorexception.
3.Assert:Type(handler)isObject.
4.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
5.Lettrapbe?GetMethod(handler,"ownKeys").
6.Iftrapisundeined,then
a.Return?target.[[OwnPropertyKeys]]().
7.LettrapResultArraybe?Call(trap,handler,target).
8.LettrapResultbe?CreateListFromArrayLike(trapResultArray,String,Symbol).
9.LetextensibleTargetbe?IsExtensible(target).
10.LettargetKeysbe?target.[[OwnPropertyKeys]]().
11.Assert:targetKeysisaListcontainingonlyStringandSymbolvalues.
12.LettargetConigurableKeysbeanewemptyList.
13.LettargetNonconigurableKeysbeanewemptyList.
14.Repeat,foreachelementkeyoftargetKeys,
a.Letdescbe?target.[[GetOwnProperty]](key).
b.Ifdescisnotundeinedanddesc.[[Conigurable]]isfalse,then
i.AppendkeyasanelementoftargetNonconigurableKeys.
c.Else,
i.AppendkeyasanelementoftargetConigurableKeys.
15.IfextensibleTargetistrueandtargetNonconigurableKeysisempty,then
a.ReturntrapResult.
16.LetuncheckedResultKeysbeanewListwhichisacopyoftrapResult.
17.Repeat,foreachkeythatisanelementoftargetNonconigurableKeys,
a.IfkeyisnotanelementofuncheckedResultKeys,throwaTypeErrorexception.
b.RemovekeyfromuncheckedResultKeys.
18.IfextensibleTargetistrue,returntrapResult.
19.Repeat,foreachkeythatisanelementoftargetConigurableKeys,
a.IfkeyisnotanelementofuncheckedResultKeys,throwaTypeErrorexception.
b.RemovekeyfromuncheckedResultKeys.
20.IfuncheckedResultKeysisnotempty,throwaTypeErrorexception.
21.ReturntrapResult.

NOTE [[OwnPropertyKeys]]forproxyobjectsenforcesthefollowinginvariants:

Theresultof[[OwnPropertyKeys]]isaList.
TheTypeofeachresultListelementiseitherStringorSymbol.
TheresultListmustcontainthekeysofallnonconigurableownpropertiesofthetargetobject.
Ifthetargetobjectisnotextensible,thentheresultListmustcontainallthekeysoftheownpropertiesof
thetargetobjectandnoothervalues.

9.5.12 [[Call]](thisArgument,argumentsList)

The[[Call]]internalmethodofaProxyexoticobjectOiscalledwithparametersthisArgumentandargumentsList,aListof
ECMAScriptlanguagevalues.Thefollowingstepsaretaken:
1.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
2.Ifhandlerisnull,throwaTypeErrorexception.
3.Assert:Type(handler)isObject.
4.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
5.Lettrapbe?GetMethod(handler,"apply").
6.Iftrapisundeined,then
a.Return?Call(target,thisArgument,argumentsList).
7.LetargArraybeCreateArrayFromList(argumentsList).
8.Return?Call(trap,handler,target,thisArgument,argArray).

NOTE AProxyexoticobjectonlyhasa[[Call]]internalmethodiftheinitialvalueofits[[ProxyTarget]]internalslotis
anobjectthathasa[[Call]]internalmethod.

9.5.13 [[Construct]](argumentsList,newTarget)

The[[Construct]]internalmethodofaProxyexoticobjectOiscalledwithparametersargumentsListwhichisapossibly
emptyListofECMAScriptlanguagevaluesandnewTarget.Thefollowingstepsaretaken:

1.Lethandlerbethevalueofthe[[ProxyHandler]]internalslotofO.
2.Ifhandlerisnull,throwaTypeErrorexception.
3.Assert:Type(handler)isObject.
4.Lettargetbethevalueofthe[[ProxyTarget]]internalslotofO.
5.Lettrapbe?GetMethod(handler,"construct").
6.Iftrapisundeined,then
a.Assert:targethasa[[Construct]]internalmethod.
b.Return?Construct(target,argumentsList,newTarget).
7.LetargArraybeCreateArrayFromList(argumentsList).
8.LetnewObjbe?Call(trap,handler,target,argArray,newTarget).
9.IfType(newObj)isnotObject,throwaTypeErrorexception.
10.ReturnnewObj.

NOTE1 AProxyexoticobjectonlyhasa[[Construct]]internalmethodiftheinitialvalueofits[[ProxyTarget]]internal
slotisanobjectthathasa[[Construct]]internalmethod.

NOTE2 [[Construct]]forproxyobjectsenforcesthefollowinginvariants:

Theresultof[[Construct]]mustbeanObject.

9.5.14 ProxyCreate(target,handler)

TheabstractoperationProxyCreatewithargumentstargetandhandlerisusedtospecifythecreationofnewProxyexotic
objects.Itperformsthefollowingsteps:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.IftargetisaProxyexoticobjectandthevalueofthe[[ProxyHandler]]internalslotoftargetisnull,throwaTypeError
exception.
3.IfType(handler)isnotObject,throwaTypeErrorexception.
4.IfhandlerisaProxyexoticobjectandthevalueofthe[[ProxyHandler]]internalslotofhandlerisnull,throwa
TypeErrorexception.
5.LetPbeanewlycreatedobject.
6.SetP'sessentialinternalmethods(exceptfor[[Call]]and[[Construct]])tothedeinitionsspeciiedin9.5.
7.IfIsCallable(target)istrue,then
a.Setthe[[Call]]internalmethodofPasspeciiedin9.5.12.
b.Iftargethasa[[Construct]]internalmethod,then
i.Setthe[[Construct]]internalmethodofPasspeciiedin9.5.13.
8.Setthe[[ProxyTarget]]internalslotofPtotarget.
9.Setthe[[ProxyHandler]]internalslotofPtohandler.
10.ReturnP.

10 ECMAScriptLanguage:SourceCode
10.1 SourceText
Syntax

SourceCharacter ::
anyUnicodecodepoint

ECMAScriptcodeisexpressedusingUnicode,version8.0.0orlater.ECMAScriptsourcetextisasequenceofcodepoints.All
UnicodecodepointvaluesfromU+0000toU+10FFFF,includingsurrogatecodepoints,mayoccurinsourcetextwhere
permittedbytheECMAScriptgrammars.TheactualencodingsusedtostoreandinterchangeECMAScriptsourcetextisnot
relevanttothisspeciication.Regardlessoftheexternalsourcetextencoding,aconformingECMAScriptimplementation
processesthesourcetextasifitwasanequivalentsequenceofSourceCharactervalues,eachSourceCharacterbeinga
Unicodecodepoint.ConformingECMAScriptimplementationsarenotrequiredtoperformanynormalizationofsourcetext,
orbehaveasthoughtheywereperformingnormalizationofsourcetext.

ThecomponentsofacombiningcharactersequencearetreatedasindividualUnicodecodepointseventhoughausermight
thinkofthewholesequenceasasinglecharacter.

NOTE Instringliterals,regularexpressionliterals,templateliteralsandidentiiers,anyUnicodecodepointmayalso
beexpressedusingUnicodeescapesequencesthatexplicitlyexpressacodepoint'snumericvalue.Withina
comment,suchanescapesequenceiseffectivelyignoredaspartofthecomment.

ECMAScriptdiffersfromtheJavaprogramminglanguageinthebehaviourofUnicodeescapesequences.Ina
Javaprogram,iftheUnicodeescapesequence\u000A,forexample,occurswithinasinglelinecomment,itis
interpretedasalineterminator(UnicodecodepointU+000AisLINEFEED(LF))andthereforethenextcode
pointisnotpartofthecomment.Similarly,iftheUnicodeescapesequence\u000Aoccurswithinastring
literalinaJavaprogram,itislikewiseinterpretedasalineterminator,whichisnotallowedwithinastring
literalonemustwrite\ninsteadof\u000AtocauseaLINEFEED(LF)tobepartoftheStringvalueofa
stringliteral.InanECMAScriptprogram,aUnicodeescapesequenceoccurringwithinacommentisnever
interpretedandthereforecannotcontributetoterminationofthecomment.Similarly,aUnicodeescape
sequenceoccurringwithinastringliteralinanECMAScriptprogramalwayscontributestotheliteralandis
neverinterpretedasalineterminatororasacodepointthatmightterminatethestringliteral.

10.1.1 StaticSemantics:UTF16Encoding(cp)

TheUTF16Encodingofanumericcodepointvalue,cp,isdeterminedasfollows:

1.Assert:0cp0x10FFFF.
2.Ifcp65535,returncp.
3.Letcu1beloor((cp65536)/1024)+0xD800.
4.Letcu2be((cp65536)modulo1024)+0xDC00.
5.Returnthecodeunitsequenceconsistingofcu1followedbycu2.

10.1.2 StaticSemantics:UTF16Decode(lead,trail)

Twocodeunits,leadandtrail,thatformaUTF16surrogatepairareconvertedtoacodepointbyperformingthefollowing
steps:

1.Assert:0xD800lead0xDBFFand0xDC00trail0xDFFF.
2.Letcpbe(lead0xD800)1024+(trail0xDC00)+0x10000.
3.Returnthecodepointcp.
10.2 TypesofSourceCode
TherearefourtypesofECMAScriptcode:

GlobalcodeissourcetextthatistreatedasanECMAScriptScript.TheglobalcodeofaparticularScriptdoesnotinclude
anysourcetextthatisparsedaspartofaFunctionDeclaration,FunctionExpression,GeneratorDeclaration,
GeneratorExpression,MethodDeinition,ArrowFunction,ClassDeclaration,orClassExpression.
Evalcodeisthesourcetextsuppliedtothebuiltinevalfunction.Moreprecisely,iftheparametertothebuiltineval
functionisaString,itistreatedasanECMAScriptScript.Theevalcodeforaparticularinvocationofevalistheglobal
codeportionofthatScript.
Functioncodeissourcetextthatisparsedtosupplythevalueofthe[[ECMAScriptCode]]and[[FormalParameters]]
internalslots(see9.2)ofanECMAScriptfunctionobject.ThefunctioncodeofaparticularECMAScriptfunctiondoes
notincludeanysourcetextthatisparsedasthefunctioncodeofanestedFunctionDeclaration,FunctionExpression,
GeneratorDeclaration,GeneratorExpression,MethodDeinition,ArrowFunction,ClassDeclaration,orClassExpression.
ModulecodeissourcetextthatiscodethatisprovidedasaModuleBody.Itisthecodethatisdirectlyevaluatedwhena
moduleisinitialized.Themodulecodeofaparticularmoduledoesnotincludeanysourcetextthatisparsedaspartofa
nestedFunctionDeclaration,FunctionExpression,GeneratorDeclaration,GeneratorExpression,MethodDeinition,
ArrowFunction,ClassDeclaration,orClassExpression.

NOTE FunctioncodeisgenerallyprovidedasthebodiesofFunctionDeinitions(14.1),ArrowFunctionDeinitions
(14.2),MethodDeinitions(14.3)andGeneratorDeinitions(14.4).Functioncodeisalsoderivedfromthe
argumentstotheFunctionconstructor(19.2.1.1)andtheGeneratorFunctionconstructor(25.2.1.1).

10.2.1 StrictModeCode

AnECMAScriptScriptsyntacticunitmaybeprocessedusingeitherunrestrictedorstrictmodesyntaxandsemantics.Codeis
interpretedasstrictmodecodeinthefollowingsituations:

GlobalcodeisstrictmodecodeifitbeginswithaDirectiveProloguethatcontainsaUseStrictDirective.
Modulecodeisalwaysstrictmodecode.
AllpartsofaClassDeclarationoraClassExpressionarestrictmodecode.
EvalcodeisstrictmodecodeifitbeginswithaDirectiveProloguethatcontainsaUseStrictDirectiveorifthecallto
evalisadirectevalthatiscontainedinstrictmodecode.
FunctioncodeisstrictmodecodeiftheassociatedFunctionDeclaration,FunctionExpression,GeneratorDeclaration,
GeneratorExpression,MethodDeinition,orArrowFunctioniscontainedinstrictmodecodeorifthecodethatproduces
thevalueofthefunction's[[ECMAScriptCode]]internalslotbeginswithaDirectiveProloguethatcontainsaUseStrict
Directive.
FunctioncodethatissuppliedastheargumentstothebuiltinFunctionandGeneratorconstructorsisstrictmode
codeifthelastargumentisaStringthatwhenprocessedisaFunctionBodythatbeginswithaDirectiveProloguethat
containsaUseStrictDirective.

ECMAScriptcodethatisnotstrictmodecodeiscallednonstrictcode.

10.2.2 NonECMAScriptFunctions

AnECMAScriptimplementationmaysupporttheevaluationofexoticfunctionobjectswhoseevaluativebehaviouris
expressedinsomeimplementationdeinedformofexecutablecodeotherthanviaECMAScriptcode.Whetherafunction
objectisanECMAScriptcodefunctionoranonECMAScriptfunctionisnotsemanticallyobservablefromtheperspectiveof
anECMAScriptcodefunctionthatcallsoriscalledbysuchanonECMAScriptfunction.

11 ECMAScriptLanguage:LexicalGrammar
ThesourcetextofanECMAScriptScriptorModuleisirstconvertedintoasequenceofinputelements,whicharetokens,line
terminators,comments,orwhitespace.Thesourcetextisscannedfromlefttoright,repeatedlytakingthelongestpossible
sequenceofcodepointsasthenextinputelement.
Thereareseveralsituationswheretheidentiicationoflexicalinputelementsissensitivetothesyntacticgrammarcontext
thatisconsumingtheinputelements.Thisrequiresmultiplegoalsymbolsforthelexicalgrammar.The
InputElementRegExpOrTemplateTailgoalisusedinsyntacticgrammarcontextswhereaRegularExpressionLiteral,a
TemplateMiddle,oraTemplateTailispermitted.TheInputElementRegExpgoalsymbolisusedinallsyntacticgrammar
contextswhereaRegularExpressionLiteralispermittedbutneitheraTemplateMiddle,noraTemplateTailispermitted.The
InputElementTemplateTailgoalisusedinallsyntacticgrammarcontextswhereaTemplateMiddleoraTemplateTailis
permittedbutaRegularExpressionLiteralisnotpermitted.Inallothercontexts,InputElementDivisusedasthelexicalgoal
symbol.

NOTE Theuseofmultiplelexicalgoalsensuresthattherearenolexicalambiguitiesthatwouldaffectautomatic
semicoloninsertion.Forexample,therearenosyntacticgrammarcontextswherebothaleadingdivisionor
divisionassignment,andaleadingRegularExpressionLiteralarepermitted.Thisisnotaffectedbysemicolon
insertion(see11.9);inexamplessuchasthefollowing:

a=b
/hi/g.exec(c).map(d);

wheretheirstnonwhitespace,noncommentcodepointafteraLineTerminatorisU+002F(SOLIDUS)andthe
syntacticcontextallowsdivisionordivisionassignment,nosemicolonisinsertedattheLineTerminator.That
is,theaboveexampleisinterpretedinthesamewayas:

a=b/hi/g.exec(c).map(d);

Syntax
InputElementDiv ::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
RightBracePunctuator

InputElementRegExp ::
WhiteSpace
LineTerminator
Comment
CommonToken
RightBracePunctuator
RegularExpressionLiteral

InputElementRegExpOrTemplateTail ::
WhiteSpace
LineTerminator
Comment
CommonToken
RegularExpressionLiteral
TemplateSubstitutionTail

InputElementTemplateTail ::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
TemplateSubstitutionTail
11.1 UnicodeFormatControlCharacters
TheUnicodeformatcontrolcharacters(i.e.,thecharactersincategoryCfintheUnicodeCharacterDatabasesuchasLEFT
TORIGHTMARKorRIGHTTOLEFTMARK)arecontrolcodesusedtocontroltheformattingofarangeoftextintheabsence
ofhigherlevelprotocolsforthis(suchasmarkuplanguages).

Itisusefultoallowformatcontrolcharactersinsourcetexttofacilitateeditinganddisplay.Allformatcontrolcharactersmay
beusedwithincomments,andwithinstringliterals,templateliterals,andregularexpressionliterals.

U+200C(ZEROWIDTHNONJOINER)andU+200D(ZEROWIDTHJOINER)areformatcontrolcharactersthatareusedto
makenecessarydistinctionswhenformingwordsorphrasesincertainlanguages.InECMAScriptsourcetextthesecode
pointsmayalsobeusedinanIdentiierNameaftertheirstcharacter.

U+FEFF(ZEROWIDTHNOBREAKSPACE)isaformatcontrolcharacterusedprimarilyatthestartofatexttomarkitas
Unicodeandtoallowdetectionofthetext'sencodingandbyteorder.<ZWNBSP>charactersintendedforthispurposecan
sometimesalsoappearafterthestartofatext,forexampleasaresultofconcatenatingiles.InECMAScriptsourcetext
<ZWNBSP>codepointsaretreatedaswhitespacecharacters(see11.2).

Thespecialtreatmentofcertainformatcontrolcharactersoutsideofcomments,stringliterals,andregularexpression
literalsissummarizedinTable31.

Table31:FormatControlCodePointUsage
CodePoint Name Abbreviation Usage

U+200C ZEROWIDTHNONJOINER <ZWNJ> IdentiierPart

U+200D ZEROWIDTHJOINER <ZWJ> IdentiierPart

U+FEFF ZEROWIDTHNOBREAKSPACE <ZWNBSP> WhiteSpace

11.2 WhiteSpace
Whitespacecodepointsareusedtoimprovesourcetextreadabilityandtoseparatetokens(indivisiblelexicalunits)from
eachother,butareotherwiseinsigniicant.Whitespacecodepointsmayoccurbetweenanytwotokensandatthestartor
endofinput.WhitespacecodepointsmayoccurwithinaStringLiteral,aRegularExpressionLiteral,aTemplate,ora
TemplateSubstitutionTailwheretheyareconsideredsigniicantcodepointsformingpartofaliteralvalue.Theymayalso
occurwithinaComment,butcannotappearwithinanyotherkindoftoken.

TheECMAScriptwhitespacecodepointsarelistedinTable32.

Table32:WhiteSpaceCodePoints
CodePoint Name Abbreviation

U+0009 CHARACTERTABULATION <TAB>

U+000B LINETABULATION <VT>

U+000C FORMFEED(FF) <FF>

U+0020 SPACE <SP>

U+00A0 NOBREAKSPACE <NBSP>

U+FEFF ZEROWIDTHNOBREAKSPACE <ZWNBSP>

OthercategoryZs AnyotherUnicodeSeparator,spacecodepoint <USP>


ECMAScriptimplementationsmustrecognizeasWhiteSpacecodepointslistedintheSeparator,space(Zs)category.

NOTE OtherthanforthecodepointslistedinTable32,ECMAScriptWhiteSpaceintentionallyexcludesallcodepoints
thathavetheUnicodeWhite_SpacepropertybutwhicharenotclassiiedincategoryZs.

Syntax

WhiteSpace ::
<TAB>
<VT>
<FF>
<SP>
<NBSP>
<ZWNBSP>
<USP>

11.3 LineTerminators
Likewhitespacecodepoints,lineterminatorcodepointsareusedtoimprovesourcetextreadabilityandtoseparatetokens
(indivisiblelexicalunits)fromeachother.However,unlikewhitespacecodepoints,lineterminatorshavesomeinluence
overthebehaviourofthesyntacticgrammar.Ingeneral,lineterminatorsmayoccurbetweenanytwotokens,buttherearea
fewplaceswheretheyareforbiddenbythesyntacticgrammar.Lineterminatorsalsoaffecttheprocessofautomatic
semicoloninsertion(11.9).AlineterminatorcannotoccurwithinanytokenexceptaStringLiteral,Template,or
TemplateSubstitutionTail.LineterminatorsmayonlyoccurwithinaStringLiteraltokenaspartofaLineContinuation.

AlineterminatorcanoccurwithinaMultiLineCommentbutcannotoccurwithinaSingleLineComment.

Lineterminatorsareincludedinthesetofwhitespacecodepointsthatarematchedbythe\sclassinregularexpressions.

TheECMAScriptlineterminatorcodepointsarelistedinTable33.

Table33:LineTerminatorCodePoints
CodePoint UnicodeName Abbreviation

U+000A LINEFEED(LF) <LF>

U+000D CARRIAGERETURN(CR) <CR>

U+2028 LINESEPARATOR <LS>

U+2029 PARAGRAPHSEPARATOR <PS>

OnlytheUnicodecodepointsinTable33aretreatedaslineterminators.OthernewlineorlinebreakingUnicodecodepoints
arenottreatedaslineterminatorsbutaretreatedaswhitespaceiftheymeettherequirementslistedinTable32.The
sequence<CR><LF>iscommonlyusedasalineterminator.ItshouldbeconsideredasingleSourceCharacterforthepurpose
ofreportinglinenumbers.

Syntax

LineTerminator ::
<LF>
<CR>
<LS>
<PS>

LineTerminatorSequence ::
<LF>
<CR>[lookahead<LF>]
<LS>
<PS>
<CR><LF>

11.4 Comments
Commentscanbeeithersingleormultiline.Multilinecommentscannotnest.

BecauseasinglelinecommentcancontainanyUnicodecodepointexceptaLineTerminatorcodepoint,andbecauseofthe
generalrulethatatokenisalwaysaslongaspossible,asinglelinecommentalwaysconsistsofallcodepointsfromthe//
markertotheendoftheline.However,theLineTerminatorattheendofthelineisnotconsideredtobepartofthesingleline
comment;itisrecognizedseparatelybythelexicalgrammarandbecomespartofthestreamofinputelementsforthe
syntacticgrammar.Thispointisveryimportant,becauseitimpliesthatthepresenceorabsenceofsinglelinecomments
doesnotaffecttheprocessofautomaticsemicoloninsertion(see11.9).

Commentsbehavelikewhitespaceandarediscardedexceptthat,ifaMultiLineCommentcontainsalineterminatorcode
point,thentheentirecommentisconsideredtobeaLineTerminatorforpurposesofparsingbythesyntacticgrammar.

Syntax

Comment ::
MultiLineComment
SingleLineComment

MultiLineComment ::
/* MultiLineCommentCharsopt */

MultiLineCommentChars ::
MultiLineNotAsteriskChar MultiLineCommentCharsopt
* PostAsteriskCommentCharsopt

PostAsteriskCommentChars ::
MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt
* PostAsteriskCommentCharsopt

MultiLineNotAsteriskChar ::
SourceCharacter butnot*

MultiLineNotForwardSlashOrAsteriskChar ::
SourceCharacter butnotoneof/ or*

SingleLineComment ::
// SingleLineCommentCharsopt

SingleLineCommentChars ::
SingleLineCommentChar SingleLineCommentCharsopt

SingleLineCommentChar ::
SourceCharacter butnotLineTerminator

11.5 Tokens
Syntax

CommonToken ::
IdentiierName
Punctuator
NumericLiteral
StringLiteral
Template

NOTE TheDivPunctuator,RegularExpressionLiteral,RightBracePunctuator,andTemplateSubstitutionTailproductions
deriveadditionaltokensthatarenotincludedintheCommonTokenproduction.

11.6 NamesandKeywords
IdentiierNameandReservedWordaretokensthatareinterpretedaccordingtotheDefaultIdentiierSyntaxgiveninUnicode
StandardAnnex#31,IdentiierandPatternSyntax,withsomesmallmodiications.ReservedWordisanenumeratedsubsetof
IdentiierName.ThesyntacticgrammardeinesIdentiierasanIdentiierNamethatisnotaReservedWord.TheUnicode
identiiergrammarisbasedoncharacterpropertiesspeciiedbytheUnicodeStandard.TheUnicodecodepointsinthe
speciiedcategoriesinversion8.0.0oftheUnicodestandardmustbetreatedasinthosecategoriesbyallconforming
ECMAScriptimplementations.ECMAScriptimplementationsmayrecognizeidentiiercodepointsdeinedinlatereditionsof
theUnicodeStandard.

NOTE1 Thisstandardspeciiesspeciiccodepointadditions:U+0024(DOLLARSIGN)andU+005F(LOWLINE)are
permittedanywhereinanIdentiierName,andthecodepointsU+200C(ZEROWIDTHNONJOINER)and
U+200D(ZEROWIDTHJOINER)arepermittedanywhereaftertheirstcodepointofanIdentiierName.

UnicodeescapesequencesarepermittedinanIdentiierName,wheretheycontributeasingleUnicodecodepointtothe
IdentiierName.ThecodepointisexpressedbytheHexDigitsoftheUnicodeEscapeSequence(see11.8.4).The\precedingthe
UnicodeEscapeSequenceandtheuand{}codeunits,iftheyappear,donotcontributecodepointstotheIdentiierName.A
UnicodeEscapeSequencecannotbeusedtoputacodepointintoanIdentiierNamethatwouldotherwisebeillegal.Inother
words,ifa\UnicodeEscapeSequencesequencewerereplacedbytheSourceCharacteritcontributes,theresultmuststillbea
validIdentiierNamethathastheexactsamesequenceofSourceCharacterelementsastheoriginalIdentiierName.All
interpretationsofIdentiierNamewithinthisspeciicationarebasedupontheiractualcodepointsregardlessofwhetheror
notanescapesequencewasusedtocontributeanyparticularcodepoint.

TwoIdentiierNamethatarecanonicallyequivalentaccordingtotheUnicodestandardarenotequalunless,after
replacementofeachUnicodeEscapeSequence,theyarerepresentedbytheexactsamesequenceofcodepoints.

Syntax

IdentiierName ::
IdentiierStart
IdentiierName IdentiierPart

IdentiierStart ::
UnicodeIDStart
$
_
\ UnicodeEscapeSequence

IdentiierPart ::
UnicodeIDContinue
$
_
\ UnicodeEscapeSequence
<ZWNJ>
<ZWJ>

UnicodeIDStart ::
anyUnicodecodepointwiththeUnicodepropertyID_Start
UnicodeIDContinue ::
anyUnicodecodepointwiththeUnicodepropertyID_Continue

ThedeinitionsofthenonterminalUnicodeEscapeSequenceisgivenin11.8.4.

NOTE2 ThesetsofcodepointswithUnicodepropertiesID_StartandID_Continueinclude,respectively,thecode
pointswithUnicodepropertiesOther_ID_StartandOther_ID_Continue.

11.6.1 IdentiierNames

11.6.1.1 StaticSemantics:EarlyErrors

IdentiierStart :: \ UnicodeEscapeSequence

ItisaSyntaxErrorifSV(UnicodeEscapeSequence)isnoneof"$",or"_",ortheUTF16Encodingofacodepointmatched
bytheUnicodeIDStartlexicalgrammarproduction.

IdentiierPart :: \ UnicodeEscapeSequence

ItisaSyntaxErrorifSV(UnicodeEscapeSequence)isnoneof"$",or"_",ortheUTF16Encodingofeither<ZWNJ>or
<ZWJ>,ortheUTF16EncodingofaUnicodecodepointthatwouldbematchedbytheUnicodeIDContinuelexical
grammarproduction.

11.6.1.2 StaticSemantics:StringValue

IdentiierName ::
IdentiierStart
IdentiierName IdentiierPart

1.ReturntheStringvalueconsistingofthesequenceofcodeunitscorrespondingtoIdentiierName.Indeterminingthe
sequenceanyoccurrencesof\UnicodeEscapeSequenceareirstreplacedwiththecodepointrepresentedbythe
UnicodeEscapeSequenceandthenthecodepointsoftheentireIdentiierNameareconvertedtocodeunitsby
UTF16Encodingeachcodepoint.

11.6.2 ReservedWords

AreservedwordisanIdentiierNamethatcannotbeusedasanIdentiier.

Syntax

ReservedWord ::
Keyword
FutureReservedWord
NullLiteral
BooleanLiteral

NOTE TheReservedWorddeinitionsarespeciiedasliteralsequencesofspeciicSourceCharacterelements.Acode
pointinaReservedWordcannotbeexpressedbya\UnicodeEscapeSequence.

11.6.2.1 Keywords

ThefollowingtokensareECMAScriptkeywordsandmaynotbeusedasIdentiiersinECMAScriptprograms.

Syntax

Keyword :: oneof
break do in typeof case else instanceof var catch export new void class extends return while
const finally super with continue for switch yield debugger function this default if
throw delete import try
NOTE InsomecontextsyieldisgiventhesemanticsofanIdentiier.See12.1.1.Instrictmodecode,letandstatic
aretreatedasreservedkeywordsthroughstaticsemanticrestrictions(see12.1.1,13.3.1.1,13.7.5.1,and
14.5.1)ratherthanthelexicalgrammar.

11.6.2.2 FutureReservedWords

Thefollowingtokensarereservedforusedaskeywordsinfuturelanguageextensions.

Syntax

FutureReservedWord ::
enum
await

awaitisonlytreatedasaFutureReservedWordwhenModuleisthegoalsymbolofthesyntacticgrammar.

NOTE Useofthefollowingtokenswithinstrictmodecodeisalsoreserved.Thatusageisrestrictedusingstatic
semanticrestrictions(see12.1.1)ratherthanthelexicalgrammar:

implements package protected


interface private public

11.7 Punctuators
Syntax

Punctuator :: oneof
{ ( ) [ ] . ... ; , < > <= >= == != === !== + * % ++ << >> >>> & | ^ ! ~ && || ? : = +=
= *= %= <<= >>= >>>= &= |= ^= => ** **=

DivPunctuator ::
/
/=

RightBracePunctuator ::
}

11.8 Literals
11.8.1 NullLiterals

Syntax

NullLiteral ::
null

11.8.2 BooleanLiterals

Syntax

BooleanLiteral ::
true
false

11.8.3 NumericLiterals

Syntax
NumericLiteral ::
DecimalLiteral
BinaryIntegerLiteral
OctalIntegerLiteral
HexIntegerLiteral

DecimalLiteral ::
DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt
. DecimalDigits ExponentPartopt
DecimalIntegerLiteral ExponentPartopt

DecimalIntegerLiteral ::
0
NonZeroDigit DecimalDigitsopt

DecimalDigits ::
DecimalDigit
DecimalDigits DecimalDigit

DecimalDigit :: oneof
0 1 2 3 4 5 6 7 8 9

NonZeroDigit :: oneof
1 2 3 4 5 6 7 8 9

ExponentPart ::
ExponentIndicator SignedInteger

ExponentIndicator :: oneof
e E

SignedInteger ::
DecimalDigits
+ DecimalDigits
DecimalDigits

BinaryIntegerLiteral ::
0b BinaryDigits
0B BinaryDigits

BinaryDigits ::
BinaryDigit
BinaryDigits BinaryDigit

BinaryDigit :: oneof
0 1

OctalIntegerLiteral ::
0o OctalDigits
0O OctalDigits

OctalDigits ::
OctalDigit
OctalDigits OctalDigit

OctalDigit :: oneof
0 1 2 3 4 5 6 7
HexIntegerLiteral ::
0x HexDigits
0X HexDigits

HexDigits ::
HexDigit
HexDigits HexDigit

HexDigit :: oneof
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

TheSourceCharacterimmediatelyfollowingaNumericLiteralmustnotbeanIdentiierStartorDecimalDigit.

NOTE Forexample:3inisanerrorandnotthetwoinputelements3andin.

Aconformingimplementation,whenprocessingstrictmodecode,mustnotextend,asdescribedinB.1.1,thesyntaxof
NumericLiteraltoincludeLegacyOctalIntegerLiteral,norextendthesyntaxofDecimalIntegerLiteraltoinclude
NonOctalDecimalIntegerLiteral.

11.8.3.1 StaticSemantics:MV

AnumericliteralstandsforavalueoftheNumbertype.Thisvalueisdeterminedintwosteps:irst,amathematicalvalue
(MV)isderivedfromtheliteral;second,thismathematicalvalueisroundedasdescribedbelow.

TheMVofNumericLiteral :: DecimalLiteral istheMVofDecimalLiteral.


TheMVofNumericLiteral :: BinaryIntegerLiteral istheMVofBinaryIntegerLiteral.
TheMVofNumericLiteral :: OctalIntegerLiteral istheMVofOctalIntegerLiteral.
TheMVofNumericLiteral :: HexIntegerLiteral istheMVofHexIntegerLiteral.
TheMVofDecimalLiteral :: DecimalIntegerLiteral . istheMVofDecimalIntegerLiteral.
TheMVofDecimalLiteral :: DecimalIntegerLiteral . DecimalDigits istheMVofDecimalIntegerLiteralplus(theMVof
DecimalDigits10n),wherenisthenumberofcodepointsinDecimalDigits.
TheMVofDecimalLiteral :: DecimalIntegerLiteral . ExponentPart istheMVofDecimalIntegerLiteral10e,wheree
istheMVofExponentPart.
TheMVofDecimalLiteral :: DecimalIntegerLiteral . DecimalDigits ExponentPart is(theMVofDecimalIntegerLiteral
plus(theMVofDecimalDigits10n))10e,wherenisthenumberofcodepointsinDecimalDigitsandeistheMVof
ExponentPart.
TheMVofDecimalLiteral :: . DecimalDigits istheMVofDecimalDigits10n,wherenisthenumberofcodepointsin
DecimalDigits.
TheMVofDecimalLiteral :: . DecimalDigits ExponentPart istheMVofDecimalDigits10en,wherenisthenumber
ofcodepointsinDecimalDigitsandeistheMVofExponentPart.
TheMVofDecimalLiteral :: DecimalIntegerLiteral istheMVofDecimalIntegerLiteral.
TheMVofDecimalLiteral :: DecimalIntegerLiteral ExponentPart istheMVofDecimalIntegerLiteral10e,whereeis
theMVofExponentPart.
TheMVofDecimalIntegerLiteral :: 0 is0.
TheMVofDecimalIntegerLiteral :: NonZeroDigit istheMVofNonZeroDigit.
TheMVofDecimalIntegerLiteral :: NonZeroDigit DecimalDigits is(theMVofNonZeroDigit10n)plustheMVof
DecimalDigits,wherenisthenumberofcodepointsinDecimalDigits.
TheMVofDecimalDigits :: DecimalDigit istheMVofDecimalDigit.
TheMVofDecimalDigits :: DecimalDigits DecimalDigit is(theMVofDecimalDigits10)plustheMVofDecimalDigit.
TheMVofExponentPart :: ExponentIndicator SignedInteger istheMVofSignedInteger.
TheMVofSignedInteger :: DecimalDigits istheMVofDecimalDigits.
TheMVofSignedInteger :: + DecimalDigits istheMVofDecimalDigits.
TheMVofSignedInteger :: DecimalDigits isthenegativeoftheMVofDecimalDigits.
TheMVofDecimalDigit :: 0 orofHexDigit :: 0 orofOctalDigit :: 0 orofBinaryDigit :: 0 is0.
TheMVofDecimalDigit :: 1 orofNonZeroDigit :: 1 orofHexDigit :: 1 orofOctalDigit :: 1 orofBinaryDigit :: 1
is1.
TheMVofDecimalDigit :: 2 orofNonZeroDigit :: 2 orofHexDigit :: 2 orofOctalDigit :: 2 is2.
TheMVofDecimalDigit :: 3 orofNonZeroDigit :: 3 orofHexDigit :: 3 orofOctalDigit :: 3 is3.
TheMVofDecimalDigit :: 4 orofNonZeroDigit :: 4 orofHexDigit :: 4 orofOctalDigit :: 4 is4.
TheMVofDecimalDigit :: 5 orofNonZeroDigit :: 5 orofHexDigit :: 5 orofOctalDigit :: 5 is5.
TheMVofDecimalDigit :: 6 orofNonZeroDigit :: 6 orofHexDigit :: 6 orofOctalDigit :: 6 is6.
TheMVofDecimalDigit :: 7 orofNonZeroDigit :: 7 orofHexDigit :: 7 orofOctalDigit :: 7 is7.
TheMVofDecimalDigit :: 8 orofNonZeroDigit :: 8 orofHexDigit :: 8 is8.
TheMVofDecimalDigit :: 9 orofNonZeroDigit :: 9 orofHexDigit :: 9 is9.
TheMVofHexDigit :: a orofHexDigit :: A is10.
TheMVofHexDigit :: b orofHexDigit :: B is11.
TheMVofHexDigit :: c orofHexDigit :: C is12.
TheMVofHexDigit :: d orofHexDigit :: D is13.
TheMVofHexDigit :: e orofHexDigit :: E is14.
TheMVofHexDigit :: f orofHexDigit :: F is15.
TheMVofBinaryIntegerLiteral :: 0b BinaryDigits istheMVofBinaryDigits.
TheMVofBinaryIntegerLiteral :: 0B BinaryDigits istheMVofBinaryDigits.
TheMVofBinaryDigits :: BinaryDigit istheMVofBinaryDigit.
TheMVofBinaryDigits :: BinaryDigits BinaryDigit is(theMVofBinaryDigits2)plustheMVofBinaryDigit.
TheMVofOctalIntegerLiteral :: 0o OctalDigits istheMVofOctalDigits.
TheMVofOctalIntegerLiteral :: 0O OctalDigits istheMVofOctalDigits.
TheMVofOctalDigits :: OctalDigit istheMVofOctalDigit.
TheMVofOctalDigits :: OctalDigits OctalDigit is(theMVofOctalDigits8)plustheMVofOctalDigit.
TheMVofHexIntegerLiteral :: 0x HexDigits istheMVofHexDigits.
TheMVofHexIntegerLiteral :: 0X HexDigits istheMVofHexDigits.
TheMVofHexDigits :: HexDigit istheMVofHexDigit.
TheMVofHexDigits :: HexDigits HexDigit is(theMVofHexDigits16)plustheMVofHexDigit.

OncetheexactMVforanumericliteralhasbeendetermined,itisthenroundedtoavalueoftheNumbertype.IftheMVis0,
thentheroundedvalueis+0;otherwise,theroundedvaluemustbetheNumbervaluefortheMV(asspeciiedin6.1.6),
unlesstheliteralisaDecimalLiteralandtheliteralhasmorethan20signiicantdigits,inwhichcasetheNumbervaluemay
beeithertheNumbervaluefortheMVofaliteralproducedbyreplacingeachsigniicantdigitafterthe20thwitha0digitor
theNumbervaluefortheMVofaliteralproducedbyreplacingeachsigniicantdigitafterthe20thwitha0digitandthen
incrementingtheliteralatthe20thsigniicantdigitposition.AdigitissigniicantifitisnotpartofanExponentPartand

itisnot0;or
thereisanonzerodigittoitsleftandthereisanonzerodigit,notintheExponentPart,toitsright.

11.8.4 StringLiterals

NOTE1 AstringliteraliszeroormoreUnicodecodepointsenclosedinsingleordoublequotes.Unicodecodepoints
mayalsoberepresentedbyanescapesequence.Allcodepointsmayappearliterallyinastringliteralexcept
fortheclosingquotecodepoints,U+005C(REVERSESOLIDUS),U+000D(CARRIAGERETURN),U+2028(LINE
SEPARATOR),U+2029(PARAGRAPHSEPARATOR),andU+000A(LINEFEED).Anycodepointsmayappearin
theformofanescapesequence.StringliteralsevaluatetoECMAScriptStringvalues.Whengeneratingthese
StringvaluesUnicodecodepointsareUTF16encodedasdeinedin10.1.1.CodepointsbelongingtotheBasic
MultilingualPlaneareencodedasasinglecodeunitelementofthestring.Allothercodepointsareencodedas
twocodeunitelementsofthestring.

Syntax

StringLiteral ::
" DoubleStringCharactersopt "
' SingleStringCharactersopt '

DoubleStringCharacters ::
DoubleStringCharacter DoubleStringCharactersopt

SingleStringCharacters ::
SingleStringCharacter SingleStringCharactersopt

DoubleStringCharacter ::
SourceCharacter butnotoneof" or\ orLineTerminator
\ EscapeSequence
LineContinuation

SingleStringCharacter ::
SourceCharacter butnotoneof' or\ orLineTerminator
\ EscapeSequence
LineContinuation

LineContinuation ::
\ LineTerminatorSequence

EscapeSequence ::
CharacterEscapeSequence
0 [lookaheadDecimalDigit]
HexEscapeSequence
UnicodeEscapeSequence

Aconformingimplementation,whenprocessingstrictmodecode,mustnotextendthesyntaxofEscapeSequencetoinclude
LegacyOctalEscapeSequenceasdescribedinB.1.2.

CharacterEscapeSequence ::
SingleEscapeCharacter
NonEscapeCharacter

SingleEscapeCharacter :: oneof
' " \ b f n r t v

NonEscapeCharacter ::
SourceCharacter butnotoneofEscapeCharacter orLineTerminator

EscapeCharacter ::
SingleEscapeCharacter
DecimalDigit
x
u

HexEscapeSequence ::
x HexDigit HexDigit

UnicodeEscapeSequence ::
u Hex4Digits
u{ HexDigits }

Hex4Digits ::
HexDigit HexDigit HexDigit HexDigit

ThedeinitionofthenonterminalHexDigitisgivenin11.8.3.SourceCharacterisdeinedin10.1.
NOTE2 Alineterminatorcodepointcannotappearinastringliteral,exceptaspartofaLineContinuationtoproduce
theemptycodepointssequence.TheproperwaytocausealineterminatorcodepointtobepartoftheString
valueofastringliteralistouseanescapesequencesuchas\nor\u000A.

11.8.4.1 StaticSemantics:EarlyErrors

UnicodeEscapeSequence :: u{ HexDigits }

ItisaSyntaxErroriftheMVofHexDigits>1114111.

11.8.4.2 StaticSemantics:StringValue

StringLiteral ::
" DoubleStringCharactersopt "
' SingleStringCharactersopt '

1.ReturntheStringvaluewhoseelementsaretheSVofthisStringLiteral.

11.8.4.3 StaticSemantics:SV

AstringliteralstandsforavalueoftheStringtype.TheStringvalue(SV)oftheliteralisdescribedintermsofcodeunit
valuescontributedbythevariouspartsofthestringliteral.Aspartofthisprocess,someUnicodecodepointswithinthe
stringliteralareinterpretedashavingamathematicalvalue(MV),asdescribedbeloworin11.8.3.

TheSVofStringLiteral :: " " istheemptycodeunitsequence.


TheSVofStringLiteral :: ' ' istheemptycodeunitsequence.
TheSVofStringLiteral :: " DoubleStringCharacters " istheSVofDoubleStringCharacters.
TheSVofStringLiteral :: ' SingleStringCharacters ' istheSVofSingleStringCharacters.
TheSVofDoubleStringCharacters :: DoubleStringCharacter isasequenceofoneortwocodeunitsthatistheSVof
DoubleStringCharacter.
TheSVofDoubleStringCharacters :: DoubleStringCharacter DoubleStringCharacters isasequenceofoneortwocode
unitsthatistheSVofDoubleStringCharacterfollowedbyallthecodeunitsintheSVofDoubleStringCharactersinorder.
TheSVofSingleStringCharacters :: SingleStringCharacter isasequenceofoneortwocodeunitsthatistheSVof
SingleStringCharacter.
TheSVofSingleStringCharacters :: SingleStringCharacter SingleStringCharacters isasequenceofoneortwocode
unitsthatistheSVofSingleStringCharacterfollowedbyallthecodeunitsintheSVofSingleStringCharactersinorder.
TheSVofDoubleStringCharacter :: SourceCharacter butnotoneof" or\ orLineTerminator istheUTF16Encoding
ofthecodepointvalueofSourceCharacter.
TheSVofDoubleStringCharacter :: \ EscapeSequence istheSVoftheEscapeSequence.
TheSVofDoubleStringCharacter :: LineContinuation istheemptycodeunitsequence.
TheSVofSingleStringCharacter :: SourceCharacter butnotoneof' or\ orLineTerminator istheUTF16Encoding
ofthecodepointvalueofSourceCharacter.
TheSVofSingleStringCharacter :: \ EscapeSequence istheSVoftheEscapeSequence.
TheSVofSingleStringCharacter :: LineContinuation istheemptycodeunitsequence.
TheSVofEscapeSequence :: CharacterEscapeSequence istheSVoftheCharacterEscapeSequence.
TheSVofEscapeSequence :: 0 isthecodeunitvalue0.
TheSVofEscapeSequence :: HexEscapeSequence istheSVoftheHexEscapeSequence.
TheSVofEscapeSequence :: UnicodeEscapeSequence istheSVoftheUnicodeEscapeSequence.
TheSVofCharacterEscapeSequence :: SingleEscapeCharacter isthecodeunitwhosevalueisdeterminedbythe
SingleEscapeCharacteraccordingtoTable34.
Table34:StringSingleCharacterEscapeSequences
EscapeSequence CodeUnitValue UnicodeCharacterName Symbol

\b 0x0008 BACKSPACE <BS>

\t 0x0009 CHARACTERTABULATION <HT>

\n 0x000A LINEFEED(LF) <LF>

\v 0x000B LINETABULATION <VT>

\f 0x000C FORMFEED(FF) <FF>

\r 0x000D CARRIAGERETURN(CR) <CR>

\" 0x0022 QUOTATIONMARK "

\' 0x0027 APOSTROPHE '

\\ 0x005C REVERSESOLIDUS \

TheSVofCharacterEscapeSequence :: NonEscapeCharacter istheSVoftheNonEscapeCharacter.


TheSVofNonEscapeCharacter :: SourceCharacter butnotoneofEscapeCharacter orLineTerminator isthe
UTF16EncodingofthecodepointvalueofSourceCharacter.
TheSVofHexEscapeSequence :: x HexDigit HexDigit isthecodeunitvaluethatis(16timestheMVoftheirst
HexDigit)plustheMVofthesecondHexDigit.
TheSVofUnicodeEscapeSequence :: u Hex4Digits istheSVofHex4Digits.
TheSVofHex4Digits :: HexDigit HexDigit HexDigit HexDigit isthecodeunitvaluethatis(4096timestheMVofthe
irstHexDigit)plus(256timestheMVofthesecondHexDigit)plus(16timestheMVofthethirdHexDigit)plustheMV
ofthefourthHexDigit.
TheSVofUnicodeEscapeSequence :: u{ HexDigits } istheUTF16EncodingoftheMVofHexDigits.

11.8.5 RegularExpressionLiterals

NOTE1 AregularexpressionliteralisaninputelementthatisconvertedtoaRegExpobject(see21.2)eachtimethe
literalisevaluated.Tworegularexpressionliteralsinaprogramevaluatetoregularexpressionobjectsthat
nevercompareas===toeachotherevenifthetwoliterals'contentsareidentical.ARegExpobjectmayalsobe
createdatruntimebynewRegExporcallingtheRegExpconstructorasafunction(see21.2.3).

Theproductionsbelowdescribethesyntaxforaregularexpressionliteralandareusedbytheinputelementscannertoind
theendoftheregularexpressionliteral.ThesourcetextcomprisingtheRegularExpressionBodyandthe
RegularExpressionFlagsaresubsequentlyparsedagainusingthemorestringentECMAScriptRegularExpressiongrammar
(21.2.1).

AnimplementationmayextendtheECMAScriptRegularExpressiongrammardeinedin21.2.1,butitmustnotextendthe
RegularExpressionBodyandRegularExpressionFlagsproductionsdeinedbelowortheproductionsusedbythese
productions.

Syntax

RegularExpressionLiteral ::
/ RegularExpressionBody / RegularExpressionFlags

RegularExpressionBody ::
RegularExpressionFirstChar RegularExpressionChars

RegularExpressionChars ::
[empty]
RegularExpressionChars RegularExpressionChar

RegularExpressionFirstChar ::
RegularExpressionNonTerminator butnotoneof* or\ or/ or[
RegularExpressionBackslashSequence
RegularExpressionClass

RegularExpressionChar ::
RegularExpressionNonTerminator butnotoneof\ or/ or[
RegularExpressionBackslashSequence
RegularExpressionClass

RegularExpressionBackslashSequence ::
\ RegularExpressionNonTerminator

RegularExpressionNonTerminator ::
SourceCharacter butnotLineTerminator

RegularExpressionClass ::
[ RegularExpressionClassChars ]

RegularExpressionClassChars ::
[empty]
RegularExpressionClassChars RegularExpressionClassChar

RegularExpressionClassChar ::
RegularExpressionNonTerminator butnotoneof] or\
RegularExpressionBackslashSequence

RegularExpressionFlags ::
[empty]
RegularExpressionFlags IdentiierPart

NOTE2 Regularexpressionliteralsmaynotbeempty;insteadofrepresentinganemptyregularexpressionliteral,the
codeunitsequence//startsasinglelinecomment.Tospecifyanemptyregularexpression,use:/(?:)/.

11.8.5.1 StaticSemantics:EarlyErrors

RegularExpressionFlags :: RegularExpressionFlags IdentiierPart

ItisaSyntaxErrorifIdentiierPartcontainsaUnicodeescapesequence.

11.8.5.2 StaticSemantics:BodyText

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags

1.ReturnthesourcetextthatwasrecognizedasRegularExpressionBody.

11.8.5.3 StaticSemantics:FlagText

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags

1.ReturnthesourcetextthatwasrecognizedasRegularExpressionFlags.

11.8.6 TemplateLiteralLexicalComponents

Syntax

Template ::
NoSubstitutionTemplate
TemplateHead
NoSubstitutionTemplate ::
` TemplateCharactersopt `

TemplateHead ::
` TemplateCharactersopt ${

TemplateSubstitutionTail ::
TemplateMiddle
TemplateTail

TemplateMiddle ::
} TemplateCharactersopt ${

TemplateTail ::
} TemplateCharactersopt `

TemplateCharacters ::
TemplateCharacter TemplateCharactersopt

TemplateCharacter ::
$ [lookahead{]
\ EscapeSequence
LineContinuation
LineTerminatorSequence
SourceCharacter butnotoneof` or\ or$ orLineTerminator

AconformingimplementationmustnotusetheextendeddeinitionofEscapeSequencedescribedinB.1.2whenparsinga
TemplateCharacter.

NOTE TemplateSubstitutionTailisusedbytheInputElementTemplateTailalternativelexicalgoal.

11.8.6.1 StaticSemantics:TVandTRV

AtemplateliteralcomponentisinterpretedasasequenceofUnicodecodepoints.TheTemplateValue(TV)ofaliteral
componentisdescribedintermsofcodeunitvalues(SV,11.8.4)contributedbythevariouspartsofthetemplateliteral
component.Aspartofthisprocess,someUnicodecodepointswithinthetemplatecomponentareinterpretedashavinga
mathematicalvalue(MV,11.8.3).IndeterminingaTV,escapesequencesarereplacedbytheUTF16codeunit(s)ofthe
Unicodecodepointrepresentedbytheescapesequence.TheTemplateRawValue(TRV)issimilartoaTemplateValuewith
thedifferencethatinTRVsescapesequencesareinterpretedliterally.

TheTVandTRVofNoSubstitutionTemplate :: ` ` istheemptycodeunitsequence.
TheTVandTRVofTemplateHead :: ` ${ istheemptycodeunitsequence.
TheTVandTRVofTemplateMiddle :: } ${ istheemptycodeunitsequence.
TheTVandTRVofTemplateTail :: } ` istheemptycodeunitsequence.
TheTVofNoSubstitutionTemplate :: ` TemplateCharacters ` istheTVofTemplateCharacters.
TheTVofTemplateHead :: ` TemplateCharacters ${ istheTVofTemplateCharacters.
TheTVofTemplateMiddle :: } TemplateCharacters ${ istheTVofTemplateCharacters.
TheTVofTemplateTail :: } TemplateCharacters ` istheTVofTemplateCharacters.
TheTVofTemplateCharacters :: TemplateCharacter istheTVofTemplateCharacter.
TheTVofTemplateCharacters :: TemplateCharacter TemplateCharacters isasequenceconsistingofthecodeunitsin
theTVofTemplateCharacterfollowedbyallthecodeunitsintheTVofTemplateCharactersinorder.
TheTVofTemplateCharacter :: SourceCharacter butnotoneof` or\ or$ orLineTerminator isthe
UTF16EncodingofthecodepointvalueofSourceCharacter.
TheTVofTemplateCharacter :: $ isthecodeunitvalue0x0024.
TheTVofTemplateCharacter :: \ EscapeSequence istheSVofEscapeSequence.
TheTVofTemplateCharacter :: LineContinuation istheTVofLineContinuation.
TheTVofTemplateCharacter :: LineTerminatorSequence istheTRVofLineTerminatorSequence.
TheTVofLineContinuation :: \ LineTerminatorSequence istheemptycodeunitsequence.
TheTRVofNoSubstitutionTemplate :: ` TemplateCharacters ` istheTRVofTemplateCharacters.
TheTRVofTemplateHead :: ` TemplateCharacters ${ istheTRVofTemplateCharacters.
TheTRVofTemplateMiddle :: } TemplateCharacters ${ istheTRVofTemplateCharacters.
TheTRVofTemplateTail :: } TemplateCharacters ` istheTRVofTemplateCharacters.
TheTRVofTemplateCharacters :: TemplateCharacter istheTRVofTemplateCharacter.
TheTRVofTemplateCharacters :: TemplateCharacter TemplateCharacters isasequenceconsistingofthecodeunitsin
theTRVofTemplateCharacterfollowedbyallthecodeunitsintheTRVofTemplateCharacters,inorder.
TheTRVofTemplateCharacter :: SourceCharacter butnotoneof` or\ or$ orLineTerminator isthe
UTF16EncodingofthecodepointvalueofSourceCharacter.
TheTRVofTemplateCharacter :: $ isthecodeunitvalue0x0024.
TheTRVofTemplateCharacter :: \ EscapeSequence isthesequenceconsistingofthecodeunitvalue0x005Cfollowed
bythecodeunitsofTRVofEscapeSequence.
TheTRVofTemplateCharacter :: LineContinuation istheTRVofLineContinuation.
TheTRVofTemplateCharacter :: LineTerminatorSequence istheTRVofLineTerminatorSequence.
TheTRVofEscapeSequence :: CharacterEscapeSequence istheTRVoftheCharacterEscapeSequence.
TheTRVofEscapeSequence :: 0 isthecodeunitvalue0x0030(DIGITZERO).
TheTRVofEscapeSequence :: HexEscapeSequence istheTRVoftheHexEscapeSequence.
TheTRVofEscapeSequence :: UnicodeEscapeSequence istheTRVoftheUnicodeEscapeSequence.
TheTRVofCharacterEscapeSequence :: SingleEscapeCharacter istheTRVoftheSingleEscapeCharacter.
TheTRVofCharacterEscapeSequence :: NonEscapeCharacter istheSVoftheNonEscapeCharacter.
TheTRVofSingleEscapeCharacter :: oneof ' " \ b f n r t v istheSVoftheSourceCharacterthatisthat
singlecodepoint.
TheTRVofHexEscapeSequence :: x HexDigit HexDigit isthesequenceconsistingofcodeunitvalue0x0078followed
byTRVoftheirstHexDigitfollowedbytheTRVofthesecondHexDigit.
TheTRVofUnicodeEscapeSequence :: u Hex4Digits isthesequenceconsistingofcodeunitvalue0x0075followedby
TRVofHex4Digits.
TheTRVofUnicodeEscapeSequence :: u{ HexDigits } isthesequenceconsistingofcodeunitvalue0x0075followed
bycodeunitvalue0x007BfollowedbyTRVofHexDigitsfollowedbycodeunitvalue0x007D.
TheTRVofHex4Digits :: HexDigit HexDigit HexDigit HexDigit isthesequenceconsistingoftheTRVoftheirst
HexDigitfollowedbytheTRVofthesecondHexDigitfollowedbytheTRVofthethirdHexDigitfollowedbytheTRVof
thefourthHexDigit.
TheTRVofHexDigits :: HexDigit istheTRVofHexDigit.
TheTRVofHexDigits :: HexDigits HexDigit isthesequenceconsistingofTRVofHexDigitsfollowedbyTRVofHexDigit.
TheTRVofaHexDigitistheSVoftheSourceCharacterthatisthatHexDigit.
TheTRVofLineContinuation :: \ LineTerminatorSequence isthesequenceconsistingofthecodeunitvalue0x005C
followedbythecodeunitsofTRVofLineTerminatorSequence.
TheTRVofLineTerminatorSequence :: <LF>isthecodeunitvalue0x000A.
TheTRVofLineTerminatorSequence :: <CR>isthecodeunitvalue0x000A.
TheTRVofLineTerminatorSequence :: <LS>isthecodeunitvalue0x2028.
TheTRVofLineTerminatorSequence :: <PS>isthecodeunitvalue0x2029.
TheTRVofLineTerminatorSequence :: <CR><LF>isthesequenceconsistingofthecodeunitvalue0x000A.

NOTE TVexcludesthecodeunitsofLineContinuationwhileTRVincludesthem.<CR><LF>and<CR>
LineTerminatorSequencesarenormalizedto<LF>forbothTVandTRV.AnexplicitEscapeSequenceisneededto
includea<CR>or<CR><LF>sequence.

11.9 AutomaticSemicolonInsertion
MostECMAScriptstatementsanddeclarationsmustbeterminatedwithasemicolon.Suchsemicolonsmayalwaysappear
explicitlyinthesourcetext.Forconvenience,however,suchsemicolonsmaybeomittedfromthesourcetextincertain
situations.Thesesituationsaredescribedbysayingthatsemicolonsareautomaticallyinsertedintothesourcecodetoken
streaminthosesituations.
11.9.1 RulesofAutomaticSemicolonInsertion

Inthefollowingrules,tokenmeanstheactualrecognizedlexicaltokendeterminedusingthecurrentlexicalgoalsymbolas
describedinclause11.

Therearethreebasicrulesofsemicoloninsertion:

1.When,asaScriptorModuleisparsedfromlefttoright,atoken(calledtheoffendingtoken)isencounteredthatisnot
allowedbyanyproductionofthegrammar,thenasemicolonisautomaticallyinsertedbeforetheoffendingtokenifone
ormoreofthefollowingconditionsistrue:

TheoffendingtokenisseparatedfromtheprevioustokenbyatleastoneLineTerminator.
Theoffendingtokenis}.
Theprevioustokenis)andtheinsertedsemicolonwouldthenbeparsedastheterminatingsemicolonofado
whilestatement(13.7.2).
2.When,astheScriptorModuleisparsedfromlefttoright,theendoftheinputstreamoftokensisencounteredandthe
parserisunabletoparsetheinputtokenstreamasasinglecompleteECMAScriptScriptorModule,thenasemicolonis
automaticallyinsertedattheendoftheinputstream.
3.When,astheScriptorModuleisparsedfromlefttoright,atokenisencounteredthatisallowedbysomeproductionof
thegrammar,buttheproductionisarestrictedproductionandthetokenwouldbetheirsttokenforaterminalor
nonterminalimmediatelyfollowingtheannotation[noLineTerminatorhere]withintherestrictedproduction(and
thereforesuchatokeniscalledarestrictedtoken),andtherestrictedtokenisseparatedfromtheprevioustokenbyat
leastoneLineTerminator,thenasemicolonisautomaticallyinsertedbeforetherestrictedtoken.

However,thereisanadditionaloverridingconditionontheprecedingrules:asemicolonisneverinsertedautomaticallyif
thesemicolonwouldthenbeparsedasanemptystatementorifthatsemicolonwouldbecomeoneofthetwosemicolonsin
theheaderofaforstatement(see13.7.4).

NOTE Thefollowingaretheonlyrestrictedproductionsinthegrammar:

UpdateExpression[Yield] :
LeftHandSideExpression[?Yield] [noLineTerminatorhere] ++
LeftHandSideExpression[?Yield] [noLineTerminatorhere]

ContinueStatement[Yield] :
continue ;
continue [noLineTerminatorhere] LabelIdentiier[?Yield] ;

BreakStatement[Yield] :
break ;
break [noLineTerminatorhere] LabelIdentiier[?Yield] ;

ReturnStatement[Yield] :
return ;
return [noLineTerminatorhere] Expression[In,?Yield] ;

ThrowStatement[Yield] :
throw [noLineTerminatorhere] Expression[In,?Yield] ;

ArrowFunction[In,Yield] :
ArrowParameters[?Yield] [noLineTerminatorhere] => ConciseBody[?In]

YieldExpression[In] :
yield [noLineTerminatorhere] * AssignmentExpression[?In,Yield]
yield [noLineTerminatorhere] AssignmentExpression[?In,Yield]
Thepracticaleffectoftheserestrictedproductionsisasfollows:

Whena++ortokenisencounteredwheretheparserwouldtreatitasapostixoperator,andatleast
oneLineTerminatoroccurredbetweentheprecedingtokenandthe++ortoken,thenasemicolonis
automaticallyinsertedbeforethe++ortoken.
Whenacontinue,break,return,throw,oryieldtokenisencounteredandaLineTerminatoris
encounteredbeforethenexttoken,asemicolonisautomaticallyinsertedafterthecontinue,break,
return,throw,oryieldtoken.

TheresultingpracticaladvicetoECMAScriptprogrammersis:

Apostix++oroperatorshouldappearonthesamelineasitsoperand.
AnExpressioninareturnorthrowstatementoranAssignmentExpressioninayieldexpressionshould
startonthesamelineasthereturn,throw,oryieldtoken.
ALabelIdentiierinabreakorcontinuestatementshouldbeonthesamelineasthebreakor
continuetoken.

11.9.2 ExamplesofAutomaticSemicolonInsertion

Thesource

{12}3

isnotavalidsentenceintheECMAScriptgrammar,evenwiththeautomaticsemicoloninsertionrules.Incontrast,thesource

{1
2}3

isalsonotavalidECMAScriptsentence,butistransformedbyautomaticsemicoloninsertionintothefollowing:

{1
;2;}3;

whichisavalidECMAScriptsentence.

Thesource

for(a;b
)

isnotavalidECMAScriptsentenceandisnotalteredbyautomaticsemicoloninsertionbecausethesemicolonisneededfor
theheaderofaforstatement.Automaticsemicoloninsertionneverinsertsoneofthetwosemicolonsintheheaderofafor
statement.

Thesource

return
a+b

istransformedbyautomaticsemicoloninsertionintothefollowing:

return;
a+b;

NOTE1 Theexpressiona+bisnottreatedasavaluetobereturnedbythereturnstatement,becausea
LineTerminatorseparatesitfromthetokenreturn.

Thesource
a=b
++c

istransformedbyautomaticsemicoloninsertionintothefollowing:

a=b;
++c;

NOTE2 Thetoken++isnottreatedasapostixoperatorapplyingtothevariableb,becauseaLineTerminatoroccurs
betweenband++.

Thesource

if(a>b)
elsec=d

isnotavalidECMAScriptsentenceandisnotalteredbyautomaticsemicoloninsertionbeforetheelsetoken,eventhough
noproductionofthegrammarappliesatthatpoint,becauseanautomaticallyinsertedsemicolonwouldthenbeparsedasan
emptystatement.

Thesource

a=b+c
(d+e).print()

isnottransformedbyautomaticsemicoloninsertion,becausetheparenthesizedexpressionthatbeginsthesecondlinecan
beinterpretedasanargumentlistforafunctioncall:

a=b+c(d+e).print()

Inthecircumstancethatanassignmentstatementmustbeginwithaleftparenthesis,itisagoodideafortheprogrammerto
provideanexplicitsemicolonattheendoftheprecedingstatementratherthantorelyonautomaticsemicoloninsertion.

12 ECMAScriptLanguage:Expressions
12.1 Identiiers
Syntax

IdentiierReference[Yield] :
Identiier
[~Yield] yield

BindingIdentiier[Yield] :
Identiier
[~Yield] yield

LabelIdentiier[Yield] :
Identiier
[~Yield] yield

Identiier :
IdentiierName butnotReservedWord

12.1.1 StaticSemantics:EarlyErrors
BindingIdentiier : Identiier
ItisaSyntaxErrorifthecodematchedbythisproductioniscontainedinstrictmodecodeandtheStringValueof
Identiieris"arguments"or"eval".

IdentiierReference : yield
BindingIdentiier : yield
LabelIdentiier : yield

ItisaSyntaxErrorifthecodematchedbythisproductioniscontainedinstrictmodecode.

IdentiierReference : Identiier
BindingIdentiier : Identiier
LabelIdentiier : Identiier

ItisaSyntaxErrorifthisproductionhasa[Yield]parameterandStringValueofIdentiieris"yield".

Identiier : IdentiierName butnotReservedWord

ItisaSyntaxErrorifthisphraseiscontainedinstrictmodecodeandtheStringValueofIdentiierNameis:
"implements","interface","let","package","private","protected","public","static",or"yield".
ItisaSyntaxErrorifStringValueofIdentiierNameisthesameStringvalueastheStringValueofanyReservedWord
exceptforyield.

NOTE StringValueofIdentiierNamenormalizesanyUnicodeescapesequencesinIdentiierNamehencesuchescapes
cannotbeusedtowriteanIdentiierwhosecodepointsequenceisthesameasaReservedWord.

12.1.2 StaticSemantics:BoundNames
BindingIdentiier : Identiier

1.ReturnanewListcontainingtheStringValueofIdentiier.

BindingIdentiier : yield

1.ReturnanewListcontaining"yield".

12.1.3 StaticSemantics:IsValidSimpleAssignmentTarget
IdentiierReference : Identiier

1.IfthisIdentiierReferenceiscontainedinstrictmodecodeandStringValueofIdentiieris"eval"or"arguments",
returnfalse.
2.Returntrue.

IdentiierReference : yield

1.Returntrue.

12.1.4 StaticSemantics:StringValue
IdentiierReference : yield
BindingIdentiier : yield
LabelIdentiier : yield

1.Return"yield".

Identiier : IdentiierName butnotReservedWord

1.ReturntheStringValueofIdentiierName.

12.1.5 RuntimeSemantics:BindingInitialization
Withargumentsvalueandenvironment.

NOTE undeinedispassedforenvironmenttoindicatethataPutValueoperationshouldbeusedtoassignthe
initializationvalue.Thisisthecaseforvarstatementsandformalparameterlistsofsomenonstrictfunctions
(See9.2.12).Inthosecasesalexicalbindingishoistedandpreinitializedpriortoevaluationofitsinitializer.

BindingIdentiier : Identiier

1.LetnamebeStringValueofIdentiier.
2.Return?InitializeBoundName(name,value,environment).

BindingIdentiier : yield

1.Return?InitializeBoundName("yield",value,environment).

12.1.5.1 RuntimeSemantics:InitializeBoundName(name,value,environment)

1.Assert:Type(name)isString.
2.Ifenvironmentisnotundeined,then
a.LetenvbetheEnvironmentRecordcomponentofenvironment.
b.Performenv.InitializeBinding(name,value).
c.ReturnNormalCompletion(undeined).
3.Else,
a.LetlhsbeResolveBinding(name).
b.Return?PutValue(lhs,value).

12.1.6 RuntimeSemantics:Evaluation
IdentiierReference : Identiier

1.Return?ResolveBinding(StringValueofIdentiier).

IdentiierReference : yield

1.Return?ResolveBinding("yield").

NOTE1 TheresultofevaluatinganIdentiierReferenceisalwaysavalueoftypeReference.

NOTE2 Innonstrictcode,thekeywordyieldmaybeusedasanidentiier.EvaluatingtheIdentiierReference
productionresolvesthebindingofyieldasifitwasanIdentiier.EarlyErrorrestrictionensuresthatsuchan
evaluationonlycanoccurfornonstrictcode.See13.3.1forthehandlingofyieldinbindingcreationcontexts.

12.2 PrimaryExpression
Syntax

PrimaryExpression[Yield] :
this
IdentiierReference[?Yield]
Literal
ArrayLiteral[?Yield]
ObjectLiteral[?Yield]
FunctionExpression
ClassExpression[?Yield]
GeneratorExpression
RegularExpressionLiteral
TemplateLiteral[?Yield]
CoverParenthesizedExpressionAndArrowParameterList[?Yield]

CoverParenthesizedExpressionAndArrowParameterList[Yield] :
( Expression[In,?Yield] )
( )
( ... BindingIdentiier[?Yield] )
( ... BindingPattern[?Yield] )
( Expression[In,?Yield] , ... BindingIdentiier[?Yield] )
( Expression[In,?Yield] , ... BindingPattern[?Yield] )

SupplementalSyntax

Whenprocessingtheproduction
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
theinterpretationofCoverParenthesizedExpressionAndArrowParameterListisreinedusingthefollowinggrammar:

ParenthesizedExpression[Yield] :
( Expression[In,?Yield] )

12.2.1 Semantics

12.2.1.1 StaticSemantics:CoveredParenthesizedExpression

CoverParenthesizedExpressionAndArrowParameterList : ( Expression )

1.Returntheresultofparsingthelexicaltokenstreammatchedby
CoverParenthesizedExpressionAndArrowParameterList[Yield] usingeitherParenthesizedExpressionor
ParenthesizedExpression[Yield] asthegoalsymboldependinguponwhetherthe[Yield]grammarparameterwas
presentwhenCoverParenthesizedExpressionAndArrowParameterListwasmatched.

12.2.1.2 StaticSemantics:HasName

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

1.LetexprbeCoveredParenthesizedExpressionofCoverParenthesizedExpressionAndArrowParameterList.
2.IfIsFunctionDeinitionofexprisfalse,returnfalse.
3.ReturnHasNameofexpr.

12.2.1.3 StaticSemantics:IsFunctionDeinition

PrimaryExpression :
this
IdentiierReference
Literal
ArrayLiteral
ObjectLiteral
RegularExpressionLiteral
TemplateLiteral

1.Returnfalse.

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

1.LetexprbeCoveredParenthesizedExpressionofCoverParenthesizedExpressionAndArrowParameterList.
2.ReturnIsFunctionDeinitionofexpr.

12.2.1.4 StaticSemantics:IsIdentiierRef
PrimaryExpression : IdentiierReference

1.Returntrue.

PrimaryExpression :
this
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
RegularExpressionLiteral
TemplateLiteral
CoverParenthesizedExpressionAndArrowParameterList

1.Returnfalse.

12.2.1.5 StaticSemantics:IsValidSimpleAssignmentTarget

PrimaryExpression :
this
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
RegularExpressionLiteral
TemplateLiteral

1.Returnfalse.

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

1.LetexprbeCoveredParenthesizedExpressionofCoverParenthesizedExpressionAndArrowParameterList.
2.ReturnIsValidSimpleAssignmentTargetofexpr.

12.2.2 ThethisKeyword

12.2.2.1 RuntimeSemantics:Evaluation

PrimaryExpression : this

1.Return?ResolveThisBinding().

12.2.3 IdentiierReference

See12.1forIdentiierReference.

12.2.4 Literals

Syntax

Literal :
NullLiteral
BooleanLiteral
NumericLiteral
StringLiteral
12.2.4.1 RuntimeSemantics:Evaluation

Literal : NullLiteral

1.Returnnull.

Literal : BooleanLiteral

1.ReturnfalseifBooleanLiteralisthetokenfalse.
2.ReturntrueifBooleanLiteralisthetokentrue.

Literal : NumericLiteral

1.ReturnthenumberwhosevalueisMVofNumericLiteralasdeinedin11.8.3.

Literal : StringLiteral

1.ReturntheStringValueofStringLiteralasdeinedin11.8.4.2.

12.2.5 ArrayInitializer

NOTE AnArrayLiteralisanexpressiondescribingtheinitializationofanArrayobject,usingalist,ofzeroormore
expressionseachofwhichrepresentsanarrayelement,enclosedinsquarebrackets.Theelementsneednotbe
literals;theyareevaluatedeachtimethearrayinitializerisevaluated.

Arrayelementsmaybeelidedatthebeginning,middleorendoftheelementlist.Wheneveracommaintheelementlistis
notprecededbyanAssignmentExpression(i.e.,acommaatthebeginningorafteranothercomma),themissingarrayelement
contributestothelengthoftheArrayandincreasestheindexofsubsequentelements.Elidedarrayelementsarenotdeined.
Ifanelementiselidedattheendofanarray,thatelementdoesnotcontributetothelengthoftheArray.

Syntax

ArrayLiteral[Yield] :
[ Elisionopt ]
[ ElementList[?Yield] ]
[ ElementList[?Yield] , Elisionopt ]

ElementList[Yield] :
Elisionopt AssignmentExpression[In,?Yield]
Elisionopt SpreadElement[?Yield]
ElementList[?Yield] , Elisionopt AssignmentExpression[In,?Yield]
ElementList[?Yield] , Elisionopt SpreadElement[?Yield]

Elision :
,
Elision ,

SpreadElement[Yield] :
... AssignmentExpression[In,?Yield]

12.2.5.1 StaticSemantics:ElisionWidth

Elision : ,

1.Returnthenumericvalue1.

Elision : Elision ,

1.LetprecedingbetheElisionWidthofElision.
2.Returnpreceding+1.

12.2.5.2 RuntimeSemantics:ArrayAccumulation

WithparametersarrayandnextIndex.

ElementList : Elision AssignmentExpression

1.LetpaddingbetheElisionWidthofElision;ifElisionisnotpresent,usethenumericvaluezero.
2.LetinitResultbetheresultofevaluatingAssignmentExpression.
3.LetinitValuebe?GetValue(initResult).
4.LetcreatedbeCreateDataProperty(array,ToString(ToUint32(nextIndex+padding)),initValue).
5.Assert:createdistrue.
6.ReturnnextIndex+padding+1.

ElementList : Elision SpreadElement

1.LetpaddingbetheElisionWidthofElision;ifElisionisnotpresent,usethenumericvaluezero.
2.ReturntheresultofperformingArrayAccumulationforSpreadElementwithargumentsarrayandnextIndex+padding.

ElementList : ElementList , Elision AssignmentExpression

1.LetpostIndexbetheresultofperformingArrayAccumulationforElementListwithargumentsarrayandnextIndex.
2.ReturnIfAbrupt(postIndex).
3.LetpaddingbetheElisionWidthofElision;ifElisionisnotpresent,usethenumericvaluezero.
4.LetinitResultbetheresultofevaluatingAssignmentExpression.
5.LetinitValuebe?GetValue(initResult).
6.LetcreatedbeCreateDataProperty(array,ToString(ToUint32(postIndex+padding)),initValue).
7.Assert:createdistrue.
8.ReturnpostIndex+padding+1.

ElementList : ElementList , Elision SpreadElement

1.LetpostIndexbetheresultofperformingArrayAccumulationforElementListwithargumentsarrayandnextIndex.
2.ReturnIfAbrupt(postIndex).
3.LetpaddingbetheElisionWidthofElision;ifElisionisnotpresent,usethenumericvaluezero.
4.ReturntheresultofperformingArrayAccumulationforSpreadElementwithargumentsarrayandpostIndex+padding.

SpreadElement : ... AssignmentExpression

1.LetspreadRefbetheresultofevaluatingAssignmentExpression.
2.LetspreadObjbe?GetValue(spreadRef).
3.Letiteratorbe?GetIterator(spreadObj).
4.Repeat
a.Letnextbe?IteratorStep(iterator).
b.Ifnextisfalse,returnnextIndex.
c.LetnextValuebe?IteratorValue(next).
d.LetstatusbeCreateDataProperty(array,ToString(ToUint32(nextIndex)),nextValue).
e.Assert:statusistrue.
f.LetnextIndexbenextIndex+1.

NOTE CreateDataPropertyisusedtoensurethatownpropertiesaredeinedforthearrayevenifthestandardbuilt
inArrayprototypeobjecthasbeenmodiiedinamannerthatwouldprecludethecreationofnewown
propertiesusing[[Set]].

12.2.5.3 RuntimeSemantics:Evaluation

ArrayLiteral : [ Elision ]
1.LetarraybeArrayCreate(0).
2.LetpadbetheElisionWidthofElision;ifElisionisnotpresent,usethenumericvaluezero.
3.PerformSet(array,"length",ToUint32(pad),false).
4.NOTE:TheaboveSetcannotfailbecauseofthenatureoftheobjectreturnedbyArrayCreate.
5.Returnarray.

ArrayLiteral : [ ElementList ]

1.LetarraybeArrayCreate(0).
2.LetlenbetheresultofperformingArrayAccumulationforElementListwithargumentsarrayand0.
3.ReturnIfAbrupt(len).
4.PerformSet(array,"length",ToUint32(len),false).
5.NOTE:TheaboveSetcannotfailbecauseofthenatureoftheobjectreturnedbyArrayCreate.
6.Returnarray.

ArrayLiteral : [ ElementList , Elision ]

1.LetarraybeArrayCreate(0).
2.LetlenbetheresultofperformingArrayAccumulationforElementListwithargumentsarrayand0.
3.ReturnIfAbrupt(len).
4.LetpaddingbetheElisionWidthofElision;ifElisionisnotpresent,usethenumericvaluezero.
5.PerformSet(array,"length",ToUint32(padding+len),false).
6.NOTE:TheaboveSetcannotfailbecauseofthenatureoftheobjectreturnedbyArrayCreate.
7.Returnarray.

12.2.6 ObjectInitializer

NOTE1 AnobjectinitializerisanexpressiondescribingtheinitializationofanObject,writteninaformresemblinga
literal.Itisalistofzeroormorepairsofpropertykeysandassociatedvalues,enclosedincurlybrackets.The
valuesneednotbeliterals;theyareevaluatedeachtimetheobjectinitializerisevaluated.

Syntax

ObjectLiteral[Yield] :
{ }
{ PropertyDeinitionList[?Yield] }
{ PropertyDeinitionList[?Yield] , }

PropertyDeinitionList[Yield] :
PropertyDeinition[?Yield]
PropertyDeinitionList[?Yield] , PropertyDeinition[?Yield]

PropertyDeinition[Yield] :
IdentiierReference[?Yield]
CoverInitializedName[?Yield]
PropertyName[?Yield] : AssignmentExpression[In,?Yield]
MethodDeinition[?Yield]

PropertyName[Yield] :
LiteralPropertyName
ComputedPropertyName[?Yield]

LiteralPropertyName :
IdentiierName
StringLiteral
NumericLiteral
ComputedPropertyName[Yield] :
[ AssignmentExpression[In,?Yield] ]

CoverInitializedName[Yield] :
IdentiierReference[?Yield] Initializer[In,?Yield]

Initializer[In,Yield] :
= AssignmentExpression[?In,?Yield]

NOTE2 MethodDeinitionisdeinedin14.3.

NOTE3 Incertaincontexts,ObjectLiteralisusedasacovergrammarforamorerestrictedsecondarygrammar.The
CoverInitializedNameproductionisnecessarytofullycoverthesesecondarygrammars.However,useofthis
productionresultsinanearlySyntaxErrorinnormalcontextswhereanactualObjectLiteralisexpected.

12.2.6.1 StaticSemantics:EarlyErrors

PropertyDeinition : MethodDeinition

ItisaSyntaxErrorifHasDirectSuperofMethodDeinitionistrue.

InadditiontodescribinganactualobjectinitializertheObjectLiteralproductionsarealsousedasacovergrammarfor
ObjectAssignmentPattern.andmayberecognizedaspartofaCoverParenthesizedExpressionAndArrowParameterList.When
ObjectLiteralappearsinacontextwhereObjectAssignmentPatternisrequiredthefollowingEarlyErrorrulesarenotapplied.
Inaddition,theyarenotappliedwheninitiallyparsingaCoverParenthesizedExpressionAndArrowParameterList.

PropertyDeinition : CoverInitializedName

AlwaysthrowaSyntaxErrorifcodematchesthisproduction.

NOTE ThisproductionexistssothatObjectLiteralcanserveasacovergrammarforObjectAssignmentPattern.It
cannotoccurinanactualobjectinitializer.

12.2.6.2 StaticSemantics:ComputedPropertyContains

Withparametersymbol.

PropertyName : LiteralPropertyName

1.Returnfalse.

PropertyName : ComputedPropertyName

1.ReturntheresultofComputedPropertyNameContainssymbol.

12.2.6.3 StaticSemantics:Contains

Withparametersymbol.

PropertyDeinition : MethodDeinition

1.IfsymbolisMethodDeinition,returntrue.
2.ReturntheresultofComputedPropertyContainsforMethodDeinitionwithargumentsymbol.

NOTE Staticsemanticrulesthatdependuponsubstructuregenerallydonotlookintofunctiondeinitions.

LiteralPropertyName : IdentiierName

1.IfsymbolisaReservedWord,returnfalse.
2.IfsymbolisanIdentiierandStringValueofsymbolisthesamevalueastheStringValueofIdentiierName,returntrue.
3.Returnfalse.
12.2.6.4 StaticSemantics:HasComputedPropertyKey

PropertyDeinitionList : PropertyDeinitionList , PropertyDeinition

1.IfHasComputedPropertyKeyofPropertyDeinitionLististrue,returntrue.
2.ReturnHasComputedPropertyKeyofPropertyDeinition.

PropertyDeinition : IdentiierReference

1.Returnfalse.

PropertyDeinition : PropertyName : AssignmentExpression

1.ReturnIsComputedPropertyKeyofPropertyName.

12.2.6.5 StaticSemantics:IsComputedPropertyKey

PropertyName : LiteralPropertyName

1.Returnfalse.

PropertyName : ComputedPropertyName

1.Returntrue.

12.2.6.6 StaticSemantics:PropName

PropertyDeinition : IdentiierReference

1.ReturnStringValueofIdentiierReference.

PropertyDeinition : PropertyName : AssignmentExpression

1.ReturnPropNameofPropertyName.

LiteralPropertyName : IdentiierName

1.ReturnStringValueofIdentiierName.

LiteralPropertyName : StringLiteral

1.ReturnaStringvaluewhosecodeunitsaretheSVoftheStringLiteral.

LiteralPropertyName : NumericLiteral

1.LetnbrbetheresultofformingthevalueoftheNumericLiteral.
2.Return!ToString(nbr).

ComputedPropertyName : [ AssignmentExpression ]

1.Returnempty.

12.2.6.7 StaticSemantics:PropertyNameList

PropertyDeinitionList : PropertyDeinition

1.IfPropNameofPropertyDeinitionisempty,returnanewemptyList.
2.ReturnanewListcontainingPropNameofPropertyDeinition.

PropertyDeinitionList : PropertyDeinitionList , PropertyDeinition

1.LetlistbePropertyNameListofPropertyDeinitionList.
2.IfPropNameofPropertyDeinitionisempty,returnlist.
3.AppendPropNameofPropertyDeinitiontotheendoflist.
4.Returnlist.

12.2.6.8 RuntimeSemantics:Evaluation

ObjectLiteral : { }

1.ReturnObjectCreate(%ObjectPrototype%).

ObjectLiteral :
{ PropertyDeinitionList }
{ PropertyDeinitionList , }

1.LetobjbeObjectCreate(%ObjectPrototype%).
2.LetstatusbetheresultofperformingPropertyDeinitionEvaluationofPropertyDeinitionListwithargumentsobjand
true.
3.ReturnIfAbrupt(status).
4.Returnobj.

LiteralPropertyName : IdentiierName

1.ReturnStringValueofIdentiierName.

LiteralPropertyName : StringLiteral

1.ReturnaStringvaluewhosecodeunitsaretheSVoftheStringLiteral.

LiteralPropertyName : NumericLiteral

1.LetnbrbetheresultofformingthevalueoftheNumericLiteral.
2.Return!ToString(nbr).

ComputedPropertyName : [ AssignmentExpression ]

1.LetexprValuebetheresultofevaluatingAssignmentExpression.
2.LetpropNamebe?GetValue(exprValue).
3.Return?ToPropertyKey(propName).

12.2.6.9 RuntimeSemantics:PropertyDeinitionEvaluation

Withparametersobjectandenumerable.

PropertyDeinitionList : PropertyDeinitionList , PropertyDeinition

1.LetstatusbetheresultofperformingPropertyDeinitionEvaluationofPropertyDeinitionListwithargumentsobjectand
enumerable.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingPropertyDeinitionEvaluationofPropertyDeinitionwithargumentsobjectand
enumerable.

PropertyDeinition : IdentiierReference

1.LetpropNamebeStringValueofIdentiierReference.
2.LetexprValuebetheresultofevaluatingIdentiierReference.
3.LetpropValuebe?GetValue(exprValue).
4.Assert:enumerableistrue.
5.ReturnCreateDataPropertyOrThrow(object,propName,propValue).

PropertyDeinition : PropertyName : AssignmentExpression

1.LetpropKeybetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(propKey).
3.LetexprValueRefbetheresultofevaluatingAssignmentExpression.
4.LetpropValuebe?GetValue(exprValueRef).
5.IfIsAnonymousFunctionDeinition(AssignmentExpression)istrue,then
a.LethasNamePropertybe?HasOwnProperty(propValue,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(propValue,propKey).
6.Assert:enumerableistrue.
7.ReturnCreateDataPropertyOrThrow(object,propKey,propValue).

NOTE AnalternativesemanticsforthisproductionisgiveninB.3.1.

12.2.7 FunctionDeiningExpressions

See14.1forPrimaryExpression : FunctionExpression .

See14.4forPrimaryExpression : GeneratorExpression .

See14.5forPrimaryExpression : ClassExpression .

12.2.8 RegularExpressionLiterals

Syntax

See11.8.5.

12.2.8.1 StaticSemantics:EarlyErrors

PrimaryExpression : RegularExpressionLiteral

ItisaSyntaxErrorifBodyTextofRegularExpressionLiteralcannotberecognizedusingthegoalsymbolPatternofthe
ECMAScriptRegExpgrammarspeciiedin21.2.1.
ItisaSyntaxErrorifFlagTextofRegularExpressionLiteralcontainsanycodepointsotherthan"g","i","m","u",or
"y",orifitcontainsthesamecodepointmorethanonce.

12.2.8.2 RuntimeSemantics:Evaluation

PrimaryExpression : RegularExpressionLiteral

1.LetpatternbetheStringvalueconsistingoftheUTF16EncodingofeachcodepointofBodyTextof
RegularExpressionLiteral.
2.LetlagsbetheStringvalueconsistingoftheUTF16EncodingofeachcodepointofFlagTextofRegularExpressionLiteral.
3.ReturnRegExpCreate(pattern,lags).

12.2.9 TemplateLiterals

Syntax

TemplateLiteral[Yield] :
NoSubstitutionTemplate
TemplateHead Expression[In,?Yield] TemplateSpans[?Yield]

TemplateSpans[Yield] :
TemplateTail
TemplateMiddleList[?Yield] TemplateTail

TemplateMiddleList[Yield] :
TemplateMiddle Expression[In,?Yield]
TemplateMiddleList[?Yield] TemplateMiddle Expression[In,?Yield]

12.2.9.1 StaticSemantics:TemplateStrings
Withparameterraw.

TemplateLiteral : NoSubstitutionTemplate

1.Ifrawisfalse,then
a.LetstringbetheTVofNoSubstitutionTemplate.
2.Else,
a.LetstringbetheTRVofNoSubstitutionTemplate.
3.ReturnaListcontainingthesingleelement,string.

TemplateLiteral : TemplateHead Expression TemplateSpans

1.Ifrawisfalse,then
a.LetheadbetheTVofTemplateHead.
2.Else,
a.LetheadbetheTRVofTemplateHead.
3.LettailbeTemplateStringsofTemplateSpanswithargumentraw.
4.ReturnaListcontainingheadfollowedbytheelements,inorder,oftail.

TemplateSpans : TemplateTail

1.Ifrawisfalse,then
a.LettailbetheTVofTemplateTail.
2.Else,
a.LettailbetheTRVofTemplateTail.
3.ReturnaListcontainingthesingleelement,tail.

TemplateSpans : TemplateMiddleList TemplateTail

1.LetmiddlebeTemplateStringsofTemplateMiddleListwithargumentraw.
2.Ifrawisfalse,then
a.LettailbetheTVofTemplateTail.
3.Else,
a.LettailbetheTRVofTemplateTail.
4.ReturnaListcontainingtheelements,inorder,ofmiddlefollowedbytail.

TemplateMiddleList : TemplateMiddle Expression

1.Ifrawisfalse,then
a.LetstringbetheTVofTemplateMiddle.
2.Else,
a.LetstringbetheTRVofTemplateMiddle.
3.ReturnaListcontainingthesingleelement,string.

TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression

1.LetfrontbeTemplateStringsofTemplateMiddleListwithargumentraw.
2.Ifrawisfalse,then
a.LetlastbetheTVofTemplateMiddle.
3.Else,
a.LetlastbetheTRVofTemplateMiddle.
4.AppendlastasthelastelementoftheListfront.
5.Returnfront.

12.2.9.2 RuntimeSemantics:ArgumentListEvaluation

TemplateLiteral : NoSubstitutionTemplate

1.LettemplateLiteralbethisTemplateLiteral.
2.LetsiteObjbeGetTemplateObject(templateLiteral).
3.ReturnaListcontainingtheoneelementwhichissiteObj.

TemplateLiteral : TemplateHead Expression TemplateSpans

1.LettemplateLiteralbethisTemplateLiteral.
2.LetsiteObjbeGetTemplateObject(templateLiteral).
3.LetirstSubbetheresultofevaluatingExpression.
4.ReturnIfAbrupt(irstSub).
5.LetrestSubbeSubstitutionEvaluationofTemplateSpans.
6.ReturnIfAbrupt(restSub).
7.Assert:restSubisaList.
8.ReturnaListwhoseirstelementissiteObj,whosesecondelementsisirstSub,andwhosesubsequentelementsarethe
elementsofrestSub,inorder.restSubmaycontainnoelements.

12.2.9.3 RuntimeSemantics:GetTemplateObject(templateLiteral)

TheabstractoperationGetTemplateObjectiscalledwithagrammarproduction,templateLiteral,asanargument.Itperforms
thefollowingsteps:

1.LetrawStringsbeTemplateStringsoftemplateLiteralwithargumenttrue.
2.LetrealmbethecurrentRealmRecord.
3.LettemplateRegistryberealm.[[TemplateMap]].
4.ForeachelementeoftemplateRegistry,do
a.Ife.[[Strings]]andrawStringscontainthesamevaluesinthesameorder,then
i.Returne.[[Array]].
5.LetcookedStringsbeTemplateStringsoftemplateLiteralwithargumentfalse.
6.LetcountbethenumberofelementsintheListcookedStrings.
7.LettemplatebeArrayCreate(count).
8.LetrawObjbeArrayCreate(count).
9.Letindexbe0.
10.Repeatwhileindex<count
a.Letpropbe!ToString(index).
b.LetcookedValuebetheStringvaluecookedStrings[index].
c.Calltemplate.[[DeineOwnProperty]](prop,PropertyDescriptor{[[Value]]:cookedValue,[[Writable]]:false,
[[Enumerable]]:true,[[Conigurable]]:false}).
d.LetrawValuebetheStringvaluerawStrings[index].
e.CallrawObj.[[DeineOwnProperty]](prop,PropertyDescriptor{[[Value]]:rawValue,[[Writable]]:false,
[[Enumerable]]:true,[[Conigurable]]:false}).
f.Letindexbeindex+1.
11.PerformSetIntegrityLevel(rawObj,"frozen").
12.Calltemplate.[[DeineOwnProperty]]("raw",PropertyDescriptor{[[Value]]:rawObj,[[Writable]]:false,[[Enumerable]]:
false,[[Conigurable]]:false}).
13.PerformSetIntegrityLevel(template,"frozen").
14.AppendtheRecord{[[Strings]]:rawStrings,[[Array]]:template}totemplateRegistry.
15.Returntemplate.

NOTE1 Thecreationofatemplateobjectcannotresultinanabruptcompletion.

NOTE2 EachTemplateLiteralintheprogramcodeofarealmisassociatedwithauniquetemplateobjectthatisusedin
theevaluationoftaggedTemplates(12.2.9.5).Thetemplateobjectsarefrozenandthesametemplateobjectis
usedeachtimeaspeciictaggedTemplateisevaluated.Whethertemplateobjectsarecreatedlazilyuponirst
evaluationoftheTemplateLiteraloreagerlypriortoirstevaluationisanimplementationchoicethatisnot
observabletoECMAScriptcode.

NOTE3 Futureeditionsofthisspeciicationmaydeineadditionalnonenumerablepropertiesoftemplateobjects.
12.2.9.4 RuntimeSemantics:SubstitutionEvaluation

TemplateSpans : TemplateTail

1.ReturnanewemptyList.

TemplateSpans : TemplateMiddleList TemplateTail

1.ReturntheresultofSubstitutionEvaluationofTemplateMiddleList.

TemplateMiddleList : TemplateMiddle Expression

1.LetsubbetheresultofevaluatingExpression.
2.ReturnIfAbrupt(sub).
3.ReturnaListcontainingonlysub.

TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression

1.LetprecedingbetheresultofSubstitutionEvaluationofTemplateMiddleList.
2.ReturnIfAbrupt(preceding).
3.LetnextbetheresultofevaluatingExpression.
4.ReturnIfAbrupt(next).
5.AppendnextasthelastelementoftheListpreceding.
6.Returnpreceding.

12.2.9.5 RuntimeSemantics:Evaluation

TemplateLiteral : NoSubstitutionTemplate

1.ReturntheStringvaluewhosecodeunitsaretheelementsoftheTVofNoSubstitutionTemplateasdeinedin11.8.6.

TemplateLiteral : TemplateHead Expression TemplateSpans

1.LetheadbetheTVofTemplateHeadasdeinedin11.8.6.
2.LetsubbetheresultofevaluatingExpression.
3.ReturnIfAbrupt(sub).
4.Letmiddlebe?ToString(sub).
5.LettailbetheresultofevaluatingTemplateSpans.
6.ReturnIfAbrupt(tail).
7.ReturntheStringvaluewhosecodeunitsaretheelementsofheadfollowedbytheelementsofmiddlefollowedbythe
elementsoftail.

NOTE1 ThestringconversionsemanticsappliedtotheExpressionvaluearelikeString.prototype.concatrather
thanthe+operator.

TemplateSpans : TemplateTail

1.LettailbetheTVofTemplateTailasdeinedin11.8.6.
2.Returnthestringconsistingofthecodeunitsoftail.

TemplateSpans : TemplateMiddleList TemplateTail

1.LetheadbetheresultofevaluatingTemplateMiddleList.
2.ReturnIfAbrupt(head).
3.LettailbetheTVofTemplateTailasdeinedin11.8.6.
4.Returnthestringwhosecodeunitsaretheelementsofheadfollowedbytheelementsoftail.

TemplateMiddleList : TemplateMiddle Expression

1.LetheadbetheTVofTemplateMiddleasdeinedin11.8.6.
2.LetsubbetheresultofevaluatingExpression.
3.ReturnIfAbrupt(sub).
4.Letmiddlebe?ToString(sub).
5.Returnthesequenceofcodeunitsconsistingofthecodeunitsofheadfollowedbytheelementsofmiddle.

NOTE2 ThestringconversionsemanticsappliedtotheExpressionvaluearelikeString.prototype.concatrather
thanthe+operator.

TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression

1.LetrestbetheresultofevaluatingTemplateMiddleList.
2.ReturnIfAbrupt(rest).
3.LetmiddlebetheTVofTemplateMiddleasdeinedin11.8.6.
4.LetsubbetheresultofevaluatingExpression.
5.ReturnIfAbrupt(sub).
6.Letlastbe?ToString(sub).
7.Returnthesequenceofcodeunitsconsistingoftheelementsofrestfollowedbythecodeunitsofmiddlefollowedbythe
elementsoflast.

NOTE3 ThestringconversionsemanticsappliedtotheExpressionvaluearelikeString.prototype.concatrather
thanthe+operator.

12.2.10 TheGroupingOperator

12.2.10.1 StaticSemantics:EarlyErrors

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

ItisaSyntaxErrorifthelexicaltokensequencematchedbyCoverParenthesizedExpressionAndArrowParameterList
cannotbeparsedwithnotokensleftoverusingParenthesizedExpressionasthegoalsymbol.
AllEarlyErrorsrulesforParenthesizedExpressionanditsderivedproductionsalsoapplyto
CoveredParenthesizedExpressionofCoverParenthesizedExpressionAndArrowParameterList.

12.2.10.2 StaticSemantics:IsFunctionDeinition

ParenthesizedExpression : ( Expression )

1.ReturnIsFunctionDeinitionofExpression.

12.2.10.3 StaticSemantics:IsValidSimpleAssignmentTarget

ParenthesizedExpression : ( Expression )

1.ReturnIsValidSimpleAssignmentTargetofExpression.

12.2.10.4 RuntimeSemantics:Evaluation

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

1.LetexprbeCoveredParenthesizedExpressionofCoverParenthesizedExpressionAndArrowParameterList.
2.Returntheresultofevaluatingexpr.

ParenthesizedExpression : ( Expression )

1.ReturntheresultofevaluatingExpression.ThismaybeoftypeReference.

NOTE ThisalgorithmdoesnotapplyGetValuetotheresultofevaluatingExpression.Theprincipalmotivationforthis
issothatoperatorssuchasdeleteandtypeofmaybeappliedtoparenthesizedexpressions.

12.3 LeftHandSideExpressions
Syntax

MemberExpression[Yield] :
PrimaryExpression[?Yield]
MemberExpression[?Yield] [ Expression[In,?Yield] ]
MemberExpression[?Yield] . IdentiierName
MemberExpression[?Yield] TemplateLiteral[?Yield]
SuperProperty[?Yield]
MetaProperty
new MemberExpression[?Yield] Arguments[?Yield]

SuperProperty[Yield] :
super [ Expression[In,?Yield] ]
super . IdentiierName

MetaProperty :
NewTarget

NewTarget :
new . target

NewExpression[Yield] :
MemberExpression[?Yield]
new NewExpression[?Yield]

CallExpression[Yield] :
MemberExpression[?Yield] Arguments[?Yield]
SuperCall[?Yield]
CallExpression[?Yield] Arguments[?Yield]
CallExpression[?Yield] [ Expression[In,?Yield] ]
CallExpression[?Yield] . IdentiierName
CallExpression[?Yield] TemplateLiteral[?Yield]

SuperCall[Yield] :
super Arguments[?Yield]

Arguments[Yield] :
( )
( ArgumentList[?Yield] )

ArgumentList[Yield] :
AssignmentExpression[In,?Yield]
... AssignmentExpression[In,?Yield]
ArgumentList[?Yield] , AssignmentExpression[In,?Yield]
ArgumentList[?Yield] , ... AssignmentExpression[In,?Yield]

LeftHandSideExpression[Yield] :
NewExpression[?Yield]
CallExpression[?Yield]

12.3.1 StaticSemantics

12.3.1.1 StaticSemantics:Contains
Withparametersymbol.

MemberExpression : MemberExpression . IdentiierName

1.IfMemberExpressionContainssymbolistrue,returntrue.
2.IfsymbolisaReservedWord,returnfalse.
3.IfsymbolisanIdentiierandStringValueofsymbolisthesamevalueastheStringValueofIdentiierName,returntrue.
4.Returnfalse.

SuperProperty : super . IdentiierName

1.IfsymbolistheReservedWordsuper,returntrue.
2.IfsymbolisaReservedWord,returnfalse.
3.IfsymbolisanIdentiierandStringValueofsymbolisthesamevalueastheStringValueofIdentiierName,returntrue.
4.Returnfalse.

CallExpression : CallExpression . IdentiierName

1.IfCallExpressionContainssymbolistrue,returntrue.
2.IfsymbolisaReservedWord,returnfalse.
3.IfsymbolisanIdentiierandStringValueofsymbolisthesamevalueastheStringValueofIdentiierName,returntrue.
4.Returnfalse.

12.3.1.2 StaticSemantics:IsFunctionDeinition

MemberExpression :
MemberExpression [ Expression ]
MemberExpression . IdentiierName
MemberExpression TemplateLiteral
SuperProperty
MetaProperty
new MemberExpression Arguments

NewExpression :
new NewExpression

CallExpression :
MemberExpression Arguments
SuperCall
CallExpression Arguments
CallExpression [ Expression ]
CallExpression . IdentiierName
CallExpression TemplateLiteral

1.Returnfalse.

12.3.1.3 StaticSemantics:IsDestructuring

MemberExpression : PrimaryExpression

1.IfPrimaryExpressioniseitheranObjectLiteraloranArrayLiteral,returntrue.
2.Returnfalse.

MemberExpression :
MemberExpression [ Expression ]
MemberExpression . IdentiierName
MemberExpression TemplateLiteral
SuperProperty
MetaProperty
new MemberExpression Arguments

NewExpression :
new NewExpression

CallExpression :
MemberExpression Arguments
SuperCall
CallExpression Arguments
CallExpression [ Expression ]
CallExpression . IdentiierName
CallExpression TemplateLiteral

1.Returnfalse.

12.3.1.4 StaticSemantics:IsIdentiierRef

LeftHandSideExpression :
CallExpression

MemberExpression :
MemberExpression [ Expression ]
MemberExpression . IdentiierName
MemberExpression TemplateLiteral
SuperProperty
MetaProperty
new MemberExpression Arguments

NewExpression :
new NewExpression

1.Returnfalse.

12.3.1.5 StaticSemantics:IsValidSimpleAssignmentTarget

CallExpression :
CallExpression [ Expression ]
CallExpression . IdentiierName

MemberExpression :
MemberExpression [ Expression ]
MemberExpression . IdentiierName
SuperProperty

1.Returntrue.

CallExpression :
MemberExpression Arguments
SuperCall
CallExpression Arguments
CallExpression TemplateLiteral

NewExpression :
new NewExpression

MemberExpression :
MemberExpression TemplateLiteral
new MemberExpression Arguments

NewTarget :
new . target

1.Returnfalse.

12.3.2 PropertyAccessors

NOTE Propertiesareaccessedbyname,usingeitherthedotnotation:

MemberExpression.IdentiierName
CallExpression.IdentiierName

orthebracketnotation:

MemberExpression[Expression]
CallExpression[Expression]

Thedotnotationisexplainedbythefollowingsyntacticconversion:

MemberExpression.IdentiierName

isidenticalinitsbehaviourto

MemberExpression[<identiiernamestring>]

andsimilarly

CallExpression.IdentiierName

isidenticalinitsbehaviourto

CallExpression[<identiiernamestring>]

where<identiiernamestring>istheresultofevaluatingStringValueofIdentiierName.

12.3.2.1 RuntimeSemantics:Evaluation

MemberExpression : MemberExpression [ Expression ]

1.LetbaseReferencebetheresultofevaluatingMemberExpression.
2.LetbaseValuebe?GetValue(baseReference).
3.LetpropertyNameReferencebetheresultofevaluatingExpression.
4.LetpropertyNameValuebe?GetValue(propertyNameReference).
5.Letbvbe?RequireObjectCoercible(baseValue).
6.LetpropertyKeybe?ToPropertyKey(propertyNameValue).
7.Ifthecodematchedbythesyntacticproductionthatisbeingevaluatedisstrictmodecode,letstrictbetrue,elselet
strictbefalse.
8.ReturnavalueoftypeReferencewhosebasevalueisbv,whosereferencednameispropertyKey,andwhosestrict
referencelagisstrict.

MemberExpression : MemberExpression . IdentiierName

1.LetbaseReferencebetheresultofevaluatingMemberExpression.
2.LetbaseValuebe?GetValue(baseReference).
3.Letbvbe?RequireObjectCoercible(baseValue).
4.LetpropertyNameStringbeStringValueofIdentiierName.
5.Ifthecodematchedbythesyntacticproductionthatisbeingevaluatedisstrictmodecode,letstrictbetrue,elselet
strictbefalse.
6.ReturnavalueoftypeReferencewhosebasevalueisbv,whosereferencednameispropertyNameString,andwhose
strictreferencelagisstrict.

CallExpression : CallExpression [ Expression ]

IsevaluatedinexactlythesamemannerasMemberExpression : MemberExpression [ Expression ] exceptthatthe


containedCallExpressionisevaluatedinstep1.

CallExpression : CallExpression . IdentiierName

IsevaluatedinexactlythesamemannerasMemberExpression : MemberExpression . IdentiierName exceptthatthe


containedCallExpressionisevaluatedinstep1.

12.3.3 ThenewOperator

12.3.3.1 RuntimeSemantics:Evaluation

NewExpression : new NewExpression

1.Return?EvaluateNew(NewExpression,empty).

MemberExpression : new MemberExpression Arguments

1.Return?EvaluateNew(MemberExpression,Arguments).

12.3.3.1.1 RuntimeSemantics:EvaluateNew(constructProduction,arguments)

TheabstractoperationEvaluateNewwithargumentsconstructProduction,andargumentsperformsthefollowingsteps:

1.Assert:constructProductioniseitheraNewExpressionoraMemberExpression.
2.Assert:argumentsiseitheremptyoranArgumentsproduction.
3.LetrefbetheresultofevaluatingconstructProduction.
4.Letconstructorbe?GetValue(ref).
5.Ifargumentsisempty,letargListbeanewemptyList.
6.Else,
a.LetargListbeArgumentListEvaluationofarguments.
b.ReturnIfAbrupt(argList).
7.IfIsConstructor(constructor)isfalse,throwaTypeErrorexception.
8.Return?Construct(constructor,argList).

12.3.4 FunctionCalls

12.3.4.1 RuntimeSemantics:Evaluation

CallExpression : MemberExpression Arguments

1.LetrefbetheresultofevaluatingMemberExpression.
2.Letfuncbe?GetValue(ref).
3.IfType(ref)isReferenceandIsPropertyReference(ref)isfalseandGetReferencedName(ref)is"eval",then
a.IfSameValue(func,%eval%)istrue,then
i.LetargListbe?ArgumentListEvaluation(Arguments).
ii.IfargListhasnoelements,returnundeined.
iii.LetevalTextbetheirstelementofargList.
iv.IfthesourcecodematchingthisCallExpressionisstrictcode,letstrictCallerbetrue.OtherwiseletstrictCaller
befalse.
v.LetevalRealmbethecurrentRealmRecord.
vi.Return?PerformEval(evalText,evalRealm,strictCaller,true).
4.IfType(ref)isReference,then
a.IfIsPropertyReference(ref)istrue,then
i.LetthisValuebeGetThisValue(ref).
b.Else,thebaseofrefisanEnvironmentRecord
i.LetrefEnvbeGetBase(ref).
ii.LetthisValueberefEnv.WithBaseObject().
5.ElseType(ref)isnotReference,
a.LetthisValuebeundeined.
6.LetthisCallbethisCallExpression.
7.LettailCallbeIsInTailPosition(thisCall).
8.Return?EvaluateDirectCall(func,thisValue,Arguments,tailCall).

ACallExpressionevaluationthatexecutesstep3.a.viisadirecteval.

CallExpression : CallExpression Arguments

1.LetrefbetheresultofevaluatingCallExpression.
2.LetthisCallbethisCallExpression.
3.LettailCallbeIsInTailPosition(thisCall).
4.Return?EvaluateCall(ref,Arguments,tailCall).

12.3.4.2 RuntimeSemantics:EvaluateCall(ref,arguments,tailPosition)

TheabstractoperationEvaluateCalltakesasargumentsavalueref,asyntacticgrammarproductionarguments,anda
BooleanargumenttailPosition.Itperformsthefollowingsteps:

1.Letfuncbe?GetValue(ref).
2.IfType(ref)isReference,then
a.IfIsPropertyReference(ref)istrue,then
i.LetthisValuebeGetThisValue(ref).
b.Else,thebaseofrefisanEnvironmentRecord
i.LetrefEnvbeGetBase(ref).
ii.LetthisValueberefEnv.WithBaseObject().
3.ElseType(ref)isnotReference,
a.LetthisValuebeundeined.
4.Return?EvaluateDirectCall(func,thisValue,arguments,tailPosition).

12.3.4.3 RuntimeSemantics:EvaluateDirectCall(func,thisValue,arguments,tailPosition)

TheabstractoperationEvaluateDirectCalltakesasargumentsavaluefunc,avaluethisValue,asyntacticgrammarproduction
arguments,andaBooleanargumenttailPosition.Itperformsthefollowingsteps:

1.LetargListbe?ArgumentListEvaluation(arguments).
2.IfType(func)isnotObject,throwaTypeErrorexception.
3.IfIsCallable(func)isfalse,throwaTypeErrorexception.
4.IftailPositionistrue,performPrepareForTailCall().
5.LetresultbeCall(func,thisValue,argList).
6.Assert:IftailPositionistrue,theabovecallwillnotreturnhere,butinsteadevaluationwillcontinueasifthefollowing
returnhasalreadyoccurred.
7.Assert:Ifresultisnotanabruptcompletion,thenType(result)isanECMAScriptlanguagetype.
8.Returnresult.

12.3.5 ThesuperKeyword

12.3.5.1 RuntimeSemantics:Evaluation

SuperProperty : super [ Expression ]

1.LetpropertyNameReferencebetheresultofevaluatingExpression.
2.LetpropertyNameValuebeGetValue(propertyNameReference).
3.LetpropertyKeybe?ToPropertyKey(propertyNameValue).
4.Ifthecodematchedbythesyntacticproductionthatisbeingevaluatedisstrictmodecode,letstrictbetrue,elselet
strictbefalse.
5.Return?MakeSuperPropertyReference(propertyKey,strict).

SuperProperty : super . IdentiierName

1.LetpropertyKeybeStringValueofIdentiierName.
2.Ifthecodematchedbythesyntacticproductionthatisbeingevaluatedisstrictmodecode,letstrictbetrue,elselet
strictbefalse.
3.Return?MakeSuperPropertyReference(propertyKey,strict).

SuperCall : super Arguments

1.LetnewTargetbeGetNewTarget().
2.IfnewTargetisundeined,throwaReferenceErrorexception.
3.Letfuncbe?GetSuperConstructor().
4.LetargListbeArgumentListEvaluationofArguments.
5.ReturnIfAbrupt(argList).
6.Letresultbe?Construct(func,argList,newTarget).
7.LetthisERbeGetThisEnvironment().
8.Return?thisER.BindThisValue(result).

12.3.5.2 RuntimeSemantics:GetSuperConstructor()

TheabstractoperationGetSuperConstructorperformsthefollowingsteps:

1.LetenvRecbeGetThisEnvironment().
2.Assert:envRecisafunctionEnvironmentRecord.
3.LetactiveFunctionbeenvRec.[[FunctionObject]].
4.LetsuperConstructorbe?activeFunction.[[GetPrototypeOf]]().
5.IfIsConstructor(superConstructor)isfalse,throwaTypeErrorexception.
6.ReturnsuperConstructor.

12.3.5.3 RuntimeSemantics:MakeSuperPropertyReference(propertyKey,strict)

TheabstractoperationMakeSuperPropertyReferencewithargumentspropertyKeyandstrictperformsthefollowingsteps:

1.LetenvbeGetThisEnvironment().
2.Ifenv.HasSuperBinding()isfalse,throwaReferenceErrorexception.
3.LetactualThisbe?env.GetThisBinding().
4.LetbaseValuebe?env.GetSuperBase().
5.Letbvbe?RequireObjectCoercible(baseValue).
6.ReturnavalueoftypeReferencethatisaSuperReferencewhosebasevalueisbv,whosereferencednameis
propertyKey,whosethisValueisactualThis,andwhosestrictreferencelagisstrict.

12.3.6 ArgumentLists

NOTE TheevaluationofanargumentlistproducesaListofvalues.

12.3.6.1 RuntimeSemantics:ArgumentListEvaluation

Arguments : ( )

1.ReturnanewemptyList.

ArgumentList : AssignmentExpression

1.LetrefbetheresultofevaluatingAssignmentExpression.
2.Letargbe?GetValue(ref).
3.ReturnaListwhosesoleitemisarg.

ArgumentList : ... AssignmentExpression

1.LetlistbeanewemptyList.
2.LetspreadRefbetheresultofevaluatingAssignmentExpression.
3.LetspreadObjbe?GetValue(spreadRef).
4.Letiteratorbe?GetIterator(spreadObj).
5.Repeat
a.Letnextbe?IteratorStep(iterator).
b.Ifnextisfalse,returnlist.
c.LetnextArgbe?IteratorValue(next).
d.AppendnextArgasthelastelementoflist.

ArgumentList : ArgumentList , AssignmentExpression

1.LetprecedingArgsbetheresultofevaluatingArgumentList.
2.ReturnIfAbrupt(precedingArgs).
3.LetrefbetheresultofevaluatingAssignmentExpression.
4.Letargbe?GetValue(ref).
5.AppendargtotheendofprecedingArgs.
6.ReturnprecedingArgs.

ArgumentList : ArgumentList , ... AssignmentExpression

1.LetprecedingArgsbetheresultofevaluatingArgumentList.
2.LetspreadRefbetheresultofevaluatingAssignmentExpression.
3.Letiteratorbe?GetIterator(?GetValue(spreadRef)).
4.Repeat
a.Letnextbe?IteratorStep(iterator).
b.Ifnextisfalse,returnprecedingArgs.
c.LetnextArgbe?IteratorValue(next).
d.AppendnextArgasthelastelementofprecedingArgs.

12.3.7 TaggedTemplates

NOTE AtaggedtemplateisafunctioncallwheretheargumentsofthecallarederivedfromaTemplateLiteral(12.2.9).
Theactualargumentsincludeatemplateobject(12.2.9.3)andthevaluesproducedbyevaluatingthe
expressionsembeddedwithintheTemplateLiteral.

12.3.7.1 RuntimeSemantics:Evaluation

MemberExpression : MemberExpression TemplateLiteral

1.LettagRefbetheresultofevaluatingMemberExpression.
2.LetthisCallbethisMemberExpression.
3.LettailCallbeIsInTailPosition(thisCall).
4.Return?EvaluateCall(tagRef,TemplateLiteral,tailCall).

CallExpression : CallExpression TemplateLiteral

1.LettagRefbetheresultofevaluatingCallExpression.
2.LetthisCallbethisCallExpression.
3.LettailCallbeIsInTailPosition(thisCall).
4.Return?EvaluateCall(tagRef,TemplateLiteral,tailCall).

12.3.8 MetaProperties
12.3.8.1 RuntimeSemantics:Evaluation

NewTarget : new . target

1.ReturnGetNewTarget().

12.4 UpdateExpressions
Syntax

UpdateExpression[Yield] :
LeftHandSideExpression[?Yield]
LeftHandSideExpression[?Yield] [noLineTerminatorhere] ++
LeftHandSideExpression[?Yield] [noLineTerminatorhere]
++ UnaryExpression[?Yield]
UnaryExpression[?Yield]

12.4.1 StaticSemantics:EarlyErrors

UpdateExpression :
LeftHandSideExpression ++
LeftHandSideExpression

ItisanearlyReferenceErrorifIsValidSimpleAssignmentTargetofLeftHandSideExpressionisfalse.

UpdateExpression :
++ UnaryExpression
UnaryExpression

ItisanearlyReferenceErrorifIsValidSimpleAssignmentTargetofUnaryExpressionisfalse.

12.4.2 StaticSemantics:IsFunctionDeinition

UpdateExpression :
LeftHandSideExpression ++
LeftHandSideExpression
++ UnaryExpression
UnaryExpression

1.Returnfalse.

12.4.3 StaticSemantics:IsValidSimpleAssignmentTarget

UpdateExpression :
LeftHandSideExpression ++
LeftHandSideExpression
++ UnaryExpression
UnaryExpression

1.Returnfalse.

12.4.4 PostixIncrementOperator

12.4.4.1 RuntimeSemantics:Evaluation

UpdateExpression : LeftHandSideExpression ++

1.LetlhsbetheresultofevaluatingLeftHandSideExpression.
2.LetoldValuebe?ToNumber(?GetValue(lhs)).
3.LetnewValuebetheresultofaddingthevalue1tooldValue,usingthesamerulesasforthe+operator(see12.8.5).
4.Perform?PutValue(lhs,newValue).
5.ReturnoldValue.

12.4.5 PostixDecrementOperator

12.4.5.1 RuntimeSemantics:Evaluation

UpdateExpression : LeftHandSideExpression

1.LetlhsbetheresultofevaluatingLeftHandSideExpression.
2.LetoldValuebe?ToNumber(?GetValue(lhs)).
3.LetnewValuebetheresultofsubtractingthevalue1fromoldValue,usingthesamerulesasfortheoperator(see
12.8.5).
4.Perform?PutValue(lhs,newValue).
5.ReturnoldValue.

12.4.6 PreixIncrementOperator

12.4.6.1 RuntimeSemantics:Evaluation

UpdateExpression : ++ UnaryExpression

1.LetexprbetheresultofevaluatingUnaryExpression.
2.LetoldValuebe?ToNumber(?GetValue(expr)).
3.LetnewValuebetheresultofaddingthevalue1tooldValue,usingthesamerulesasforthe+operator(see12.8.5).
4.Perform?PutValue(expr,newValue).
5.ReturnnewValue.

12.4.7 PreixDecrementOperator

12.4.7.1 RuntimeSemantics:Evaluation

UpdateExpression : UnaryExpression

1.LetexprbetheresultofevaluatingUnaryExpression.
2.LetoldValuebe?ToNumber(?GetValue(expr)).
3.LetnewValuebetheresultofsubtractingthevalue1fromoldValue,usingthesamerulesasfortheoperator(see
12.8.5).
4.Perform?PutValue(expr,newValue).
5.ReturnnewValue.

12.5 UnaryOperators
Syntax

UnaryExpression[Yield] :
UpdateExpression[?Yield]
delete UnaryExpression[?Yield]
void UnaryExpression[?Yield]
typeof UnaryExpression[?Yield]
+ UnaryExpression[?Yield]
UnaryExpression[?Yield]
~ UnaryExpression[?Yield]
! UnaryExpression[?Yield]
12.5.1 StaticSemantics:IsFunctionDeinition

UnaryExpression :
UpdateExpression
delete UnaryExpression
void UnaryExpression
typeof UnaryExpression
+ UnaryExpression
UnaryExpression
~ UnaryExpression
! UnaryExpression

1.Returnfalse.

12.5.2 StaticSemantics:IsValidSimpleAssignmentTarget

UnaryExpression :
UpdateExpression
delete UnaryExpression
void UnaryExpression
typeof UnaryExpression
+ UnaryExpression
UnaryExpression
~ UnaryExpression
! UnaryExpression

1.Returnfalse.

12.5.3 ThedeleteOperator

12.5.3.1 StaticSemantics:EarlyErrors

UnaryExpression : delete UnaryExpression

ItisaSyntaxErroriftheUnaryExpressioniscontainedinstrictmodecodeandthederivedUnaryExpressionis
PrimaryExpression : IdentiierReference .

ItisaSyntaxErrorifthederivedUnaryExpressionis
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
andCoverParenthesizedExpressionAndArrowParameterListultimatelyderivesaphrasethat,ifusedinplaceof
UnaryExpression,wouldproduceaSyntaxErroraccordingtotheserules.Thisruleisrecursivelyapplied.

NOTE Thelastrulemeansthatexpressionssuchasdelete(((foo)))produceearlyerrorsbecauseofrecursive
applicationoftheirstrule.

12.5.3.2 RuntimeSemantics:Evaluation

UnaryExpression : delete UnaryExpression

1.LetrefbetheresultofevaluatingUnaryExpression.
2.ReturnIfAbrupt(ref).
3.IfType(ref)isnotReference,returntrue.
4.IfIsUnresolvableReference(ref)istrue,then
a.Assert:IsStrictReference(ref)isfalse.
b.Returntrue.
5.IfIsPropertyReference(ref)istrue,then
a.IfIsSuperReference(ref)istrue,throwaReferenceErrorexception.
b.LetbaseObjbe!ToObject(GetBase(ref)).
c.LetdeleteStatusbe?baseObj.[[Delete]](GetReferencedName(ref)).
d.IfdeleteStatusisfalseandIsStrictReference(ref)istrue,throwaTypeErrorexception.
e.ReturndeleteStatus.
6.ElserefisaReferencetoanEnvironmentRecordbinding,
a.LetbindingsbeGetBase(ref).
b.Return?bindings.DeleteBinding(GetReferencedName(ref)).

NOTE Whenadeleteoperatoroccurswithinstrictmodecode,aSyntaxErrorexceptionisthrownifits
UnaryExpressionisadirectreferencetoavariable,functionargument,orfunctionname.Inaddition,ifa
deleteoperatoroccurswithinstrictmodecodeandthepropertytobedeletedhastheattribute{
[[Conigurable]]:false},aTypeErrorexceptionisthrown.

12.5.4 ThevoidOperator

12.5.4.1 RuntimeSemantics:Evaluation

UnaryExpression : void UnaryExpression

1.LetexprbetheresultofevaluatingUnaryExpression.
2.Perform?GetValue(expr).
3.Returnundeined.

NOTE GetValuemustbecalledeventhoughitsvalueisnotusedbecauseitmayhaveobservablesideeffects.

12.5.5 ThetypeofOperator

12.5.5.1 RuntimeSemantics:Evaluation

UnaryExpression : typeof UnaryExpression

1.LetvalbetheresultofevaluatingUnaryExpression.
2.IfType(val)isReference,then
a.IfIsUnresolvableReference(val)istrue,return"undefined".
3.Letvalbe?GetValue(val).
4.ReturnaStringaccordingtoTable35.

Table35:typeofOperatorResults
Typeofval Result

Undeined "undefined"

Null "object"

Boolean "boolean"

Number "number"

String "string"

Symbol "symbol"

Object(ordinaryanddoesnotimplement "object"
[[Call]])

Object(standardexoticanddoesnot "object"
implement[[Call]])

Object(implements[[Call]]) "function"

Object(nonstandardexoticanddoesnot Implementationdeined.Mustnotbe"undefined","boolean","function",
implement[[Call]]) "number","symbol",or"string".
NOTE Implementationsarediscouragedfromdeiningnewtypeofresultvaluesfornonstandardexoticobjects.If
possible"object"shouldbeusedforsuchobjects.

12.5.6 Unary+Operator

NOTE Theunary+operatorconvertsitsoperandtoNumbertype.

12.5.6.1 RuntimeSemantics:Evaluation

UnaryExpression : + UnaryExpression

1.LetexprbetheresultofevaluatingUnaryExpression.
2.Return?ToNumber(?GetValue(expr)).

12.5.7 UnaryOperator

NOTE TheunaryoperatorconvertsitsoperandtoNumbertypeandthennegatesit.Negating+0produces0,and
negating0produces+0.

12.5.7.1 RuntimeSemantics:Evaluation

UnaryExpression : UnaryExpression

1.LetexprbetheresultofevaluatingUnaryExpression.
2.LetoldValuebe?ToNumber(?GetValue(expr)).
3.IfoldValueisNaN,returnNaN.
4.ReturntheresultofnegatingoldValue;thatis,computeaNumberwiththesamemagnitudebutoppositesign.

12.5.8 BitwiseNOTOperator(~)

12.5.8.1 RuntimeSemantics:Evaluation

UnaryExpression : ~ UnaryExpression

1.LetexprbetheresultofevaluatingUnaryExpression.
2.LetoldValuebe?ToInt32(?GetValue(expr)).
3.ReturntheresultofapplyingbitwisecomplementtooldValue.Theresultisasigned32bitinteger.

12.5.9 LogicalNOTOperator(!)

12.5.9.1 RuntimeSemantics:Evaluation

UnaryExpression : ! UnaryExpression

1.LetexprbetheresultofevaluatingUnaryExpression.
2.LetoldValuebeToBoolean(?GetValue(expr)).
3.IfoldValueistrue,returnfalse.
4.Returntrue.

12.6 ExponentiationOperator
Syntax

ExponentiationExpression[Yield] :
UnaryExpression[?Yield]
UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]

12.6.1 StaticSemantics:IsFunctionDeinition

ExponentiationExpression :
UpdateExpression ** ExponentiationExpression

1.Returnfalse.

12.6.2 StaticSemantics:IsValidSimpleAssignmentTarget

ExponentiationExpression :
UpdateExpression ** ExponentiationExpression

1.Returnfalse.

12.6.3 RuntimeSemantics:Evaluation
ExponentiationExpression : UpdateExpression ** ExponentiationExpression

1.LetleftbetheresultofevaluatingUpdateExpression.
2.LetleftValuebe?GetValue(left).
3.LetrightbetheresultofevaluatingExponentiationExpression.
4.LetrightValuebe?GetValue(right).
5.Letbasebe?ToNumber(leftValue).
6.Letexponentbe?ToNumber(rightValue).
7.ReturntheresultofApplyingthe**operatorwithbaseandexponentasspeciiedin12.7.3.4.

12.7 MultiplicativeOperators
Syntax

MultiplicativeExpression[Yield] :
ExponentiationExpression[?Yield]
MultiplicativeExpression[?Yield] MultiplicativeOperator ExponentiationExpression[?Yield]

MultiplicativeOperator : oneof
* / %

12.7.1 StaticSemantics:IsFunctionDeinition
MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression

1.Returnfalse.

12.7.2 StaticSemantics:IsValidSimpleAssignmentTarget
MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression

1.Returnfalse.

12.7.3 RuntimeSemantics:Evaluation

MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression

1.LetleftbetheresultofevaluatingMultiplicativeExpression.
2.LetleftValuebe?GetValue(left).
3.LetrightbetheresultofevaluatingExponentiationExpression.
4.LetrightValuebe?GetValue(right).
5.Letlnumbe?ToNumber(leftValue).
6.Letrnumbe?ToNumber(rightValue).
7.ReturntheresultofapplyingtheMultiplicativeOperator(*,/,or%)tolnumandrnumasspeciiedin12.7.3.1,12.7.3.2,or
12.7.3.3.
12.7.3.1 Applyingthe*Operator

The*MultiplicativeOperatorperformsmultiplication,producingtheproductofitsoperands.Multiplicationiscommutative.
MultiplicationisnotalwaysassociativeinECMAScript,becauseofiniteprecision.

TheresultofaloatingpointmultiplicationisgovernedbytherulesofIEEE7542008binarydoubleprecisionarithmetic:

IfeitheroperandisNaN,theresultisNaN.
Thesignoftheresultispositiveifbothoperandshavethesamesign,negativeiftheoperandshavedifferentsigns.
MultiplicationofanininitybyazeroresultsinNaN.
Multiplicationofanininitybyanininityresultsinanininity.Thesignisdeterminedbytherulealreadystatedabove.
Multiplicationofanininitybyainitenonzerovalueresultsinasignedininity.Thesignisdeterminedbytherule
alreadystatedabove.
Intheremainingcases,whereneitheranininitynorNaNisinvolved,theproductiscomputedandroundedtothe
nearestrepresentablevalueusingIEEE7542008roundtonearest,tiestoevenmode.Ifthemagnitudeistoolargeto
represent,theresultisthenanininityofappropriatesign.Ifthemagnitudeistoosmalltorepresent,theresultisthena
zeroofappropriatesign.TheECMAScriptlanguagerequiressupportofgradualunderlowasdeinedbyIEEE7542008.

12.7.3.2 Applyingthe/Operator

The/MultiplicativeOperatorperformsdivision,producingthequotientofitsoperands.Theleftoperandisthedividendand
therightoperandisthedivisor.ECMAScriptdoesnotperformintegerdivision.Theoperandsandresultofalldivision
operationsaredoubleprecisionloatingpointnumbers.TheresultofdivisionisdeterminedbythespeciicationofIEEE
7542008arithmetic:

IfeitheroperandisNaN,theresultisNaN.
Thesignoftheresultispositiveifbothoperandshavethesamesign,negativeiftheoperandshavedifferentsigns.
DivisionofanininitybyanininityresultsinNaN.
Divisionofanininitybyazeroresultsinanininity.Thesignisdeterminedbytherulealreadystatedabove.
Divisionofanininitybyanonzeroinitevalueresultsinasignedininity.Thesignisdeterminedbytherulealready
statedabove.
Divisionofainitevaluebyanininityresultsinzero.Thesignisdeterminedbytherulealreadystatedabove.
DivisionofazerobyazeroresultsinNaN;divisionofzerobyanyotherinitevalueresultsinzero,withthesign
determinedbytherulealreadystatedabove.
Divisionofanonzeroinitevaluebyazeroresultsinasignedininity.Thesignisdeterminedbytherulealreadystated
above.
Intheremainingcases,whereneitheranininity,norazero,norNaNisinvolved,thequotientiscomputedandrounded
tothenearestrepresentablevalueusingIEEE7542008roundtonearest,tiestoevenmode.Ifthemagnitudeistoo
largetorepresent,theoperationoverlows;theresultisthenanininityofappropriatesign.Ifthemagnitudeistoo
smalltorepresent,theoperationunderlowsandtheresultisazerooftheappropriatesign.TheECMAScriptlanguage
requiressupportofgradualunderlowasdeinedbyIEEE7542008.

12.7.3.3 Applyingthe%Operator

The%MultiplicativeOperatoryieldstheremainderofitsoperandsfromanimplieddivision;theleftoperandisthedividend
andtherightoperandisthedivisor.

NOTE InCandC++,theremainderoperatoracceptsonlyintegraloperands;inECMAScript,italsoacceptsloating
pointoperands.

Theresultofaloatingpointremainderoperationascomputedbythe%operatorisnotthesameastheremainder
operationdeinedbyIEEE7542008.TheIEEE7542008remainderoperationcomputestheremainderfromarounding
division,notatruncatingdivision,andsoitsbehaviourisnotanalogoustothatoftheusualintegerremainderoperator.
InsteadtheECMAScriptlanguagedeines%onloatingpointoperationstobehaveinamanneranalogoustothatoftheJava
integerremainderoperator;thismaybecomparedwiththeClibraryfunctionfmod.

TheresultofanECMAScriptloatingpointremainderoperationisdeterminedbytherulesofIEEEarithmetic:
IfeitheroperandisNaN,theresultisNaN.
Thesignoftheresultequalsthesignofthedividend.
Ifthedividendisanininity,orthedivisorisazero,orboth,theresultisNaN.
Ifthedividendisiniteandthedivisorisanininity,theresultequalsthedividend.
Ifthedividendisazeroandthedivisorisnonzeroandinite,theresultisthesameasthedividend.
Intheremainingcases,whereneitheranininity,norazero,norNaNisinvolved,theloatingpointremainderrfroma
dividendnandadivisordisdeinedbythemathematicalrelationr=n(dq)whereqisanintegerthatisnegative
onlyifn/disnegativeandpositiveonlyifn/dispositive,andwhosemagnitudeisaslargeaspossiblewithoutexceeding
themagnitudeofthetruemathematicalquotientofnandd.riscomputedandroundedtothenearestrepresentable
valueusingIEEE7542008roundtonearest,tiestoevenmode.

12.7.3.4 Applyingthe**Operator

Returnsanimplementationdependentapproximationoftheresultofraisingbasetothepowerexponent.

IfexponentisNaN,theresultisNaN.
Ifexponentis+0,theresultis1,evenifbaseisNaN.
Ifexponentis0,theresultis1,evenifbaseisNaN.
IfbaseisNaNandexponentisnonzero,theresultisNaN.
Ifabs(base)>1andexponentis+,theresultis+.
Ifabs(base)>1andexponentis,theresultis+0.
Ifabs(base)is1andexponentis+,theresultisNaN.
Ifabs(base)is1andexponentis,theresultisNaN.
Ifabs(base)<1andexponentis+,theresultis+0.
Ifabs(base)<1andexponentis,theresultis+.
Ifbaseis+andexponent>0,theresultis+.
Ifbaseis+andexponent<0,theresultis+0.
Ifbaseisandexponent>0andexponentisanoddinteger,theresultis.
Ifbaseisandexponent>0andexponentisnotanoddinteger,theresultis+.
Ifbaseisandexponent<0andexponentisanoddinteger,theresultis0.
Ifbaseisandexponent<0andexponentisnotanoddinteger,theresultis+0.
Ifbaseis+0andexponent>0,theresultis+0.
Ifbaseis+0andexponent<0,theresultis+.
Ifbaseis0andexponent>0andexponentisanoddinteger,theresultis0.
Ifbaseis0andexponent>0andexponentisnotanoddinteger,theresultis+0.
Ifbaseis0andexponent<0andexponentisanoddinteger,theresultis.
Ifbaseis0andexponent<0andexponentisnotanoddinteger,theresultis+.
Ifbase<0andbaseisiniteandexponentisiniteandexponentisnotaninteger,theresultisNaN.

NOTE Theresultofbase**exponentwhenbaseis1or1andexponentis+IninityorIninitydiffersfromIEEE
7542008.TheirsteditionofECMAScriptspeciiedaresultofNaNforthisoperation,whereaslaterversions
ofIEEE7542008speciied1.ThehistoricalECMAScriptbehaviourispreservedforcompatibilityreasons.

12.8 AdditiveOperators
Syntax

AdditiveExpression[Yield] :
MultiplicativeExpression[?Yield]
AdditiveExpression[?Yield] + MultiplicativeExpression[?Yield]
AdditiveExpression[?Yield] MultiplicativeExpression[?Yield]

12.8.1 StaticSemantics:IsFunctionDeinition

AdditiveExpression :
AdditiveExpression + MultiplicativeExpression
AdditiveExpression MultiplicativeExpression

1.Returnfalse.

12.8.2 StaticSemantics:IsValidSimpleAssignmentTarget

AdditiveExpression :
AdditiveExpression + MultiplicativeExpression
AdditiveExpression MultiplicativeExpression

1.Returnfalse.

12.8.3 TheAdditionOperator(+)

NOTE Theadditionoperatoreitherperformsstringconcatenationornumericaddition.

12.8.3.1 RuntimeSemantics:Evaluation

AdditiveExpression : AdditiveExpression + MultiplicativeExpression

1.LetlrefbetheresultofevaluatingAdditiveExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingMultiplicativeExpression.
4.Letrvalbe?GetValue(rref).
5.Letlprimbe?ToPrimitive(lval).
6.Letrprimbe?ToPrimitive(rval).
7.IfType(lprim)isStringorType(rprim)isString,then
a.Letlstrbe?ToString(lprim).
b.Letrstrbe?ToString(rprim).
c.ReturntheStringthatistheresultofconcatenatinglstrandrstr.
8.Letlnumbe?ToNumber(lprim).
9.Letrnumbe?ToNumber(rprim).
10.Returntheresultofapplyingtheadditionoperationtolnumandrnum.SeetheNotebelow12.8.5.

NOTE1 NohintisprovidedinthecallstoToPrimitiveinsteps5and6.AllstandardobjectsexceptDateobjectshandle
theabsenceofahintasifthehintNumberweregiven;Dateobjectshandletheabsenceofahintasifthehint
Stringweregiven.Exoticobjectsmayhandletheabsenceofahintinsomeothermanner.

NOTE2 Step7differsfromstep5oftheAbstractRelationalComparisonalgorithm,byusingthelogicaloroperation
insteadofthelogicalandoperation.

12.8.4 TheSubtractionOperator()

12.8.4.1 RuntimeSemantics:Evaluation

AdditiveExpression : AdditiveExpression MultiplicativeExpression

1.LetlrefbetheresultofevaluatingAdditiveExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingMultiplicativeExpression.
4.Letrvalbe?GetValue(rref).
5.Letlnumbe?ToNumber(lval).
6.Letrnumbe?ToNumber(rval).
7.Returntheresultofapplyingthesubtractionoperationtolnumandrnum.Seethenotebelow12.8.5.

12.8.5 ApplyingtheAdditiveOperatorstoNumbers
The+operatorperformsadditionwhenappliedtotwooperandsofnumerictype,producingthesumoftheoperands.The
operatorperformssubtraction,producingthedifferenceoftwonumericoperands.

Additionisacommutativeoperation,butnotalwaysassociative.

TheresultofanadditionisdeterminedusingtherulesofIEEE7542008binarydoubleprecisionarithmetic:

IfeitheroperandisNaN,theresultisNaN.
ThesumoftwoininitiesofoppositesignisNaN.
Thesumoftwoininitiesofthesamesignistheininityofthatsign.
Thesumofanininityandainitevalueisequaltotheininiteoperand.
Thesumoftwonegativezeroesis0.Thesumoftwopositivezeroes,oroftwozeroesofoppositesign,is+0.
Thesumofazeroandanonzeroinitevalueisequaltothenonzerooperand.
Thesumoftwononzeroinitevaluesofthesamemagnitudeandoppositesignis+0.
Intheremainingcases,whereneitheranininity,norazero,norNaNisinvolved,andtheoperandshavethesamesign
orhavedifferentmagnitudes,thesumiscomputedandroundedtothenearestrepresentablevalueusingIEEE754
2008roundtonearest,tiestoevenmode.Ifthemagnitudeistoolargetorepresent,theoperationoverlowsandthe
resultisthenanininityofappropriatesign.TheECMAScriptlanguagerequiressupportofgradualunderlowas
deinedbyIEEE7542008.

NOTE Theoperatorperformssubtractionwhenappliedtotwooperandsofnumerictype,producingthedifference
ofitsoperands;theleftoperandistheminuendandtherightoperandisthesubtrahend.Givennumeric
operandsaandb,itisalwaysthecasethatabproducesthesameresultasa+(b).

12.9 BitwiseShiftOperators
Syntax

ShiftExpression[Yield] :
AdditiveExpression[?Yield]
ShiftExpression[?Yield] << AdditiveExpression[?Yield]
ShiftExpression[?Yield] >> AdditiveExpression[?Yield]
ShiftExpression[?Yield] >>> AdditiveExpression[?Yield]

12.9.1 StaticSemantics:IsFunctionDeinition

ShiftExpression :
ShiftExpression << AdditiveExpression
ShiftExpression >> AdditiveExpression
ShiftExpression >>> AdditiveExpression

1.Returnfalse.

12.9.2 StaticSemantics:IsValidSimpleAssignmentTarget

ShiftExpression :
ShiftExpression << AdditiveExpression
ShiftExpression >> AdditiveExpression
ShiftExpression >>> AdditiveExpression

1.Returnfalse.

12.9.3 TheLeftShiftOperator(<<)

NOTE Performsabitwiseleftshiftoperationontheleftoperandbytheamountspeciiedbytherightoperand.

12.9.3.1 RuntimeSemantics:Evaluation
ShiftExpression : ShiftExpression << AdditiveExpression

1.LetlrefbetheresultofevaluatingShiftExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingAdditiveExpression.
4.Letrvalbe?GetValue(rref).
5.Letlnumbe?ToInt32(lval).
6.Letrnumbe?ToUint32(rval).
7.LetshiftCountbetheresultofmaskingoutallbuttheleastsigniicant5bitsofrnum,thatis,computernum&0x1F.
8.ReturntheresultofleftshiftinglnumbyshiftCountbits.Theresultisasigned32bitinteger.

12.9.4 TheSignedRightShiftOperator(>>)

NOTE Performsasignillingbitwiserightshiftoperationontheleftoperandbytheamountspeciiedbytheright
operand.

12.9.4.1 RuntimeSemantics:Evaluation

ShiftExpression : ShiftExpression >> AdditiveExpression

1.LetlrefbetheresultofevaluatingShiftExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingAdditiveExpression.
4.Letrvalbe?GetValue(rref).
5.Letlnumbe?ToInt32(lval).
6.Letrnumbe?ToUint32(rval).
7.LetshiftCountbetheresultofmaskingoutallbuttheleastsigniicant5bitsofrnum,thatis,computernum&0x1F.
8.ReturntheresultofperformingasignextendingrightshiftoflnumbyshiftCountbits.Themostsigniicantbitis
propagated.Theresultisasigned32bitinteger.

12.9.5 TheUnsignedRightShiftOperator(>>>)

NOTE Performsazeroillingbitwiserightshiftoperationontheleftoperandbytheamountspeciiedbytheright
operand.

12.9.5.1 RuntimeSemantics:Evaluation

ShiftExpression : ShiftExpression >>> AdditiveExpression

1.LetlrefbetheresultofevaluatingShiftExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingAdditiveExpression.
4.Letrvalbe?GetValue(rref).
5.Letlnumbe?ToUint32(lval).
6.Letrnumbe?ToUint32(rval).
7.LetshiftCountbetheresultofmaskingoutallbuttheleastsigniicant5bitsofrnum,thatis,computernum&0x1F.
8.ReturntheresultofperformingazeroillingrightshiftoflnumbyshiftCountbits.Vacatedbitsareilledwithzero.The
resultisanunsigned32bitinteger.

12.10 RelationalOperators
NOTE1 TheresultofevaluatingarelationaloperatorisalwaysoftypeBoolean,relectingwhethertherelationship
namedbytheoperatorholdsbetweenitstwooperands.

Syntax

RelationalExpression[In,Yield] :
ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] < ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] > ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] <= ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] >= ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] instanceof ShiftExpression[?Yield]
[+In] RelationalExpression[In,?Yield] in ShiftExpression[?Yield]

NOTE2 The[In]grammarparameterisneededtoavoidconfusingtheinoperatorinarelationalexpressionwiththe
inoperatorinaforstatement.

12.10.1 StaticSemantics:IsFunctionDeinition

RelationalExpression :
RelationalExpression < ShiftExpression
RelationalExpression > ShiftExpression
RelationalExpression <= ShiftExpression
RelationalExpression >= ShiftExpression
RelationalExpression instanceof ShiftExpression
RelationalExpression in ShiftExpression

1.Returnfalse.

12.10.2 StaticSemantics:IsValidSimpleAssignmentTarget

RelationalExpression :
RelationalExpression < ShiftExpression
RelationalExpression > ShiftExpression
RelationalExpression <= ShiftExpression
RelationalExpression >= ShiftExpression
RelationalExpression instanceof ShiftExpression
RelationalExpression in ShiftExpression

1.Returnfalse.

12.10.3 RuntimeSemantics:Evaluation
RelationalExpression : RelationalExpression < ShiftExpression

1.LetlrefbetheresultofevaluatingRelationalExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingShiftExpression.
4.Letrvalbe?GetValue(rref).
5.LetrbetheresultofperformingAbstractRelationalComparisonlval<rval.
6.ReturnIfAbrupt(r).
7.Ifrisundeined,returnfalse.Otherwise,returnr.

RelationalExpression : RelationalExpression > ShiftExpression

1.LetlrefbetheresultofevaluatingRelationalExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingShiftExpression.
4.Letrvalbe?GetValue(rref).
5.LetrbetheresultofperformingAbstractRelationalComparisonrval<lvalwithLeftFirstequaltofalse.
6.ReturnIfAbrupt(r).
7.Ifrisundeined,returnfalse.Otherwise,returnr.
RelationalExpression : RelationalExpression <= ShiftExpression

1.LetlrefbetheresultofevaluatingRelationalExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingShiftExpression.
4.Letrvalbe?GetValue(rref).
5.LetrbetheresultofperformingAbstractRelationalComparisonrval<lvalwithLeftFirstequaltofalse.
6.ReturnIfAbrupt(r).
7.Ifristrueorundeined,returnfalse.Otherwise,returntrue.

RelationalExpression : RelationalExpression >= ShiftExpression

1.LetlrefbetheresultofevaluatingRelationalExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingShiftExpression.
4.Letrvalbe?GetValue(rref).
5.LetrbetheresultofperformingAbstractRelationalComparisonlval<rval.
6.ReturnIfAbrupt(r).
7.Ifristrueorundeined,returnfalse.Otherwise,returntrue.

RelationalExpression : RelationalExpression instanceof ShiftExpression

1.LetlrefbetheresultofevaluatingRelationalExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingShiftExpression.
4.Letrvalbe?GetValue(rref).
5.Return?InstanceofOperator(lval,rval).

RelationalExpression : RelationalExpression in ShiftExpression

1.LetlrefbetheresultofevaluatingRelationalExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingShiftExpression.
4.Letrvalbe?GetValue(rref).
5.IfType(rval)isnotObject,throwaTypeErrorexception.
6.Return?HasProperty(rval,ToPropertyKey(lval)).

12.10.4 RuntimeSemantics:InstanceofOperator(O,C)

TheabstractoperationInstanceofOperator(O,C)implementsthegenericalgorithmfordeterminingifanobjectOinherits
fromtheinheritancepathdeinedbyconstructorC.Thisabstractoperationperformsthefollowingsteps:

1.IfType(C)isnotObject,throwaTypeErrorexception.
2.LetinstOfHandlerbe?GetMethod(C,@@hasInstance).
3.IfinstOfHandlerisnotundeined,then
a.ReturnToBoolean(?Call(instOfHandler,C,O)).
4.IfIsCallable(C)isfalse,throwaTypeErrorexception.
5.Return?OrdinaryHasInstance(C,O).

NOTE Steps5and6providecompatibilitywithpreviouseditionsofECMAScriptthatdidnotusea@@hasInstance
methodtodeinetheinstanceofoperatorsemantics.Ifafunctionobjectdoesnotdeineorinherit
@@hasInstanceitusesthedefaultinstanceofsemantics.

12.11 EqualityOperators
NOTE TheresultofevaluatinganequalityoperatorisalwaysoftypeBoolean,relectingwhethertherelationship
namedbytheoperatorholdsbetweenitstwooperands.
Syntax

EqualityExpression[In,Yield] :
RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] == RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] != RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] === RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] !== RelationalExpression[?In,?Yield]

12.11.1 StaticSemantics:IsFunctionDeinition

EqualityExpression :
EqualityExpression == RelationalExpression
EqualityExpression != RelationalExpression
EqualityExpression === RelationalExpression
EqualityExpression !== RelationalExpression

1.Returnfalse.

12.11.2 StaticSemantics:IsValidSimpleAssignmentTarget

EqualityExpression :
EqualityExpression == RelationalExpression
EqualityExpression != RelationalExpression
EqualityExpression === RelationalExpression
EqualityExpression !== RelationalExpression

1.Returnfalse.

12.11.3 RuntimeSemantics:Evaluation
EqualityExpression : EqualityExpression == RelationalExpression

1.LetlrefbetheresultofevaluatingEqualityExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingRelationalExpression.
4.Letrvalbe?GetValue(rref).
5.ReturntheresultofperformingAbstractEqualityComparisonrval==lval.

EqualityExpression : EqualityExpression != RelationalExpression

1.LetlrefbetheresultofevaluatingEqualityExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingRelationalExpression.
4.Letrvalbe?GetValue(rref).
5.LetrbetheresultofperformingAbstractEqualityComparisonrval==lval.
6.Ifristrue,returnfalse.Otherwise,returntrue.

EqualityExpression : EqualityExpression === RelationalExpression

1.LetlrefbetheresultofevaluatingEqualityExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingRelationalExpression.
4.Letrvalbe?GetValue(rref).
5.ReturntheresultofperformingStrictEqualityComparisonrval===lval.

EqualityExpression : EqualityExpression !== RelationalExpression


1.LetlrefbetheresultofevaluatingEqualityExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingRelationalExpression.
4.Letrvalbe?GetValue(rref).
5.LetrbetheresultofperformingStrictEqualityComparisonrval===lval.
6.Ifristrue,returnfalse.Otherwise,returntrue.

NOTE1 Giventheabovedeinitionofequality:

Stringcomparisoncanbeforcedby:""+a==""+b.
Numericcomparisoncanbeforcedby:+a==+b.
Booleancomparisoncanbeforcedby:!a==!b.

NOTE2 Theequalityoperatorsmaintainthefollowinginvariants:

A!=Bisequivalentto!(A==B).
A==BisequivalenttoB==A,exceptintheorderofevaluationofAandB.

NOTE3 Theequalityoperatorisnotalwaystransitive.Forexample,theremightbetwodistinctStringobjects,each
representingthesameStringvalue;eachStringobjectwouldbeconsideredequaltotheStringvaluebythe==
operator,butthetwoStringobjectswouldnotbeequaltoeachother.Forexample:

newString("a")=="a"and"a"==newString("a")arebothtrue.
newString("a")==newString("a")isfalse.

NOTE4 ComparisonofStringsusesasimpleequalitytestonsequencesofcodeunitvalues.Thereisnoattempttouse
themorecomplex,semanticallyorienteddeinitionsofcharacterorstringequalityandcollatingorderdeined
intheUnicodespeciication.ThereforeStringsvaluesthatarecanonicallyequalaccordingtotheUnicode
standardcouldtestasunequal.IneffectthisalgorithmassumesthatbothStringsarealreadyinnormalized
form.

12.12 BinaryBitwiseOperators
Syntax

BitwiseANDExpression[In,Yield] :
EqualityExpression[?In,?Yield]
BitwiseANDExpression[?In,?Yield] & EqualityExpression[?In,?Yield]

BitwiseXORExpression[In,Yield] :
BitwiseANDExpression[?In,?Yield]
BitwiseXORExpression[?In,?Yield] ^ BitwiseANDExpression[?In,?Yield]

BitwiseORExpression[In,Yield] :
BitwiseXORExpression[?In,?Yield]
BitwiseORExpression[?In,?Yield] | BitwiseXORExpression[?In,?Yield]

12.12.1 StaticSemantics:IsFunctionDeinition
BitwiseANDExpression : BitwiseANDExpression & EqualityExpression
BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression

1.Returnfalse.

12.12.2 StaticSemantics:IsValidSimpleAssignmentTarget
BitwiseANDExpression : BitwiseANDExpression & EqualityExpression
BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression

1.Returnfalse.

12.12.3 RuntimeSemantics:Evaluation

TheproductionA : A @ B ,where@isoneofthebitwiseoperatorsintheproductionsabove,isevaluatedasfollows:

1.LetlrefbetheresultofevaluatingA.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingB.
4.Letrvalbe?GetValue(rref).
5.Letlnumbe?ToInt32(lval).
6.Letrnumbe?ToInt32(rval).
7.Returntheresultofapplyingthebitwiseoperator@tolnumandrnum.Theresultisasigned32bitinteger.

12.13 BinaryLogicalOperators
Syntax

LogicalANDExpression[In,Yield] :
BitwiseORExpression[?In,?Yield]
LogicalANDExpression[?In,?Yield] && BitwiseORExpression[?In,?Yield]

LogicalORExpression[In,Yield] :
LogicalANDExpression[?In,?Yield]
LogicalORExpression[?In,?Yield] || LogicalANDExpression[?In,?Yield]

NOTE Thevalueproducedbya&&or||operatorisnotnecessarilyoftypeBoolean.Thevalueproducedwillalways
bethevalueofoneofthetwooperandexpressions.

12.13.1 StaticSemantics:IsFunctionDeinition
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
LogicalORExpression : LogicalORExpression || LogicalANDExpression

1.Returnfalse.

12.13.2 StaticSemantics:IsValidSimpleAssignmentTarget
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
LogicalORExpression : LogicalORExpression || LogicalANDExpression

1.Returnfalse.

12.13.3 RuntimeSemantics:Evaluation
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression

1.LetlrefbetheresultofevaluatingLogicalANDExpression.
2.Letlvalbe?GetValue(lref).
3.LetlboolbeToBoolean(lval).
4.Iflboolisfalse,returnlval.
5.LetrrefbetheresultofevaluatingBitwiseORExpression.
6.Return?GetValue(rref).
LogicalORExpression : LogicalORExpression || LogicalANDExpression

1.LetlrefbetheresultofevaluatingLogicalORExpression.
2.Letlvalbe?GetValue(lref).
3.LetlboolbeToBoolean(lval).
4.Iflboolistrue,returnlval.
5.LetrrefbetheresultofevaluatingLogicalANDExpression.
6.Return?GetValue(rref).

12.14 ConditionalOperator(?:)
Syntax

ConditionalExpression[In,Yield] :
LogicalORExpression[?In,?Yield]
LogicalORExpression[?In,?Yield] ? AssignmentExpression[In,?Yield] : AssignmentExpression[?In,?Yield]

NOTE ThegrammarforaConditionalExpressioninECMAScriptisslightlydifferentfromthatinCandJava,whicheach
allowthesecondsubexpressiontobeanExpressionbutrestrictthethirdexpressiontobea
ConditionalExpression.ThemotivationforthisdifferenceinECMAScriptistoallowanassignmentexpressionto
begovernedbyeitherarmofaconditionalandtoeliminatetheconfusingandfairlyuselesscaseofacomma
expressionasthecentreexpression.

12.14.1 StaticSemantics:IsFunctionDeinition
ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression

1.Returnfalse.

12.14.2 StaticSemantics:IsValidSimpleAssignmentTarget
ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression

1.Returnfalse.

12.14.3 RuntimeSemantics:Evaluation
ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression

1.LetlrefbetheresultofevaluatingLogicalORExpression.
2.LetlvalbeToBoolean(?GetValue(lref)).
3.Iflvalistrue,then
a.LettrueRefbetheresultofevaluatingtheirstAssignmentExpression.
b.Return?GetValue(trueRef).
4.Else,
a.LetfalseRefbetheresultofevaluatingthesecondAssignmentExpression.
b.Return?GetValue(falseRef).

12.15 AssignmentOperators
Syntax

AssignmentExpression[In,Yield] :
ConditionalExpression[?In,?Yield]
[+Yield] YieldExpression[?In]
ArrowFunction[?In,?Yield]
LeftHandSideExpression[?Yield] = AssignmentExpression[?In,?Yield]
LeftHandSideExpression[?Yield] AssignmentOperator AssignmentExpression[?In,?Yield]

AssignmentOperator : oneof
*= /= %= += = <<= >>= >>>= &= ^= |= **=

12.15.1 StaticSemantics:EarlyErrors
AssignmentExpression : LeftHandSideExpression = AssignmentExpression

ItisaSyntaxErrorifLeftHandSideExpressioniseitheranObjectLiteraloranArrayLiteralandthelexicaltokensequence
matchedbyLeftHandSideExpressioncannotbeparsedwithnotokensleftoverusingAssignmentPatternasthegoal
symbol.
ItisanearlyReferenceErrorifLeftHandSideExpressionisneitheranObjectLiteralnoranArrayLiteraland
IsValidSimpleAssignmentTargetofLeftHandSideExpressionisfalse.

AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression

ItisanearlyReferenceErrorifIsValidSimpleAssignmentTargetofLeftHandSideExpressionisfalse.

12.15.2 StaticSemantics:IsFunctionDeinition
AssignmentExpression : ArrowFunction

1.Returntrue.

AssignmentExpression :
YieldExpression
LeftHandSideExpression = AssignmentExpression
LeftHandSideExpression AssignmentOperator AssignmentExpression

1.Returnfalse.

12.15.3 StaticSemantics:IsValidSimpleAssignmentTarget

AssignmentExpression :
YieldExpression
ArrowFunction
LeftHandSideExpression = AssignmentExpression
LeftHandSideExpression AssignmentOperator AssignmentExpression

1.Returnfalse.

12.15.4 RuntimeSemantics:Evaluation
AssignmentExpression : LeftHandSideExpression = AssignmentExpression

1.IfLeftHandSideExpressionisneitheranObjectLiteralnoranArrayLiteral,then
a.LetlrefbetheresultofevaluatingLeftHandSideExpression.
b.ReturnIfAbrupt(lref).
c.LetrrefbetheresultofevaluatingAssignmentExpression.
d.Letrvalbe?GetValue(rref).
e.IfIsAnonymousFunctionDeinition(AssignmentExpression)andIsIdentiierRefofLeftHandSideExpressionareboth
true,then
i.LethasNamePropertybe?HasOwnProperty(rval,"name").
ii.IfhasNamePropertyisfalse,performSetFunctionName(rval,GetReferencedName(lref)).
f.Perform?PutValue(lref,rval).
g.Returnrval.
2.LetassignmentPatternbetheparseofthesourcetextcorrespondingtoLeftHandSideExpressionusing
AssignmentPattern[?Yield] asthegoalsymbol.
3.LetrrefbetheresultofevaluatingAssignmentExpression.
4.Letrvalbe?GetValue(rref).
5.LetstatusbetheresultofperformingDestructuringAssignmentEvaluationofassignmentPatternusingrvalasthe
argument.
6.ReturnIfAbrupt(status).
7.Returnrval.

AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression

1.LetlrefbetheresultofevaluatingLeftHandSideExpression.
2.Letlvalbe?GetValue(lref).
3.LetrrefbetheresultofevaluatingAssignmentExpression.
4.Letrvalbe?GetValue(rref).
5.Letopbethe@whereAssignmentOperatoris@=.
6.Letrbetheresultofapplyingoptolvalandrvalasifevaluatingtheexpressionlvaloprval.
7.Perform?PutValue(lref,r).
8.Returnr.

NOTE Whenanassignmentoccurswithinstrictmodecode,itisanruntimeerroriflrefinstep1.foftheirst
algorithmorstep7ofthesecondalgorithmitisanunresolvablereference.Ifitis,aReferenceErrorexception
isthrown.TheLeftHandSideExpressionalsomaynotbeareferencetoadatapropertywiththeattributevalue
{[[Writable]]:false},toanaccessorpropertywiththeattributevalue{[[Set]]:undeined},nortoanon
existentpropertyofanobjectforwhichtheIsExtensiblepredicatereturnsthevaluefalse.Inthesecasesa
TypeErrorexceptionisthrown.

12.15.5 DestructuringAssignment

SupplementalSyntax

IncertaincircumstanceswhenprocessingtheproductionAssignmentExpression : LeftHandSideExpression =
AssignmentExpression thefollowinggrammarisusedtoreinetheinterpretationofLeftHandSideExpression.

AssignmentPattern[Yield] :
ObjectAssignmentPattern[?Yield]
ArrayAssignmentPattern[?Yield]

ObjectAssignmentPattern[Yield] :
{ }
{ AssignmentPropertyList[?Yield] }
{ AssignmentPropertyList[?Yield] , }

ArrayAssignmentPattern[Yield] :
[ Elisionopt AssignmentRestElement[?Yield] opt ]
[ AssignmentElementList[?Yield] ]
[ AssignmentElementList[?Yield] , Elisionopt AssignmentRestElement[?Yield] opt ]

AssignmentPropertyList[Yield] :
AssignmentProperty[?Yield]
AssignmentPropertyList[?Yield] , AssignmentProperty[?Yield]

AssignmentElementList[Yield] :
AssignmentElisionElement[?Yield]
AssignmentElementList[?Yield] , AssignmentElisionElement[?Yield]
AssignmentElisionElement[Yield] :
Elisionopt AssignmentElement[?Yield]

AssignmentProperty[Yield] :
IdentiierReference[?Yield] Initializer[In,?Yield] opt
PropertyName[?Yield] : AssignmentElement[?Yield]

AssignmentElement[Yield] :
DestructuringAssignmentTarget[?Yield] Initializer[In,?Yield] opt

AssignmentRestElement[Yield] :
... DestructuringAssignmentTarget[?Yield]

DestructuringAssignmentTarget[Yield] :
LeftHandSideExpression[?Yield]

12.15.5.1 StaticSemantics:EarlyErrors

AssignmentProperty : IdentiierReference Initializer

ItisaSyntaxErrorifIsValidSimpleAssignmentTargetofIdentiierReferenceisfalse.

DestructuringAssignmentTarget : LeftHandSideExpression

ItisaSyntaxErrorifLeftHandSideExpressioniseitheranObjectLiteraloranArrayLiteralandifthelexicaltoken
sequencematchedbyLeftHandSideExpressioncannotbeparsedwithnotokensleftoverusingAssignmentPatternasthe
goalsymbol.
ItisaSyntaxErrorifLeftHandSideExpressionisneitheranObjectLiteralnoranArrayLiteraland
IsValidSimpleAssignmentTarget(LeftHandSideExpression)isfalse.

12.15.5.2 RuntimeSemantics:DestructuringAssignmentEvaluation

withparametervalue

ObjectAssignmentPattern : { }

1.Perform?RequireObjectCoercible(value).
2.ReturnNormalCompletion(empty).

ObjectAssignmentPattern :
{ AssignmentPropertyList }
{ AssignmentPropertyList , }

1.Perform?RequireObjectCoercible(value).
2.ReturntheresultofperformingDestructuringAssignmentEvaluationforAssignmentPropertyListusingvalueasthe
argument.

ArrayAssignmentPattern : [ ]

1.Letiteratorbe?GetIterator(value).
2.Return?IteratorClose(iterator,NormalCompletion(empty)).

ArrayAssignmentPattern : [ Elision ]

1.Letiteratorbe?GetIterator(value).
2.LetiteratorRecordbeRecord{[[Iterator]]:iterator,[[Done]]:false}.
3.LetresultbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordasthe
argument.
4.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,result).
5.Returnresult.

ArrayAssignmentPattern : [ Elision AssignmentRestElement ]

1.Letiteratorbe?GetIterator(value).
2.LetiteratorRecordbeRecord{[[Iterator]]:iterator,[[Done]]:false}.
3.IfElisionispresent,then
a.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordas
theargument.
b.Ifstatusisanabruptcompletion,then
i.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,status).
ii.ReturnCompletion(status).
4.LetresultbetheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentRestElementwith
iteratorRecordastheargument.
5.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,result).
6.Returnresult.

ArrayAssignmentPattern : [ AssignmentElementList ]

1.Letiteratorbe?GetIterator(value).
2.LetiteratorRecordbeRecord{[[Iterator]]:iterator,[[Done]]:false}.
3.LetresultbetheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentElementListusing
iteratorRecordastheargument.
4.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,result).
5.Returnresult.

ArrayAssignmentPattern : [ AssignmentElementList , Elision AssignmentRestElement ]

1.Letiteratorbe?GetIterator(value).
2.LetiteratorRecordbeRecord{[[Iterator]]:iterator,[[Done]]:false}.
3.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentElementListusing
iteratorRecordastheargument.
4.Ifstatusisanabruptcompletion,then
a.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,status).
b.ReturnCompletion(status).
5.IfElisionispresent,then
a.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordas
theargument.
b.Ifstatusisanabruptcompletion,then
i.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,status).
ii.ReturnCompletion(status).
6.IfAssignmentRestElementispresent,then
a.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentRestElementwith
iteratorRecordastheargument.
7.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,status).
8.ReturnCompletion(status).

AssignmentPropertyList : AssignmentPropertyList , AssignmentProperty

1.LetstatusbetheresultofperformingDestructuringAssignmentEvaluationforAssignmentPropertyListusingvalueasthe
argument.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingDestructuringAssignmentEvaluationforAssignmentPropertyusingvalueasthe
argument.

AssignmentProperty : IdentiierReference Initializer


1.LetPbeStringValueofIdentiierReference.
2.Letlrefbe?ResolveBinding(P).
3.Letvbe?GetV(value,P).
4.IfInitializeropt ispresentandvisundeined,then
a.LetdefaultValuebetheresultofevaluatingInitializer.
b.Letvbe?GetValue(defaultValue).
c.IfIsAnonymousFunctionDeinition(Initializer)istrue,then
i.LethasNamePropertybe?HasOwnProperty(v,"name").
ii.IfhasNamePropertyisfalse,performSetFunctionName(v,P).
5.Return?PutValue(lref,v).

AssignmentProperty : PropertyName : AssignmentElement

1.LetnamebetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(name).
3.ReturntheresultofperformingKeyedDestructuringAssignmentEvaluationofAssignmentElementwithvalueandname
asthearguments.

12.15.5.3 RuntimeSemantics:IteratorDestructuringAssignmentEvaluation

withparametersiteratorRecord

AssignmentElementList : AssignmentElisionElement

1.ReturntheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentElisionElementusing
iteratorRecordastheargument.

AssignmentElementList : AssignmentElementList , AssignmentElisionElement

1.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentElementListusing
iteratorRecordastheargument.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentElisionElementusing
iteratorRecordastheargument.

AssignmentElisionElement : AssignmentElement

1.ReturntheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentElementwithiteratorRecord
astheargument.

AssignmentElisionElement : Elision AssignmentElement

1.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordasthe
argument.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingIteratorDestructuringAssignmentEvaluationofAssignmentElementwithiteratorRecord
astheargument.

Elision : ,

1.IfiteratorRecord.[[Done]]isfalse,then
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
2.ReturnNormalCompletion(empty).

Elision : Elision ,
1.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordasthe
argument.
2.ReturnIfAbrupt(status).
3.IfiteratorRecord.[[Done]]isfalse,then
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
4.ReturnNormalCompletion(empty).

AssignmentElement : DestructuringAssignmentTarget Initializer

1.IfDestructuringAssignmentTargetisneitheranObjectLiteralnoranArrayLiteral,then
a.LetlrefbetheresultofevaluatingDestructuringAssignmentTarget.
b.ReturnIfAbrupt(lref).
2.IfiteratorRecord.[[Done]]isfalse,then
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
e.Else,
i.LetvaluebeIteratorValue(next).
ii.Ifvalueisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
iii.ReturnIfAbrupt(value).
3.IfiteratorRecord.[[Done]]istrue,letvaluebeundeined.
4.IfInitializerispresentandvalueisundeined,then
a.LetdefaultValuebetheresultofevaluatingInitializer.
b.Letvbe?GetValue(defaultValue).
5.Else,letvbevalue.
6.IfDestructuringAssignmentTargetisanObjectLiteraloranArrayLiteral,then
a.LetnestedAssignmentPatternbetheparseofthesourcetextcorrespondingtoDestructuringAssignmentTarget
usingeitherAssignmentPatternorAssignmentPattern[Yield] asthegoalsymboldependinguponwhetherthis
AssignmentElementhasthe[Yield]parameter.
b.ReturntheresultofperformingDestructuringAssignmentEvaluationofnestedAssignmentPatternwithvasthe
argument.
7.IfInitializerispresentandvalueisundeinedandIsAnonymousFunctionDeinition(Initializer)andIsIdentiierRefof
DestructuringAssignmentTargetarebothtrue,then
a.LethasNamePropertybe?HasOwnProperty(v,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(v,GetReferencedName(lref)).
8.Return?PutValue(lref,v).

NOTE LefttorightevaluationorderismaintainedbyevaluatingaDestructuringAssignmentTargetthatisnota
destructuringpatternpriortoaccessingtheiteratororevaluatingtheInitializer.

AssignmentRestElement : ... DestructuringAssignmentTarget

1.IfDestructuringAssignmentTargetisneitheranObjectLiteralnoranArrayLiteral,then
a.LetlrefbetheresultofevaluatingDestructuringAssignmentTarget.
b.ReturnIfAbrupt(lref).
2.LetAbeArrayCreate(0).
3.Letnbe0.
4.RepeatwhileiteratorRecord.[[Done]]isfalse,
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
e.Else,
i.LetnextValuebeIteratorValue(next).
ii.IfnextValueisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
iii.ReturnIfAbrupt(nextValue).
iv.LetstatusbeCreateDataProperty(A,!ToString(n),nextValue).
v.Assert:statusistrue.
vi.Incrementnby1.
5.IfDestructuringAssignmentTargetisneitheranObjectLiteralnoranArrayLiteral,then
a.Return?PutValue(lref,A).
6.LetnestedAssignmentPatternbetheparseofthesourcetextcorrespondingtoDestructuringAssignmentTargetusing
eitherAssignmentPatternorAssignmentPattern[Yield] asthegoalsymboldependinguponwhetherthis
AssignmentElementhasthe[Yield]parameter.
7.ReturntheresultofperformingDestructuringAssignmentEvaluationofnestedAssignmentPatternwithAasthe
argument.

12.15.5.4 RuntimeSemantics:KeyedDestructuringAssignmentEvaluation

withparametersvalueandpropertyName

AssignmentElement : DestructuringAssignmentTarget Initializer

1.IfDestructuringAssignmentTargetisneitheranObjectLiteralnoranArrayLiteral,then
a.LetlrefbetheresultofevaluatingDestructuringAssignmentTarget.
b.ReturnIfAbrupt(lref).
2.Letvbe?GetV(value,propertyName).
3.IfInitializerispresentandvisundeined,then
a.LetdefaultValuebetheresultofevaluatingInitializer.
b.LetrhsValuebe?GetValue(defaultValue).
4.Else,letrhsValuebev.
5.IfDestructuringAssignmentTargetisanObjectLiteraloranArrayLiteral,then
a.LetassignmentPatternbetheparseofthesourcetextcorrespondingtoDestructuringAssignmentTargetusing
eitherAssignmentPatternorAssignmentPattern[Yield] asthegoalsymboldependinguponwhetherthis
AssignmentElementhasthe[Yield]parameter.
b.ReturntheresultofperformingDestructuringAssignmentEvaluationofassignmentPatternwithrhsValueasthe
argument.
6.IfInitializerispresentandvisundeinedandIsAnonymousFunctionDeinition(Initializer)andIsIdentiierRefof
DestructuringAssignmentTargetarebothtrue,then
a.LethasNamePropertybe?HasOwnProperty(rhsValue,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(rhsValue,GetReferencedName(lref)).
7.Return?PutValue(lref,rhsValue).

12.16 CommaOperator(,)
Syntax

Expression[In,Yield] :
AssignmentExpression[?In,?Yield]
Expression[?In,?Yield] , AssignmentExpression[?In,?Yield]

12.16.1 StaticSemantics:IsFunctionDeinition
Expression : Expression , AssignmentExpression

1.Returnfalse.
12.16.2 StaticSemantics:IsValidSimpleAssignmentTarget
Expression : Expression , AssignmentExpression

1.Returnfalse.

12.16.3 RuntimeSemantics:Evaluation
Expression : Expression , AssignmentExpression

1.LetlrefbetheresultofevaluatingExpression.
2.Perform?GetValue(lref).
3.LetrrefbetheresultofevaluatingAssignmentExpression.
4.Return?GetValue(rref).

NOTE GetValuemustbecalledeventhoughitsvalueisnotusedbecauseitmayhaveobservablesideeffects.

13 ECMAScriptLanguage:StatementsandDeclarations
Syntax
Statement[Yield,Return] :
BlockStatement[?Yield,?Return]
VariableStatement[?Yield]
EmptyStatement
ExpressionStatement[?Yield]
IfStatement[?Yield,?Return]
BreakableStatement[?Yield,?Return]
ContinueStatement[?Yield]
BreakStatement[?Yield]
[+Return] ReturnStatement[?Yield]
WithStatement[?Yield,?Return]
LabelledStatement[?Yield,?Return]
ThrowStatement[?Yield]
TryStatement[?Yield,?Return]
DebuggerStatement

Declaration[Yield] :
HoistableDeclaration[?Yield]
ClassDeclaration[?Yield]
LexicalDeclaration[In,?Yield]

HoistableDeclaration[Yield,Default] :
FunctionDeclaration[?Yield,?Default]
GeneratorDeclaration[?Yield,?Default]

BreakableStatement[Yield,Return] :
IterationStatement[?Yield,?Return]
SwitchStatement[?Yield,?Return]

13.1 StatementSemantics
13.1.1 StaticSemantics:ContainsDuplicateLabels
WithargumentlabelSet.

Statement :
VariableStatement
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement

1.Returnfalse.

13.1.2 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

Statement :
VariableStatement
EmptyStatement
ExpressionStatement
ContinueStatement
ReturnStatement
ThrowStatement
DebuggerStatement

1.Returnfalse.

13.1.3 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

Statement :
VariableStatement
EmptyStatement
ExpressionStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement

1.Returnfalse.

BreakableStatement : IterationStatement

1.LetnewIterationSetbeacopyofiterationSetwithalltheelementsoflabelSetappended.
2.ReturnContainsUndeinedContinueTargetofIterationStatementwithargumentsnewIterationSetand.

13.1.4 StaticSemantics:DeclarationPart
HoistableDeclaration : FunctionDeclaration

1.ReturnFunctionDeclaration.

HoistableDeclaration : GeneratorDeclaration

1.ReturnGeneratorDeclaration.
Declaration : ClassDeclaration

1.ReturnClassDeclaration.

Declaration : LexicalDeclaration

1.ReturnLexicalDeclaration.

13.1.5 StaticSemantics:VarDeclaredNames

Statement :
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement

1.ReturnanewemptyList.

13.1.6 StaticSemantics:VarScopedDeclarations

Statement :
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement

1.ReturnanewemptyList.

13.1.7 RuntimeSemantics:LabelledEvaluation

WithargumentlabelSet.

BreakableStatement : IterationStatement

1.LetstmtResultbetheresultofperformingLabelledEvaluationofIterationStatementwithargumentlabelSet.
2.IfstmtResult.[[Type]]isbreak,then
a.IfstmtResult.[[Target]]isempty,then
i.IfstmtResult.[[Value]]isempty,letstmtResultbeNormalCompletion(undeined).
ii.Else,letstmtResultbeNormalCompletion(stmtResult.[[Value]]).
3.ReturnCompletion(stmtResult).

BreakableStatement : SwitchStatement

1.LetstmtResultbetheresultofevaluatingSwitchStatement.
2.IfstmtResult.[[Type]]isbreak,then
a.IfstmtResult.[[Target]]isempty,then
i.IfstmtResult.[[Value]]isempty,letstmtResultbeNormalCompletion(undeined).
ii.Else,letstmtResultbeNormalCompletion(stmtResult.[[Value]]).
3.ReturnCompletion(stmtResult).

NOTE ABreakableStatementisonethatcanbeexitedviaanunlabelledBreakStatement.
13.1.8 RuntimeSemantics:Evaluation

HoistableDeclaration :
GeneratorDeclaration

1.ReturnNormalCompletion(empty).

HoistableDeclaration :
FunctionDeclaration

1.ReturntheresultofevaluatingFunctionDeclaration.

BreakableStatement :
IterationStatement
SwitchStatement

1.LetnewLabelSetbeanewemptyList.
2.ReturntheresultofperformingLabelledEvaluationofthisBreakableStatementwithargumentnewLabelSet.

13.2 Block
Syntax

BlockStatement[Yield,Return] :
Block[?Yield,?Return]

Block[Yield,Return] :
{ StatementList[?Yield,?Return] opt }

StatementList[Yield,Return] :
StatementListItem[?Yield,?Return]
StatementList[?Yield,?Return] StatementListItem[?Yield,?Return]

StatementListItem[Yield,Return] :
Statement[?Yield,?Return]
Declaration[?Yield]

13.2.1 StaticSemantics:EarlyErrors
Block : { StatementList }

ItisaSyntaxErroriftheLexicallyDeclaredNamesofStatementListcontainsanyduplicateentries.
ItisaSyntaxErrorifanyelementoftheLexicallyDeclaredNamesofStatementListalsooccursintheVarDeclaredNames
ofStatementList.

13.2.2 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

Block : { }

1.Returnfalse.

StatementList : StatementList StatementListItem

1.LethasDuplicatesbeContainsDuplicateLabelsofStatementListwithargumentlabelSet.
2.IfhasDuplicatesistrue,returntrue.
3.ReturnContainsDuplicateLabelsofStatementListItemwithargumentlabelSet.
StatementListItem : Declaration

1.Returnfalse.

13.2.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

Block : { }

1.Returnfalse.

StatementList : StatementList StatementListItem

1.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofStatementListwithargumentlabelSet.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedBreakTargetofStatementListItemwithargumentlabelSet.

StatementListItem : Declaration

1.Returnfalse.

13.2.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

Block : { }

1.Returnfalse.

StatementList : StatementList StatementListItem

1.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofStatementListwithargumentsiterationSetand.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedContinueTargetofStatementListItemwithargumentsiterationSetand.

StatementListItem : Declaration

1.Returnfalse.

13.2.5 StaticSemantics:LexicallyDeclaredNames
Block : { }

1.ReturnanewemptyList.

StatementList : StatementList StatementListItem

1.LetnamesbeLexicallyDeclaredNamesofStatementList.
2.AppendtonamestheelementsoftheLexicallyDeclaredNamesofStatementListItem.
3.Returnnames.

StatementListItem : Statement

1.IfStatementisStatement : LabelledStatement ,returnLexicallyDeclaredNamesofLabelledStatement.


2.ReturnanewemptyList.

StatementListItem : Declaration

1.ReturntheBoundNamesofDeclaration.

13.2.6 StaticSemantics:LexicallyScopedDeclarations
StatementList : StatementList StatementListItem

1.LetdeclarationsbeLexicallyScopedDeclarationsofStatementList.
2.AppendtodeclarationstheelementsoftheLexicallyScopedDeclarationsofStatementListItem.
3.Returndeclarations.

StatementListItem : Statement

1.IfStatementisStatement : LabelledStatement ,returnLexicallyScopedDeclarationsofLabelledStatement.


2.ReturnanewemptyList.

StatementListItem : Declaration

1.ReturnanewListcontainingDeclarationPartofDeclaration.

13.2.7 StaticSemantics:TopLevelLexicallyDeclaredNames
StatementList : StatementList StatementListItem

1.LetnamesbeTopLevelLexicallyDeclaredNamesofStatementList.
2.AppendtonamestheelementsoftheTopLevelLexicallyDeclaredNamesofStatementListItem.
3.Returnnames.

StatementListItem : Statement

1.ReturnanewemptyList.

StatementListItem : Declaration

1.IfDeclarationisDeclaration : HoistableDeclaration ,then


a.Return.
2.ReturntheBoundNamesofDeclaration.

NOTE Atthetoplevelofafunction,orscript,functiondeclarationsaretreatedlikevardeclarationsratherthanlike
lexicaldeclarations.

13.2.8 StaticSemantics:TopLevelLexicallyScopedDeclarations
Block : { }

1.ReturnanewemptyList.

StatementList : StatementList StatementListItem

1.LetdeclarationsbeTopLevelLexicallyScopedDeclarationsofStatementList.
2.AppendtodeclarationstheelementsoftheTopLevelLexicallyScopedDeclarationsofStatementListItem.
3.Returndeclarations.

StatementListItem : Statement

1.ReturnanewemptyList.

StatementListItem : Declaration

1.IfDeclarationisDeclaration : HoistableDeclaration ,then


a.Return.
2.ReturnanewListcontainingDeclaration.

13.2.9 StaticSemantics:TopLevelVarDeclaredNames
Block : { }
1.ReturnanewemptyList.

StatementList : StatementList StatementListItem

1.LetnamesbeTopLevelVarDeclaredNamesofStatementList.
2.AppendtonamestheelementsoftheTopLevelVarDeclaredNamesofStatementListItem.
3.Returnnames.

StatementListItem : Declaration

1.IfDeclarationisDeclaration : HoistableDeclaration ,then


a.ReturntheBoundNamesofHoistableDeclaration.
2.ReturnanewemptyList.

StatementListItem : Statement

1.IfStatementisStatement : LabelledStatement ,returnTopLevelVarDeclaredNamesofStatement.


2.ReturnVarDeclaredNamesofStatement.

NOTE Atthetoplevelofafunctionorscript,innerfunctiondeclarationsaretreatedlikevardeclarations.

13.2.10 StaticSemantics:TopLevelVarScopedDeclarations
Block : { }

1.ReturnanewemptyList.

StatementList : StatementList StatementListItem

1.LetdeclarationsbeTopLevelVarScopedDeclarationsofStatementList.
2.AppendtodeclarationstheelementsoftheTopLevelVarScopedDeclarationsofStatementListItem.
3.Returndeclarations.

StatementListItem : Statement

1.IfStatementisStatement : LabelledStatement ,returnTopLevelVarScopedDeclarationsofStatement.


2.ReturnVarScopedDeclarationsofStatement.

StatementListItem : Declaration

1.IfDeclarationisDeclaration : HoistableDeclaration ,then


a.LetdeclarationbeDeclarationPartofHoistableDeclaration.
b.Returndeclaration.
2.ReturnanewemptyList.

13.2.11 StaticSemantics:VarDeclaredNames
Block : { }

1.ReturnanewemptyList.

StatementList : StatementList StatementListItem

1.LetnamesbeVarDeclaredNamesofStatementList.
2.AppendtonamestheelementsoftheVarDeclaredNamesofStatementListItem.
3.Returnnames.

StatementListItem : Declaration

1.ReturnanewemptyList.
13.2.12 StaticSemantics:VarScopedDeclarations
Block : { }

1.ReturnanewemptyList.

StatementList : StatementList StatementListItem

1.LetdeclarationsbeVarScopedDeclarationsofStatementList.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofStatementListItem.
3.Returndeclarations.

StatementListItem : Declaration

1.ReturnanewemptyList.

13.2.13 RuntimeSemantics:Evaluation
Block : { }

1.ReturnNormalCompletion(empty).

Block : { StatementList }

1.LetoldEnvbetherunningexecutioncontext'sLexicalEnvironment.
2.LetblockEnvbeNewDeclarativeEnvironment(oldEnv).
3.PerformBlockDeclarationInstantiation(StatementList,blockEnv).
4.Settherunningexecutioncontext'sLexicalEnvironmenttoblockEnv.
5.LetblockValuebetheresultofevaluatingStatementList.
6.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
7.ReturnblockValue.

NOTE1 NomatterhowcontrolleavestheBlocktheLexicalEnvironmentisalwaysrestoredtoitsformerstate.

StatementList : StatementList StatementListItem

1.LetslbetheresultofevaluatingStatementList.
2.ReturnIfAbrupt(sl).
3.LetsbetheresultofevaluatingStatementListItem.
4.ReturnCompletion(UpdateEmpty(s,sl)).

NOTE2 ThevalueofaStatementLististhevalueofthelastvalueproducingitemintheStatementList.Forexample,the
followingcallstotheevalfunctionallreturnthevalue1:

eval("1;;;;;")
eval("1;{}")
eval("1;vara;")

13.2.14 RuntimeSemantics:BlockDeclarationInstantiation(code,env)

NOTE WhenaBlockorCaseBlockproductionisevaluatedanewdeclarativeEnvironmentRecordiscreatedand
bindingsforeachblockscopedvariable,constant,function,generatorfunction,orclassdeclaredintheblock
areinstantiatedintheEnvironmentRecord.

BlockDeclarationInstantiationisperformedasfollowsusingargumentscodeandenv.codeisthegrammarproduction
correspondingtothebodyoftheblock.envistheLexicalEnvironmentinwhichbindingsaretobecreated.

1.LetenvRecbeenv'sEnvironmentRecord.
2.Assert:envRecisadeclarativeEnvironmentRecord.
3.LetdeclarationsbetheLexicallyScopedDeclarationsofcode.
4.Foreachelementdindeclarationsdo
a.ForeachelementdnoftheBoundNamesofddo
i.IfIsConstantDeclarationofdistrue,then
1.Perform!envRec.CreateImmutableBinding(dn,true).
ii.Else,
1.Perform!envRec.CreateMutableBinding(dn,false).
b.IfdisaGeneratorDeclarationproductionoraFunctionDeclarationproduction,then
i.LetfnbethesoleelementoftheBoundNamesofd.
ii.LetfobetheresultofperformingInstantiateFunctionObjectfordwithargumentenv.
iii.PerformenvRec.InitializeBinding(fn,fo).

13.3 DeclarationsandtheVariableStatement
13.3.1 LetandConstDeclarations

NOTE letandconstdeclarationsdeinevariablesthatarescopedtotherunningexecutioncontext's
LexicalEnvironment.ThevariablesarecreatedwhentheircontainingLexicalEnvironmentisinstantiatedbut
maynotbeaccessedinanywayuntilthevariable'sLexicalBindingisevaluated.Avariabledeinedbya
LexicalBindingwithanInitializerisassignedthevalueofitsInitializer'sAssignmentExpressionwhenthe
LexicalBindingisevaluated,notwhenthevariableiscreated.IfaLexicalBindinginaletdeclarationdoesnot
haveanInitializerthevariableisassignedthevalueundeinedwhentheLexicalBindingisevaluated.

Syntax

LexicalDeclaration[In,Yield] :
LetOrConst BindingList[?In,?Yield] ;

LetOrConst :
let
const

BindingList[In,Yield] :
LexicalBinding[?In,?Yield]
BindingList[?In,?Yield] , LexicalBinding[?In,?Yield]

LexicalBinding[In,Yield] :
BindingIdentiier[?Yield] Initializer[?In,?Yield] opt
BindingPattern[?Yield] Initializer[?In,?Yield]

13.3.1.1 StaticSemantics:EarlyErrors

LexicalDeclaration : LetOrConst BindingList ;

ItisaSyntaxErroriftheBoundNamesofBindingListcontains"let".
ItisaSyntaxErroriftheBoundNamesofBindingListcontainsanyduplicateentries.

LexicalBinding : BindingIdentiier Initializer

ItisaSyntaxErrorifInitializerisnotpresentandIsConstantDeclarationoftheLexicalDeclarationcontainingthis
productionistrue.

13.3.1.2 StaticSemantics:BoundNames

LexicalDeclaration : LetOrConst BindingList ;

1.ReturntheBoundNamesofBindingList.

BindingList : BindingList , LexicalBinding


1.LetnamesbetheBoundNamesofBindingList.
2.AppendtonamestheelementsoftheBoundNamesofLexicalBinding.
3.Returnnames.

LexicalBinding : BindingIdentiier Initializer

1.ReturntheBoundNamesofBindingIdentiier.

LexicalBinding : BindingPattern Initializer

1.ReturntheBoundNamesofBindingPattern.

13.3.1.3 StaticSemantics:IsConstantDeclaration

LexicalDeclaration : LetOrConst BindingList ;

1.ReturnIsConstantDeclarationofLetOrConst.

LetOrConst : let

1.Returnfalse.

LetOrConst : const

1.Returntrue.

13.3.1.4 RuntimeSemantics:Evaluation

LexicalDeclaration : LetOrConst BindingList ;

1.LetnextbetheresultofevaluatingBindingList.
2.ReturnIfAbrupt(next).
3.ReturnNormalCompletion(empty).

BindingList : BindingList , LexicalBinding

1.LetnextbetheresultofevaluatingBindingList.
2.ReturnIfAbrupt(next).
3.ReturntheresultofevaluatingLexicalBinding.

LexicalBinding : BindingIdentiier

1.LetlhsbeResolveBinding(StringValueofBindingIdentiier).
2.ReturnInitializeReferencedBinding(lhs,undeined).

NOTE AstaticsemanticsruleensuresthatthisformofLexicalBindingneveroccursinaconstdeclaration.

LexicalBinding : BindingIdentiier Initializer

1.LetbindingIdbeStringValueofBindingIdentiier.
2.LetlhsbeResolveBinding(bindingId).
3.LetrhsbetheresultofevaluatingInitializer.
4.Letvaluebe?GetValue(rhs).
5.IfIsAnonymousFunctionDeinition(Initializer)istrue,then
a.LethasNamePropertybe?HasOwnProperty(value,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(value,bindingId).
6.ReturnInitializeReferencedBinding(lhs,value).

LexicalBinding : BindingPattern Initializer

1.LetrhsbetheresultofevaluatingInitializer.
2.Letvaluebe?GetValue(rhs).
3.Letenvbetherunningexecutioncontext'sLexicalEnvironment.
4.ReturntheresultofperformingBindingInitializationforBindingPatternusingvalueandenvasthearguments.

13.3.2 VariableStatement

NOTE Avarstatementdeclaresvariablesthatarescopedtotherunningexecutioncontext'sVariableEnvironment.
VarvariablesarecreatedwhentheircontainingLexicalEnvironmentisinstantiatedandareinitializedto
undeinedwhencreated.WithinthescopeofanyVariableEnvironmentacommonBindingIdentiiermay
appearinmorethanoneVariableDeclarationbutthosedeclarationscollectivedeineonlyonevariable.A
variabledeinedbyaVariableDeclarationwithanInitializerisassignedthevalueofitsInitializer's
AssignmentExpressionwhentheVariableDeclarationisexecuted,notwhenthevariableiscreated.

Syntax

VariableStatement[Yield] :
var VariableDeclarationList[In,?Yield] ;

VariableDeclarationList[In,Yield] :
VariableDeclaration[?In,?Yield]
VariableDeclarationList[?In,?Yield] , VariableDeclaration[?In,?Yield]

VariableDeclaration[In,Yield] :
BindingIdentiier[?Yield] Initializer[?In,?Yield] opt
BindingPattern[?Yield] Initializer[?In,?Yield]

13.3.2.1 StaticSemantics:BoundNames

VariableDeclarationList : VariableDeclarationList , VariableDeclaration

1.LetnamesbeBoundNamesofVariableDeclarationList.
2.AppendtonamestheelementsofBoundNamesofVariableDeclaration.
3.Returnnames.

VariableDeclaration : BindingIdentiier Initializer

1.ReturntheBoundNamesofBindingIdentiier.

VariableDeclaration : BindingPattern Initializer

1.ReturntheBoundNamesofBindingPattern.

13.3.2.2 StaticSemantics:VarDeclaredNames

VariableStatement : var VariableDeclarationList ;

1.ReturnBoundNamesofVariableDeclarationList.

13.3.2.3 StaticSemantics:VarScopedDeclarations

VariableDeclarationList : VariableDeclaration

1.ReturnanewListcontainingVariableDeclaration.

VariableDeclarationList : VariableDeclarationList , VariableDeclaration

1.LetdeclarationsbeVarScopedDeclarationsofVariableDeclarationList.
2.AppendVariableDeclarationtodeclarations.
3.Returndeclarations.
13.3.2.4 RuntimeSemantics:Evaluation

VariableStatement : var VariableDeclarationList ;

1.LetnextbetheresultofevaluatingVariableDeclarationList.
2.ReturnIfAbrupt(next).
3.ReturnNormalCompletion(empty).

VariableDeclarationList : VariableDeclarationList , VariableDeclaration

1.LetnextbetheresultofevaluatingVariableDeclarationList.
2.ReturnIfAbrupt(next).
3.ReturntheresultofevaluatingVariableDeclaration.

VariableDeclaration : BindingIdentiier

1.ReturnNormalCompletion(empty).

VariableDeclaration : BindingIdentiier Initializer

1.LetbindingIdbeStringValueofBindingIdentiier.
2.Letlhsbe?ResolveBinding(bindingId).
3.LetrhsbetheresultofevaluatingInitializer.
4.Letvaluebe?GetValue(rhs).
5.IfIsAnonymousFunctionDeinition(Initializer)istrue,then
a.LethasNamePropertybe?HasOwnProperty(value,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(value,bindingId).
6.Return?PutValue(lhs,value).

NOTE IfaVariableDeclarationisnestedwithinawithstatementandtheBindingIdentiierintheVariableDeclaration
isthesameasapropertynameofthebindingobjectofthewithstatement'sobjectEnvironmentRecord,then
step6willassignvaluetothepropertyinsteadofassigningtotheVariableEnvironmentbindingofthe
Identiier.

VariableDeclaration : BindingPattern Initializer

1.LetrhsbetheresultofevaluatingInitializer.
2.Letrvalbe?GetValue(rhs).
3.ReturntheresultofperformingBindingInitializationforBindingPatternpassingrvalandundeinedasarguments.

13.3.3 DestructuringBindingPatterns

Syntax

BindingPattern[Yield] :
ObjectBindingPattern[?Yield]
ArrayBindingPattern[?Yield]

ObjectBindingPattern[Yield] :
{ }
{ BindingPropertyList[?Yield] }
{ BindingPropertyList[?Yield] , }

ArrayBindingPattern[Yield] :
[ Elisionopt BindingRestElement[?Yield] opt ]
[ BindingElementList[?Yield] ]
[ BindingElementList[?Yield] , Elisionopt BindingRestElement[?Yield] opt ]
BindingPropertyList[Yield] :
BindingProperty[?Yield]
BindingPropertyList[?Yield] , BindingProperty[?Yield]

BindingElementList[Yield] :
BindingElisionElement[?Yield]
BindingElementList[?Yield] , BindingElisionElement[?Yield]

BindingElisionElement[Yield] :
Elisionopt BindingElement[?Yield]

BindingProperty[Yield] :
SingleNameBinding[?Yield]
PropertyName[?Yield] : BindingElement[?Yield]

BindingElement[Yield] :
SingleNameBinding[?Yield]
BindingPattern[?Yield] Initializer[In,?Yield] opt

SingleNameBinding[Yield] :
BindingIdentiier[?Yield] Initializer[In,?Yield] opt

BindingRestElement[Yield] :
... BindingIdentiier[?Yield]
... BindingPattern[?Yield]

13.3.3.1 StaticSemantics:BoundNames

ObjectBindingPattern : { }

1.ReturnanewemptyList.

ArrayBindingPattern : [ Elision ]

1.ReturnanewemptyList.

ArrayBindingPattern : [ Elision BindingRestElement ]

1.ReturntheBoundNamesofBindingRestElement.

ArrayBindingPattern : [ BindingElementList , Elision ]

1.ReturntheBoundNamesofBindingElementList.

ArrayBindingPattern : [ BindingElementList , Elision BindingRestElement ]

1.LetnamesbeBoundNamesofBindingElementList.
2.AppendtonamestheelementsofBoundNamesofBindingRestElement.
3.Returnnames.

BindingPropertyList : BindingPropertyList , BindingProperty

1.LetnamesbeBoundNamesofBindingPropertyList.
2.AppendtonamestheelementsofBoundNamesofBindingProperty.
3.Returnnames.

BindingElementList : BindingElementList , BindingElisionElement

1.LetnamesbeBoundNamesofBindingElementList.
2.AppendtonamestheelementsofBoundNamesofBindingElisionElement.
3.Returnnames.

BindingElisionElement : Elision BindingElement

1.ReturnBoundNamesofBindingElement.

BindingProperty : PropertyName : BindingElement

1.ReturntheBoundNamesofBindingElement.

SingleNameBinding : BindingIdentiier Initializer

1.ReturntheBoundNamesofBindingIdentiier.

BindingElement : BindingPattern Initializer

1.ReturntheBoundNamesofBindingPattern.

13.3.3.2 StaticSemantics:ContainsExpression

ObjectBindingPattern : { }

1.Returnfalse.

ArrayBindingPattern : [ Elision ]

1.Returnfalse.

ArrayBindingPattern : [ Elision BindingRestElement ]

1.ReturnContainsExpressionofBindingRestElement.

ArrayBindingPattern : [ BindingElementList , Elision ]

1.ReturnContainsExpressionofBindingElementList.

ArrayBindingPattern : [ BindingElementList , Elision BindingRestElement ]

1.LethasbeContainsExpressionofBindingElementList.
2.Ifhasistrue,returntrue.
3.ReturnContainsExpressionofBindingRestElement.

BindingPropertyList : BindingPropertyList , BindingProperty

1.LethasbeContainsExpressionofBindingPropertyList.
2.Ifhasistrue,returntrue.
3.ReturnContainsExpressionofBindingProperty.

BindingElementList : BindingElementList , BindingElisionElement

1.LethasbeContainsExpressionofBindingElementList.
2.Ifhasistrue,returntrue.
3.ReturnContainsExpressionofBindingElisionElement.

BindingElisionElement : Elision BindingElement

1.ReturnContainsExpressionofBindingElement.

BindingProperty : PropertyName : BindingElement

1.LethasbeIsComputedPropertyKeyofPropertyName.
2.Ifhasistrue,returntrue.
3.ReturnContainsExpressionofBindingElement.

BindingElement : BindingPattern Initializer

1.Returntrue.

SingleNameBinding : BindingIdentiier

1.Returnfalse.

SingleNameBinding : BindingIdentiier Initializer

1.Returntrue.

BindingRestElement : ... BindingIdentiier

1.Returnfalse.

BindingRestElement : ... BindingPattern

1.ReturnContainsExpressionofBindingPattern.

13.3.3.3 StaticSemantics:HasInitializer

BindingElement : BindingPattern

1.Returnfalse.

BindingElement : BindingPattern Initializer

1.Returntrue.

SingleNameBinding : BindingIdentiier

1.Returnfalse.

SingleNameBinding : BindingIdentiier Initializer

1.Returntrue.

13.3.3.4 StaticSemantics:IsSimpleParameterList

BindingElement : BindingPattern

1.Returnfalse.

BindingElement : BindingPattern Initializer

1.Returnfalse.

SingleNameBinding : BindingIdentiier

1.Returntrue.

SingleNameBinding : BindingIdentiier Initializer

1.Returnfalse.

13.3.3.5 RuntimeSemantics:BindingInitialization

Withparametersvalueandenvironment.

NOTE WhenundeinedispassedforenvironmentitindicatesthataPutValueoperationshouldbeusedtoassignthe
initializationvalue.Thisisthecaseforformalparameterlistsofnonstrictfunctions.Inthatcasetheformal
parameterbindingsarepreinitializedinordertodealwiththepossibilityofmultipleparameterswiththe
samename.

BindingPattern : ObjectBindingPattern

1.Perform?RequireObjectCoercible(value).
2.ReturntheresultofperformingBindingInitializationforObjectBindingPatternusingvalueandenvironmentas
arguments.

BindingPattern : ArrayBindingPattern

1.Letiteratorbe?GetIterator(value).
2.LetiteratorRecordbeRecord{[[Iterator]]:iterator,[[Done]]:false}.
3.LetresultbeIteratorBindingInitializationforArrayBindingPatternusingiteratorRecordandenvironmentasarguments.
4.IfiteratorRecord.[[Done]]isfalse,return?IteratorClose(iterator,result).
5.Returnresult.

ObjectBindingPattern : { }

1.ReturnNormalCompletion(empty).

BindingPropertyList : BindingPropertyList , BindingProperty

1.LetstatusbetheresultofperformingBindingInitializationforBindingPropertyListusingvalueandenvironmentas
arguments.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingBindingInitializationforBindingPropertyusingvalueandenvironmentasarguments.

BindingProperty : SingleNameBinding

1.LetnamebethestringthatistheonlyelementofBoundNamesofSingleNameBinding.
2.ReturntheresultofperformingKeyedBindingInitializationforSingleNameBindingusingvalue,environment,andname
asthearguments.

BindingProperty : PropertyName : BindingElement

1.LetPbetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(P).
3.ReturntheresultofperformingKeyedBindingInitializationforBindingElementusingvalue,environment,andPas
arguments.

13.3.3.6 RuntimeSemantics:IteratorBindingInitialization

WithparametersiteratorRecord,andenvironment.

NOTE WhenundeinedispassedforenvironmentitindicatesthataPutValueoperationshouldbeusedtoassignthe
initializationvalue.Thisisthecaseforformalparameterlistsofnonstrictfunctions.Inthatcasetheformal
parameterbindingsarepreinitializedinordertodealwiththepossibilityofmultipleparameterswiththe
samename.

ArrayBindingPattern : [ ]

1.ReturnNormalCompletion(empty).

ArrayBindingPattern : [ Elision ]

1.ReturntheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordasthe
argument.

ArrayBindingPattern : [ Elision BindingRestElement ]


1.IfElisionispresent,then
a.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordas
theargument.
b.ReturnIfAbrupt(status).
2.ReturntheresultofperformingIteratorBindingInitializationforBindingRestElementwithiteratorRecordand
environmentasarguments.

ArrayBindingPattern : [ BindingElementList ]

1.ReturntheresultofperformingIteratorBindingInitializationforBindingElementListwithiteratorRecordand
environmentasarguments.

ArrayBindingPattern : [ BindingElementList , ]

1.ReturntheresultofperformingIteratorBindingInitializationforBindingElementListwithiteratorRecordand
environmentasarguments.

ArrayBindingPattern : [ BindingElementList , Elision ]

1.LetstatusbetheresultofperformingIteratorBindingInitializationforBindingElementListwithiteratorRecordand
environmentasarguments.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordasthe
argument.

ArrayBindingPattern : [ BindingElementList , Elision BindingRestElement ]

1.LetstatusbetheresultofperformingIteratorBindingInitializationforBindingElementListwithiteratorRecordand
environmentasarguments.
2.ReturnIfAbrupt(status).
3.IfElisionispresent,then
a.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordas
theargument.
b.ReturnIfAbrupt(status).
4.ReturntheresultofperformingIteratorBindingInitializationforBindingRestElementwithiteratorRecordand
environmentasarguments.

BindingElementList : BindingElisionElement

1.ReturntheresultofperformingIteratorBindingInitializationforBindingElisionElementwithiteratorRecordand
environmentasarguments.

BindingElementList : BindingElementList , BindingElisionElement

1.LetstatusbetheresultofperformingIteratorBindingInitializationforBindingElementListwithiteratorRecordand
environmentasarguments.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingIteratorBindingInitializationforBindingElisionElementusingiteratorRecordand
environmentasarguments.

BindingElisionElement : BindingElement

1.ReturntheresultofperformingIteratorBindingInitializationofBindingElementwithiteratorRecordandenvironmentas
thearguments.

BindingElisionElement : Elision BindingElement

1.LetstatusbetheresultofperformingIteratorDestructuringAssignmentEvaluationofElisionwithiteratorRecordasthe
argument.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingIteratorBindingInitializationofBindingElementwithiteratorRecordandenvironmentas
thearguments.

BindingElement : SingleNameBinding

1.ReturntheresultofperformingIteratorBindingInitializationforSingleNameBindingwithiteratorRecordand
environmentasthearguments.

SingleNameBinding : BindingIdentiier Initializer

1.LetbindingIdbeStringValueofBindingIdentiier.
2.Letlhsbe?ResolveBinding(bindingId,environment).
3.IfiteratorRecord.[[Done]]isfalse,then
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
e.Else,
i.LetvbeIteratorValue(next).
ii.Ifvisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
iii.ReturnIfAbrupt(v).
4.IfiteratorRecord.[[Done]]istrue,letvbeundeined.
5.IfInitializerispresentandvisundeined,then
a.LetdefaultValuebetheresultofevaluatingInitializer.
b.Letvbe?GetValue(defaultValue).
c.IfIsAnonymousFunctionDeinition(Initializer)istrue,then
i.LethasNamePropertybe?HasOwnProperty(v,"name").
ii.IfhasNamePropertyisfalse,performSetFunctionName(v,bindingId).
6.Ifenvironmentisundeined,return?PutValue(lhs,v).
7.ReturnInitializeReferencedBinding(lhs,v).

BindingElement : BindingPattern Initializer

1.IfiteratorRecord.[[Done]]isfalse,then
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
e.Else,
i.LetvbeIteratorValue(next).
ii.Ifvisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
iii.ReturnIfAbrupt(v).
2.IfiteratorRecord.[[Done]]istrue,letvbeundeined.
3.IfInitializerispresentandvisundeined,then
a.LetdefaultValuebetheresultofevaluatingInitializer.
b.Letvbe?GetValue(defaultValue).
4.ReturntheresultofperformingBindingInitializationofBindingPatternwithvandenvironmentasthearguments.

BindingRestElement : ... BindingIdentiier

1.Letlhsbe?ResolveBinding(StringValueofBindingIdentiier,environment).
2.LetAbeArrayCreate(0).
3.Letnbe0.
4.Repeat,
a.IfiteratorRecord.[[Done]]isfalse,then
i.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
ii.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
iii.ReturnIfAbrupt(next).
iv.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
b.IfiteratorRecord.[[Done]]istrue,then
i.Ifenvironmentisundeined,return?PutValue(lhs,A).
ii.ReturnInitializeReferencedBinding(lhs,A).
c.LetnextValuebeIteratorValue(next).
d.IfnextValueisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
e.ReturnIfAbrupt(nextValue).
f.LetstatusbeCreateDataProperty(A,!ToString(n),nextValue).
g.Assert:statusistrue.
h.Incrementnby1.

BindingRestElement : ... BindingPattern

1.LetAbeArrayCreate(0).
2.Letnbe0.
3.Repeat,
a.IfiteratorRecord.[[Done]]isfalse,then
i.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
ii.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
iii.ReturnIfAbrupt(next).
iv.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
b.IfiteratorRecord.[[Done]]istrue,then
i.ReturntheresultofperformingBindingInitializationofBindingPatternwithAandenvironmentasthe
arguments.
c.LetnextValuebeIteratorValue(next).
d.IfnextValueisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
e.ReturnIfAbrupt(nextValue).
f.LetstatusbeCreateDataProperty(A,!ToString(n),nextValue).
g.Assert:statusistrue.
h.Incrementnby1.

13.3.3.7 RuntimeSemantics:KeyedBindingInitialization

Withparametersvalue,environment,andpropertyName.

NOTE WhenundeinedispassedforenvironmentitindicatesthataPutValueoperationshouldbeusedtoassignthe
initializationvalue.Thisisthecaseforformalparameterlistsofnonstrictfunctions.Inthatcasetheformal
parameterbindingsarepreinitializedinordertodealwiththepossibilityofmultipleparameterswiththe
samename.

BindingElement : BindingPattern Initializer

1.Letvbe?GetV(value,propertyName).
2.IfInitializerispresentandvisundeined,then
a.LetdefaultValuebetheresultofevaluatingInitializer.
b.Letvbe?GetValue(defaultValue).
3.ReturntheresultofperformingBindingInitializationforBindingPatternpassingvandenvironmentasarguments.

SingleNameBinding : BindingIdentiier Initializer

1.LetbindingIdbeStringValueofBindingIdentiier.
2.Letlhsbe?ResolveBinding(bindingId,environment).
3.Letvbe?GetV(value,propertyName).
4.IfInitializerispresentandvisundeined,then
a.LetdefaultValuebetheresultofevaluatingInitializer.
b.Letvbe?GetValue(defaultValue).
c.IfIsAnonymousFunctionDeinition(Initializer)istrue,then
i.LethasNamePropertybe?HasOwnProperty(v,"name").
ii.IfhasNamePropertyisfalse,performSetFunctionName(v,bindingId).
5.Ifenvironmentisundeined,return?PutValue(lhs,v).
6.ReturnInitializeReferencedBinding(lhs,v).

13.4 EmptyStatement
Syntax

EmptyStatement :
;

13.4.1 RuntimeSemantics:Evaluation
EmptyStatement : ;

1.ReturnNormalCompletion(empty).

13.5 ExpressionStatement
Syntax

ExpressionStatement[Yield] :
[lookahead{{ ,function ,class ,let[}] Expression[In,?Yield] ;

NOTE AnExpressionStatementcannotstartwithaU+007B(LEFTCURLYBRACKET)becausethatmightmakeit
ambiguouswithaBlock.Also,anExpressionStatementcannotstartwiththefunctionorclasskeywords
becausethatwouldmakeitambiguouswithaFunctionDeclaration,aGeneratorDeclaration,ora
ClassDeclaration.AnExpressionStatementcannotstartwiththetwotokensequencelet[becausethatwould
makeitambiguouswithaletLexicalDeclarationwhoseirstLexicalBindingwasanArrayBindingPattern.

13.5.1 RuntimeSemantics:Evaluation
ExpressionStatement : Expression ;

1.LetexprRefbetheresultofevaluatingExpression.
2.Return?GetValue(exprRef).

13.6 TheifStatement
Syntax

IfStatement[Yield,Return] :
if ( Expression[In,?Yield] ) Statement[?Yield,?Return] else Statement[?Yield,?Return]
if ( Expression[In,?Yield] ) Statement[?Yield,?Return]

Eachelseforwhichthechoiceofassociatedifisambiguousshallbeassociatedwiththenearestpossibleifthatwould
otherwisehavenocorrespondingelse.

13.6.1 StaticSemantics:EarlyErrors

IfStatement :
if ( Expression ) Statement else Statement
if ( Expression ) Statement

ItisaSyntaxErrorifIsLabelledFunction(Statement)istrue.

NOTE ItisonlynecessarytoapplythisruleiftheextensionspeciiedinB.3.2isimplemented.

13.6.2 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

IfStatement : if ( Expression ) Statement else Statement

1.LethasDuplicatebeContainsDuplicateLabelsoftheirstStatementwithargumentlabelSet.
2.IfhasDuplicateistrue,returntrue.
3.ReturnContainsDuplicateLabelsofthesecondStatementwithargumentlabelSet.

IfStatement : if ( Expression ) Statement

1.ReturnContainsDuplicateLabelsofStatementwithargumentlabelSet.

13.6.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

IfStatement : if ( Expression ) Statement else Statement

1.LethasUndeinedLabelsbeContainsUndeinedBreakTargetoftheirstStatementwithargumentlabelSet.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedBreakTargetofthesecondStatementwithargumentlabelSet.

IfStatement : if ( Expression ) Statement

1.ReturnContainsUndeinedBreakTargetofStatementwithargumentlabelSet.

13.6.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

IfStatement : if ( Expression ) Statement else Statement

1.LethasUndeinedLabelsbeContainsUndeinedContinueTargetoftheirstStatementwithargumentsiterationSetand.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedContinueTargetofthesecondStatementwithargumentsiterationSetand.

IfStatement : if ( Expression ) Statement

1.ReturnContainsUndeinedContinueTargetofStatementwithargumentsiterationSetand.

13.6.5 StaticSemantics:VarDeclaredNames
IfStatement : if ( Expression ) Statement else Statement

1.LetnamesbeVarDeclaredNamesoftheirstStatement.
2.AppendtonamestheelementsoftheVarDeclaredNamesofthesecondStatement.
3.Returnnames.

IfStatement : if ( Expression ) Statement

1.ReturntheVarDeclaredNamesofStatement.

13.6.6 StaticSemantics:VarScopedDeclarations
IfStatement : if ( Expression ) Statement else Statement

1.LetdeclarationsbeVarScopedDeclarationsoftheirstStatement.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofthesecondStatement.
3.Returndeclarations.

IfStatement : if ( Expression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

13.6.7 RuntimeSemantics:Evaluation
IfStatement : if ( Expression ) Statement else Statement

1.LetexprRefbetheresultofevaluatingExpression.
2.LetexprValuebeToBoolean(?GetValue(exprRef)).
3.IfexprValueistrue,then
a.LetstmtCompletionbetheresultofevaluatingtheirstStatement.
4.Else,
a.LetstmtCompletionbetheresultofevaluatingthesecondStatement.
5.ReturnCompletion(UpdateEmpty(stmtCompletion,undeined)).

IfStatement : if ( Expression ) Statement

1.LetexprRefbetheresultofevaluatingExpression.
2.LetexprValuebeToBoolean(?GetValue(exprRef)).
3.IfexprValueisfalse,then
a.ReturnNormalCompletion(undeined).
4.Else,
a.LetstmtCompletionbetheresultofevaluatingStatement.
b.ReturnCompletion(UpdateEmpty(stmtCompletion,undeined)).

13.7 IterationStatements
Syntax

IterationStatement[Yield,Return] :
do Statement[?Yield,?Return] while ( Expression[In,?Yield] ) ;
while ( Expression[In,?Yield] ) Statement[?Yield,?Return]
for ( [lookahead{let[}] Expression[?Yield] opt ; Expression[In,?Yield] opt ;
Expression[In,?Yield] opt ) Statement[?Yield,?Return]
for ( var VariableDeclarationList[?Yield] ; Expression[In,?Yield] opt ; Expression[In,?Yield] opt )
Statement[?Yield,?Return]
for ( LexicalDeclaration[?Yield] Expression[In,?Yield] opt ; Expression[In,?Yield] opt )
Statement[?Yield,?Return]
for ( [lookahead{let[}] LeftHandSideExpression[?Yield] in Expression[In,?Yield] )
Statement[?Yield,?Return]
for ( var ForBinding[?Yield] in Expression[In,?Yield] ) Statement[?Yield,?Return]
for ( ForDeclaration[?Yield] in Expression[In,?Yield] ) Statement[?Yield,?Return]
for ( [lookaheadlet] LeftHandSideExpression[?Yield] of AssignmentExpression[In,?Yield] )
Statement[?Yield,?Return]
for ( var ForBinding[?Yield] of AssignmentExpression[In,?Yield] ) Statement[?Yield,?Return]
for ( ForDeclaration[?Yield] of AssignmentExpression[In,?Yield] ) Statement[?Yield,?Return]

ForDeclaration[Yield] :
LetOrConst ForBinding[?Yield]

ForBinding[Yield] :
BindingIdentiier[?Yield]
BindingPattern[?Yield]

13.7.1 Semantics

13.7.1.1 StaticSemantics:EarlyErrors

IterationStatement :
do Statement while ( Expression ) ;
while ( Expression ) Statement
for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
for ( LeftHandSideExpression in Expression ) Statement
for ( var ForBinding in Expression ) Statement
for ( ForDeclaration in Expression ) Statement
for ( LeftHandSideExpression of AssignmentExpression ) Statement
for ( var ForBinding of AssignmentExpression ) Statement
for ( ForDeclaration of AssignmentExpression ) Statement

ItisaSyntaxErrorifIsLabelledFunction(Statement)istrue.

NOTE ItisonlynecessarytoapplythisruleiftheextensionspeciiedinB.3.2isimplemented.

13.7.1.2 RuntimeSemantics:LoopContinues(completion,labelSet)

TheabstractoperationLoopContinueswithargumentscompletionandlabelSetisdeinedbythefollowingsteps:

1.Ifcompletion.[[Type]]isnormal,returntrue.
2.Ifcompletion.[[Type]]isnotcontinue,returnfalse.
3.Ifcompletion.[[Target]]isempty,returntrue.
4.Ifcompletion.[[Target]]isanelementoflabelSet,returntrue.
5.Returnfalse.

NOTE WithintheStatementpartofanIterationStatementaContinueStatementmaybeusedtobeginanewiteration.

13.7.2 ThedowhileStatement

13.7.2.1 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

IterationStatement : do Statement while ( Expression ) ;

1.ReturnContainsDuplicateLabelsofStatementwithargumentlabelSet.

13.7.2.2 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

IterationStatement : do Statement while ( Expression ) ;

1.ReturnContainsUndeinedBreakTargetofStatementwithargumentlabelSet.

13.7.2.3 StaticSemantics:ContainsUndeinedContinueTarget
WithargumentsiterationSetandlabelSet.

IterationStatement : do Statement while ( Expression ) ;

1.ReturnContainsUndeinedContinueTargetofStatementwithargumentsiterationSetand.

13.7.2.4 StaticSemantics:VarDeclaredNames

IterationStatement : do Statement while ( Expression ) ;

1.ReturntheVarDeclaredNamesofStatement.

13.7.2.5 StaticSemantics:VarScopedDeclarations

IterationStatement : do Statement while ( Expression ) ;

1.ReturntheVarScopedDeclarationsofStatement.

13.7.2.6 RuntimeSemantics:LabelledEvaluation

WithargumentlabelSet.

IterationStatement : do Statement while ( Expression ) ;

1.LetVbeundeined.
2.Repeat
a.LetstmtbetheresultofevaluatingStatement.
b.IfLoopContinues(stmt,labelSet)isfalse,returnCompletion(UpdateEmpty(stmt,V)).
c.Ifstmt.[[Value]]isnotempty,letVbestmt.[[Value]].
d.LetexprRefbetheresultofevaluatingExpression.
e.LetexprValuebe?GetValue(exprRef).
f.IfToBoolean(exprValue)isfalse,returnNormalCompletion(V).

13.7.3 ThewhileStatement

13.7.3.1 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

IterationStatement : while ( Expression ) Statement

1.ReturnContainsDuplicateLabelsofStatementwithargumentlabelSet.

13.7.3.2 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

IterationStatement : while ( Expression ) Statement

1.ReturnContainsUndeinedBreakTargetofStatementwithargumentlabelSet.

13.7.3.3 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

IterationStatement : while ( Expression ) Statement

1.ReturnContainsUndeinedContinueTargetofStatementwithargumentsiterationSetand.

13.7.3.4 StaticSemantics:VarDeclaredNames

IterationStatement : while ( Expression ) Statement


1.ReturntheVarDeclaredNamesofStatement.

13.7.3.5 StaticSemantics:VarScopedDeclarations

IterationStatement : while ( Expression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

13.7.3.6 RuntimeSemantics:LabelledEvaluation

WithargumentlabelSet.

IterationStatement : while ( Expression ) Statement

1.LetVbeundeined.
2.Repeat
a.LetexprRefbetheresultofevaluatingExpression.
b.LetexprValuebe?GetValue(exprRef).
c.IfToBoolean(exprValue)isfalse,returnNormalCompletion(V).
d.LetstmtbetheresultofevaluatingStatement.
e.IfLoopContinues(stmt,labelSet)isfalse,returnCompletion(UpdateEmpty(stmt,V)).
f.Ifstmt.[[Value]]isnotempty,letVbestmt.[[Value]].

13.7.4 TheforStatement

13.7.4.1 StaticSemantics:EarlyErrors

IterationStatement : for ( LexicalDeclaration Expression ; Expression ) Statement

ItisaSyntaxErrorifanyelementoftheBoundNamesofLexicalDeclarationalsooccursintheVarDeclaredNamesof
Statement.

13.7.4.2 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

IterationStatement :
for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

1.ReturnContainsDuplicateLabelsofStatementwithargumentlabelSet.

13.7.4.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

IterationStatement :
for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

1.ReturnContainsUndeinedBreakTargetofStatementwithargumentlabelSet.

13.7.4.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

IterationStatement :
for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

1.ReturnContainsUndeinedContinueTargetofStatementwithargumentsiterationSetand.

13.7.4.5 StaticSemantics:VarDeclaredNames

IterationStatement : for ( Expression ; Expression ; Expression ) Statement

1.ReturntheVarDeclaredNamesofStatement.

IterationStatement : for ( var VariableDeclarationList ; Expression ; Expression ) Statement

1.LetnamesbeBoundNamesofVariableDeclarationList.
2.AppendtonamestheelementsoftheVarDeclaredNamesofStatement.
3.Returnnames.

IterationStatement : for ( LexicalDeclaration Expression ; Expression ) Statement

1.ReturntheVarDeclaredNamesofStatement.

13.7.4.6 StaticSemantics:VarScopedDeclarations

IterationStatement : for ( Expression ; Expression ; Expression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

IterationStatement : for ( var VariableDeclarationList ; Expression ; Expression ) Statement

1.LetdeclarationsbeVarScopedDeclarationsofVariableDeclarationList.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofStatement.
3.Returndeclarations.

IterationStatement : for ( LexicalDeclaration Expression ; Expression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

13.7.4.7 RuntimeSemantics:LabelledEvaluation

WithargumentlabelSet.

IterationStatement : for ( Expression ; Expression ; Expression ) Statement

1.IftheirstExpressionispresent,then
a.LetexprRefbetheresultofevaluatingtheirstExpression.
b.Perform?GetValue(exprRef).
2.Return?ForBodyEvaluation(thesecondExpression,thethirdExpression,Statement,,labelSet).

IterationStatement : for ( var VariableDeclarationList ; Expression ; Expression ) Statement

1.LetvarDclbetheresultofevaluatingVariableDeclarationList.
2.ReturnIfAbrupt(varDcl).
3.Return?ForBodyEvaluation(theirstExpression,thesecondExpression,Statement,,labelSet).

IterationStatement : for ( LexicalDeclaration Expression ; Expression ) Statement

1.LetoldEnvbetherunningexecutioncontext'sLexicalEnvironment.
2.LetloopEnvbeNewDeclarativeEnvironment(oldEnv).
3.LetloopEnvRecbeloopEnv'sEnvironmentRecord.
4.LetisConstbetheresultofperformingIsConstantDeclarationofLexicalDeclaration.
5.LetboundNamesbetheBoundNamesofLexicalDeclaration.
6.ForeachelementdnofboundNamesdo
a.IfisConstistrue,then
i.Perform!loopEnvRec.CreateImmutableBinding(dn,true).
b.Else,
i.Perform!loopEnvRec.CreateMutableBinding(dn,false).
7.Settherunningexecutioncontext'sLexicalEnvironmenttoloopEnv.
8.LetforDclbetheresultofevaluatingLexicalDeclaration.
9.IfforDclisanabruptcompletion,then
a.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
b.ReturnCompletion(forDcl).
10.IfisConstisfalse,letperIterationLetsbeboundNames;otherwiseletperIterationLetsbe.
11.LetbodyResultbeForBodyEvaluation(theirstExpression,thesecondExpression,Statement,perIterationLets,labelSet).
12.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
13.ReturnCompletion(bodyResult).

13.7.4.8 RuntimeSemantics:ForBodyEvaluation(test,increment,stmt,perIterationBindings,labelSet)

TheabstractoperationForBodyEvaluationwithargumentstest,increment,stmt,perIterationBindings,andlabelSetis
performedasfollows:

1.LetVbeundeined.
2.Perform?CreatePerIterationEnvironment(perIterationBindings).
3.Repeat
a.Iftestisnot[empty],then
i.LettestRefbetheresultofevaluatingtest.
ii.LettestValuebe?GetValue(testRef).
iii.IfToBoolean(testValue)isfalse,returnNormalCompletion(V).
b.Letresultbetheresultofevaluatingstmt.
c.IfLoopContinues(result,labelSet)isfalse,returnCompletion(UpdateEmpty(result,V)).
d.Ifresult.[[Value]]isnotempty,letVberesult.[[Value]].
e.Perform?CreatePerIterationEnvironment(perIterationBindings).
f.Ifincrementisnot[empty],then
i.LetincRefbetheresultofevaluatingincrement.
ii.Perform?GetValue(incRef).

13.7.4.9 RuntimeSemantics:CreatePerIterationEnvironment(perIterationBindings)

TheabstractoperationCreatePerIterationEnvironmentwithargumentperIterationBindingsisperformedasfollows:

1.IfperIterationBindingshasanyelements,then
a.LetlastIterationEnvbetherunningexecutioncontext'sLexicalEnvironment.
b.LetlastIterationEnvRecbelastIterationEnv'sEnvironmentRecord.
c.LetouterbelastIterationEnv'souterenvironmentreference.
d.Assert:outerisnotnull.
e.LetthisIterationEnvbeNewDeclarativeEnvironment(outer).
f.LetthisIterationEnvRecbethisIterationEnv'sEnvironmentRecord.
g.ForeachelementbnofperIterationBindingsdo,
i.Perform!thisIterationEnvRec.CreateMutableBinding(bn,false).
ii.LetlastValuebe?lastIterationEnvRec.GetBindingValue(bn,true).
iii.PerformthisIterationEnvRec.InitializeBinding(bn,lastValue).
h.Settherunningexecutioncontext'sLexicalEnvironmenttothisIterationEnv.
2.Returnundeined.

13.7.5 TheforinandforofStatements

13.7.5.1 StaticSemantics:EarlyErrors
IterationStatement :
for ( LeftHandSideExpression in Expression ) Statement
for ( LeftHandSideExpression of AssignmentExpression ) Statement

ItisaSyntaxErrorifLeftHandSideExpressioniseitheranObjectLiteraloranArrayLiteralandifthelexicaltoken
sequencematchedbyLeftHandSideExpressioncannotbeparsedwithnotokensleftoverusingAssignmentPatternasthe
goalsymbol.

IfLeftHandSideExpressioniseitheranObjectLiteraloranArrayLiteralandifthelexicaltokensequencematchedby
LeftHandSideExpressioncanbeparsedwithnotokensleftoverusingAssignmentPatternasthegoalsymbolthenthefollowing
rulesarenotapplied.Instead,theEarlyErrorrulesforAssignmentPatternareused.

ItisaSyntaxErrorifIsValidSimpleAssignmentTargetofLeftHandSideExpressionisfalse.
ItisaSyntaxErroriftheLeftHandSideExpressionisCoverParenthesizedExpressionAndArrowParameterList : (
Expression ) andExpressionderivesaproductionthatwouldproduceaSyntaxErroraccordingtotheserulesifthat
productionissubstitutedforLeftHandSideExpression.Thisruleisrecursivelyapplied.

NOTE ThelastrulemeansthattheotherrulesareappliedevenifparenthesessurroundExpression.

IterationStatement :
for ( ForDeclaration in Expression ) Statement
for ( ForDeclaration of AssignmentExpression ) Statement

ItisaSyntaxErroriftheBoundNamesofForDeclarationcontains"let".
ItisaSyntaxErrorifanyelementoftheBoundNamesofForDeclarationalsooccursintheVarDeclaredNamesof
Statement.
ItisaSyntaxErroriftheBoundNamesofForDeclarationcontainsanyduplicateentries.

13.7.5.2 StaticSemantics:BoundNames

ForDeclaration : LetOrConst ForBinding

1.ReturntheBoundNamesofForBinding.

13.7.5.3 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

IterationStatement :
for ( LeftHandSideExpression in Expression ) Statement
for ( var ForBinding in Expression ) Statement
for ( ForDeclaration in Expression ) Statement
for ( LeftHandSideExpression of AssignmentExpression ) Statement
for ( var ForBinding of AssignmentExpression ) Statement
for ( ForDeclaration of AssignmentExpression ) Statement

1.ReturnContainsDuplicateLabelsofStatementwithargumentlabelSet.

13.7.5.4 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

IterationStatement :
for ( LeftHandSideExpression in Expression ) Statement
for ( var ForBinding in Expression ) Statement
for ( ForDeclaration in Expression ) Statement
for ( LeftHandSideExpression of AssignmentExpression ) Statement
for ( var ForBinding of AssignmentExpression ) Statement
for ( ForDeclaration of AssignmentExpression ) Statement

1.ReturnContainsUndeinedBreakTargetofStatementwithargumentlabelSet.

13.7.5.5 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

IterationStatement :
for ( LeftHandSideExpression in Expression ) Statement
for ( var ForBinding in Expression ) Statement
for ( ForDeclaration in Expression ) Statement
for ( LeftHandSideExpression of AssignmentExpression ) Statement
for ( var ForBinding of AssignmentExpression ) Statement
for ( ForDeclaration of AssignmentExpression ) Statement

1.ReturnContainsUndeinedContinueTargetofStatementwithargumentsiterationSetand.

13.7.5.6 StaticSemantics:IsDestructuring

ForDeclaration : LetOrConst ForBinding

1.ReturnIsDestructuringofForBinding.

ForBinding : BindingIdentiier

1.Returnfalse.

ForBinding : BindingPattern

1.Returntrue.

13.7.5.7 StaticSemantics:VarDeclaredNames

IterationStatement : for ( LeftHandSideExpression in Expression ) Statement

1.ReturntheVarDeclaredNamesofStatement.

IterationStatement : for ( var ForBinding in Expression ) Statement

1.LetnamesbetheBoundNamesofForBinding.
2.AppendtonamestheelementsoftheVarDeclaredNamesofStatement.
3.Returnnames.

IterationStatement : for ( ForDeclaration in Expression ) Statement

1.ReturntheVarDeclaredNamesofStatement.

IterationStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement

1.ReturntheVarDeclaredNamesofStatement.

IterationStatement : for ( var ForBinding of AssignmentExpression ) Statement

1.LetnamesbetheBoundNamesofForBinding.
2.AppendtonamestheelementsoftheVarDeclaredNamesofStatement.
3.Returnnames.

IterationStatement : for ( ForDeclaration of AssignmentExpression ) Statement

1.ReturntheVarDeclaredNamesofStatement.
13.7.5.8 StaticSemantics:VarScopedDeclarations

IterationStatement : for ( LeftHandSideExpression in Expression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

IterationStatement : for ( var ForBinding in Expression ) Statement

1.LetdeclarationsbeaListcontainingForBinding.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofStatement.
3.Returndeclarations.

IterationStatement : for ( ForDeclaration in Expression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

IterationStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

IterationStatement : for ( var ForBinding of AssignmentExpression ) Statement

1.LetdeclarationsbeaListcontainingForBinding.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofStatement.
3.Returndeclarations.

IterationStatement : for ( ForDeclaration of AssignmentExpression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

13.7.5.9 RuntimeSemantics:BindingInitialization

Withargumentsvalueandenvironment.

NOTE undeinedispassedforenvironmenttoindicatethataPutValueoperationshouldbeusedtoassignthe
initializationvalue.Thisisthecaseforvarstatementsandtheformalparameterlistsofsomenonstrict
functions(see9.2.12).Inthosecasesalexicalbindingishoistedandpreinitializedpriortoevaluationofits
initializer.

ForDeclaration : LetOrConst ForBinding

1.ReturntheresultofperformingBindingInitializationforForBindingpassingvalueandenvironmentasthearguments.

13.7.5.10 RuntimeSemantics:BindingInstantiation

Withargumentenvironment.

ForDeclaration : LetOrConst ForBinding

1.LetenvRecbeenvironment'sEnvironmentRecord.
2.Assert:envRecisadeclarativeEnvironmentRecord.
3.ForeachelementnameoftheBoundNamesofForBindingdo
a.IfIsConstantDeclarationofLetOrConstistrue,then
i.Perform!envRec.CreateImmutableBinding(name,true).
b.Else,
i.Perform!envRec.CreateMutableBinding(name,false).

13.7.5.11 RuntimeSemantics:LabelledEvaluation

WithargumentlabelSet.
IterationStatement : for ( LeftHandSideExpression in Expression ) Statement

1.LetkeyResultbe?ForIn/OfHeadEvaluation(,Expression,enumerate).
2.Return?ForIn/OfBodyEvaluation(LeftHandSideExpression,Statement,keyResult,assignment,labelSet).

IterationStatement : for ( var ForBinding in Expression ) Statement

1.LetkeyResultbe?ForIn/OfHeadEvaluation(,Expression,enumerate).
2.Return?ForIn/OfBodyEvaluation(ForBinding,Statement,keyResult,varBinding,labelSet).

IterationStatement : for ( ForDeclaration in Expression ) Statement

1.LetkeyResultbetheresultofperforming?ForIn/OfHeadEvaluation(BoundNamesofForDeclaration,Expression,
enumerate).
2.Return?ForIn/OfBodyEvaluation(ForDeclaration,Statement,keyResult,lexicalBinding,labelSet).

IterationStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement

1.LetkeyResultbetheresultofperforming?ForIn/OfHeadEvaluation(,AssignmentExpression,iterate).
2.Return?ForIn/OfBodyEvaluation(LeftHandSideExpression,Statement,keyResult,assignment,labelSet).

IterationStatement : for ( var ForBinding of AssignmentExpression ) Statement

1.LetkeyResultbetheresultofperforming?ForIn/OfHeadEvaluation(,AssignmentExpression,iterate).
2.Return?ForIn/OfBodyEvaluation(ForBinding,Statement,keyResult,varBinding,labelSet).

IterationStatement : for ( ForDeclaration of AssignmentExpression ) Statement

1.LetkeyResultbetheresultofperforming?ForIn/OfHeadEvaluation(BoundNamesofForDeclaration,
AssignmentExpression,iterate).
2.Return?ForIn/OfBodyEvaluation(ForDeclaration,Statement,keyResult,lexicalBinding,labelSet).

13.7.5.12 RuntimeSemantics:ForIn/OfHeadEvaluation(TDZnames,expr,iterationKind)

TheabstractoperationForIn/OfHeadEvaluationiscalledwithargumentsTDZnames,expr,anditerationKind.Thevalueof
iterationKindiseitherenumerateoriterate.

1.LetoldEnvbetherunningexecutioncontext'sLexicalEnvironment.
2.IfTDZnamesisnotanemptyList,then
a.Assert:TDZnameshasnoduplicateentries.
b.LetTDZbeNewDeclarativeEnvironment(oldEnv).
c.LetTDZEnvRecbeTDZ'sEnvironmentRecord.
d.ForeachstringnameinTDZnames,do
i.Perform!TDZEnvRec.CreateMutableBinding(name,false).
e.Settherunningexecutioncontext'sLexicalEnvironmenttoTDZ.
3.LetexprRefbetheresultofevaluatingexpr.
4.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
5.LetexprValuebe?GetValue(exprRef).
6.IfiterationKindisenumerate,then
a.IfexprValue.[[Value]]isnullorundeined,then
i.ReturnCompletion{[[Type]]:break,[[Value]]:empty,[[Target]]:empty}.
b.LetobjbeToObject(exprValue).
c.Return?EnumerateObjectProperties(obj).
7.Else,
a.Assert:iterationKindisiterate.
b.Return?GetIterator(exprValue).

13.7.5.13 RuntimeSemantics:ForIn/OfBodyEvaluation(lhs,stmt,iterator,lhsKind,labelSet)
TheabstractoperationForIn/OfBodyEvaluationiscalledwithargumentslhs,stmt,iterator,lhsKind,andlabelSet.Thevalueof
lhsKindiseitherassignment,varBindingorlexicalBinding.

1.LetoldEnvbetherunningexecutioncontext'sLexicalEnvironment.
2.LetVbeundeined.
3.LetdestructuringbeIsDestructuringoflhs.
4.IfdestructuringistrueandiflhsKindisassignment,then
a.Assert:lhsisaLeftHandSideExpression.
b.LetassignmentPatternbetheparseofthesourcetextcorrespondingtolhsusingAssignmentPatternasthegoal
symbol.
5.Repeat
a.LetnextResultbe?IteratorStep(iterator).
b.IfnextResultisfalse,returnNormalCompletion(V).
c.LetnextValuebe?IteratorValue(nextResult).
d.IflhsKindiseitherassignmentorvarBinding,then
i.Ifdestructuringisfalse,then
1.LetlhsRefbetheresultofevaluatinglhs.(Itmaybeevaluatedrepeatedly.)
e.Else,
i.Assert:lhsKindislexicalBinding.
ii.Assert:lhsisaForDeclaration.
iii.LetiterationEnvbeNewDeclarativeEnvironment(oldEnv).
iv.PerformBindingInstantiationforlhspassingiterationEnvastheargument.
v.Settherunningexecutioncontext'sLexicalEnvironmenttoiterationEnv.
vi.Ifdestructuringisfalse,then
1.Assert:lhsbindsasinglename.
2.LetlhsNamebethesoleelementofBoundNamesoflhs.
3.LetlhsRefbe!ResolveBinding(lhsName).
f.Ifdestructuringisfalse,then
i.IflhsRefisanabruptcompletion,then
1.LetstatusbelhsRef.
ii.ElseiflhsKindislexicalBinding,then
1.LetstatusbeInitializeReferencedBinding(lhsRef,nextValue).
iii.Else,
1.LetstatusbePutValue(lhsRef,nextValue).
g.Else,
i.IflhsKindisassignment,then
1.LetstatusbetheresultofperformingDestructuringAssignmentEvaluationofassignmentPatternusing
nextValueastheargument.
ii.ElseiflhsKindisvarBinding,then
1.Assert:lhsisaForBinding.
2.LetstatusbetheresultofperformingBindingInitializationforlhspassingnextValueandundeinedas
thearguments.
iii.Else,
1.Assert:lhsKindislexicalBinding.
2.Assert:lhsisaForDeclaration.
3.LetstatusbetheresultofperformingBindingInitializationforlhspassingnextValueanditerationEnvas
arguments.
h.Ifstatusisanabruptcompletion,then
i.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
ii.Return?IteratorClose(iterator,status).
i.Letresultbetheresultofevaluatingstmt.
j.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
k.IfLoopContinues(result,labelSet)isfalse,return?IteratorClose(iterator,UpdateEmpty(result,V)).
l.Ifresult.[[Value]]isnotempty,letVberesult.[[Value]].
13.7.5.14 RuntimeSemantics:Evaluation

ForBinding : BindingIdentiier

1.LetbindingIdbeStringValueofBindingIdentiier.
2.Return?ResolveBinding(bindingId).

13.7.5.15 EnumerateObjectProperties(O)

WhentheabstractoperationEnumerateObjectPropertiesiscalledwithargumentO,thefollowingstepsaretaken:

1.Assert:Type(O)isObject.
2.ReturnanIteratorobject(25.1.1.2)whosenextmethoditeratesoveralltheStringvaluedkeysofenumerable
propertiesofO.TheiteratorobjectisneverdirectlyaccessibletoECMAScriptcode.Themechanicsandorderof
enumeratingthepropertiesisnotspeciiedbutmustconformtotherulesspeciiedbelow.

Theiterator'sthrowandreturnmethodsarenullandareneverinvoked.Theiterator'snextmethodprocessesobject
propertiestodeterminewhetherthepropertykeyshouldbereturnedasaniteratorvalue.Returnedpropertykeysdonot
includekeysthatareSymbols.Propertiesofthetargetobjectmaybedeletedduringenumeration.Apropertythatisdeleted
beforeitisprocessedbytheiterator'snextmethodisignored.Ifnewpropertiesareaddedtothetargetobjectduring
enumeration,thenewlyaddedpropertiesarenotguaranteedtobeprocessedintheactiveenumeration.Apropertyname
willbereturnedbytheiterator'snextmethodatmostonceinanyenumeration.

Enumeratingthepropertiesofthetargetobjectincludesenumeratingpropertiesofitsprototype,andtheprototypeofthe
prototype,andsoon,recursively;butapropertyofaprototypeisnotprocessedifithasthesamenameasapropertythat
hasalreadybeenprocessedbytheiterator'snextmethod.Thevaluesof[[Enumerable]]attributesarenotconsideredwhen
determiningifapropertyofaprototypeobjecthasalreadybeenprocessed.Theenumerablepropertynamesofprototype
objectsmustbeobtainedbyinvokingEnumerateObjectPropertiespassingtheprototypeobjectastheargument.
EnumerateObjectPropertiesmustobtaintheownpropertykeysofthetargetobjectbycallingits[[OwnPropertyKeys]]
internalmethod.Propertyattributesofthetargetobjectmustbeobtainedbycallingits[[GetOwnProperty]]internalmethod.

NOTE ThefollowingisaninformativedeinitionofanECMAScriptgeneratorfunctionthatconformstotheserules:

function*EnumerateObjectProperties(obj){
letvisited=newSet;
for(letkeyofReflect.ownKeys(obj)){
if(typeofkey==="string"){
letdesc=Reflect.getOwnPropertyDescriptor(obj,key);
if(desc&&!visited.has(key)){
visited.add(key);
if(desc.enumerable)yieldkey;
}
}
}
letproto=Reflect.getPrototypeOf(obj)
if(proto===null)return;
for(letprotoNameofEnumerateObjectProperties(proto)){
if(!visited.has(protoName))yieldprotoName;
}
}

13.8 ThecontinueStatement
Syntax

ContinueStatement[Yield] :
continue ;
continue [noLineTerminatorhere] LabelIdentiier[?Yield] ;

13.8.1 StaticSemantics:EarlyErrors
ContinueStatement : continue ;
ContinueStatement : continue LabelIdentiier ;

ItisaSyntaxErrorifthisproductionisnotnested,directlyorindirectly(butnotcrossingfunctionboundaries),within
anIterationStatement.

13.8.2 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

ContinueStatement : continue ;

1.Returnfalse.

ContinueStatement : continue LabelIdentiier ;

1.IftheStringValueofLabelIdentiierisnotanelementofiterationSet,returntrue.
2.Returnfalse.

13.8.3 RuntimeSemantics:Evaluation
ContinueStatement : continue ;

1.ReturnCompletion{[[Type]]:continue,[[Value]]:empty,[[Target]]:empty}.

ContinueStatement : continue LabelIdentiier ;

1.LetlabelbetheStringValueofLabelIdentiier.
2.ReturnCompletion{[[Type]]:continue,[[Value]]:empty,[[Target]]:label}.

13.9 ThebreakStatement
Syntax

BreakStatement[Yield] :
break ;
break [noLineTerminatorhere] LabelIdentiier[?Yield] ;

13.9.1 StaticSemantics:EarlyErrors
BreakStatement : break ;

ItisaSyntaxErrorifthisproductionisnotnested,directlyorindirectly(butnotcrossingfunctionboundaries),within
anIterationStatementoraSwitchStatement.

13.9.2 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

BreakStatement : break ;

1.Returnfalse.

BreakStatement : break LabelIdentiier ;

1.IftheStringValueofLabelIdentiierisnotanelementoflabelSet,returntrue.
2.Returnfalse.

13.9.3 RuntimeSemantics:Evaluation
BreakStatement : break ;

1.ReturnCompletion{[[Type]]:break,[[Value]]:empty,[[Target]]:empty}.

BreakStatement : break LabelIdentiier ;

1.LetlabelbetheStringValueofLabelIdentiier.
2.ReturnCompletion{[[Type]]:break,[[Value]]:empty,[[Target]]:label}.

13.10 ThereturnStatement
Syntax

ReturnStatement[Yield] :
return ;
return [noLineTerminatorhere] Expression[In,?Yield] ;

NOTE Areturnstatementcausesafunctiontoceaseexecutionandreturnavaluetothecaller.IfExpressionis
omitted,thereturnvalueisundeined.Otherwise,thereturnvalueisthevalueofExpression.

13.10.1 RuntimeSemantics:Evaluation
ReturnStatement : return ;

1.ReturnCompletion{[[Type]]:return,[[Value]]:undeined,[[Target]]:empty}.

ReturnStatement : return Expression ;

1.LetexprRefbetheresultofevaluatingExpression.
2.LetexprValuebe?GetValue(exprRef).
3.ReturnCompletion{[[Type]]:return,[[Value]]:exprValue,[[Target]]:empty}.

13.11 ThewithStatement
Syntax

WithStatement[Yield,Return] :
with ( Expression[In,?Yield] ) Statement[?Yield,?Return]

NOTE ThewithstatementaddsanobjectEnvironmentRecordforacomputedobjecttothelexicalenvironmentof
therunningexecutioncontext.Itthenexecutesastatementusingthisaugmentedlexicalenvironment.Finally,
itrestorestheoriginallexicalenvironment.

13.11.1 StaticSemantics:EarlyErrors
WithStatement : with ( Expression ) Statement

ItisaSyntaxErrorifthecodethatmatchesthisproductioniscontainedinstrictcode.
ItisaSyntaxErrorifIsLabelledFunction(Statement)istrue.

NOTE ItisonlynecessarytoapplythesecondruleiftheextensionspeciiedinB.3.2isimplemented.

13.11.2 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.
WithStatement : with ( Expression ) Statement

1.ReturnContainsDuplicateLabelsofStatementwithargumentlabelSet.

13.11.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

WithStatement : with ( Expression ) Statement

1.ReturnContainsUndeinedBreakTargetofStatementwithargumentlabelSet.

13.11.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

WithStatement : with ( Expression ) Statement

1.ReturnContainsUndeinedContinueTargetofStatementwithargumentsiterationSetand.

13.11.5 StaticSemantics:VarDeclaredNames
WithStatement : with ( Expression ) Statement

1.ReturntheVarDeclaredNamesofStatement.

13.11.6 StaticSemantics:VarScopedDeclarations
WithStatement : with ( Expression ) Statement

1.ReturntheVarScopedDeclarationsofStatement.

13.11.7 RuntimeSemantics:Evaluation
WithStatement : with ( Expression ) Statement

1.LetvalbetheresultofevaluatingExpression.
2.Letobjbe?ToObject(?GetValue(val)).
3.LetoldEnvbetherunningexecutioncontext'sLexicalEnvironment.
4.LetnewEnvbeNewObjectEnvironment(obj,oldEnv).
5.SetthewithEnvironmentlagofnewEnv'sEnvironmentRecordtotrue.
6.Settherunningexecutioncontext'sLexicalEnvironmenttonewEnv.
7.LetCbetheresultofevaluatingStatement.
8.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
9.ReturnCompletion(UpdateEmpty(C,undeined)).

NOTE NomatterhowcontrolleavestheembeddedStatement,whethernormallyorbysomeformofabrupt
completionorexception,theLexicalEnvironmentisalwaysrestoredtoitsformerstate.

13.12 TheswitchStatement
Syntax

SwitchStatement[Yield,Return] :
switch ( Expression[In,?Yield] ) CaseBlock[?Yield,?Return]

CaseBlock[Yield,Return] :
{ CaseClauses[?Yield,?Return] opt }
{ CaseClauses[?Yield,?Return] opt DefaultClause[?Yield,?Return] CaseClauses[?Yield,?Return] opt }
CaseClauses[Yield,Return] :
CaseClause[?Yield,?Return]
CaseClauses[?Yield,?Return] CaseClause[?Yield,?Return]

CaseClause[Yield,Return] :
case Expression[In,?Yield] : StatementList[?Yield,?Return] opt

DefaultClause[Yield,Return] :
default : StatementList[?Yield,?Return] opt

13.12.1 StaticSemantics:EarlyErrors
SwitchStatement : switch ( Expression ) CaseBlock

ItisaSyntaxErroriftheLexicallyDeclaredNamesofCaseBlockcontainsanyduplicateentries.
ItisaSyntaxErrorifanyelementoftheLexicallyDeclaredNamesofCaseBlockalsooccursintheVarDeclaredNamesof
CaseBlock.

13.12.2 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

SwitchStatement : switch ( Expression ) CaseBlock

1.ReturnContainsDuplicateLabelsofCaseBlockwithargumentlabelSet.

CaseBlock : { }

1.Returnfalse.

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.IftheirstCaseClausesispresent,then
a.LethasDuplicatesbeContainsDuplicateLabelsoftheirstCaseClauseswithargumentlabelSet.
b.IfhasDuplicatesistrue,returntrue.
2.LethasDuplicatesbeContainsDuplicateLabelsofDefaultClausewithargumentlabelSet.
3.IfhasDuplicatesistrue,returntrue.
4.IfthesecondCaseClausesisnotpresent,returnfalse.
5.ReturnContainsDuplicateLabelsofthesecondCaseClauseswithargumentlabelSet.

CaseClauses : CaseClauses CaseClause

1.LethasDuplicatesbeContainsDuplicateLabelsofCaseClauseswithargumentlabelSet.
2.IfhasDuplicatesistrue,returntrue.
3.ReturnContainsDuplicateLabelsofCaseClausewithargumentlabelSet.

CaseClause : case Expression : StatementList

1.IftheStatementListispresent,returnContainsDuplicateLabelsofStatementListwithargumentlabelSet.
2.Elsereturnfalse.

DefaultClause : default : StatementList

1.IftheStatementListispresent,returnContainsDuplicateLabelsofStatementListwithargumentlabelSet.
2.Elsereturnfalse.

13.12.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.
SwitchStatement : switch ( Expression ) CaseBlock

1.ReturnContainsUndeinedBreakTargetofCaseBlockwithargumentlabelSet.

CaseBlock : { }

1.Returnfalse.

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.IftheirstCaseClausesispresent,then
a.LethasUndeinedLabelsbeContainsUndeinedBreakTargetoftheirstCaseClauseswithargumentlabelSet.
b.IfhasUndeinedLabelsistrue,returntrue.
2.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofDefaultClausewithargumentlabelSet.
3.IfhasUndeinedLabelsistrue,returntrue.
4.IfthesecondCaseClausesisnotpresent,returnfalse.
5.ReturnContainsUndeinedBreakTargetofthesecondCaseClauseswithargumentlabelSet.

CaseClauses : CaseClauses CaseClause

1.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofCaseClauseswithargumentlabelSet.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedBreakTargetofCaseClausewithargumentlabelSet.

CaseClause : case Expression : StatementList

1.IftheStatementListispresent,returnContainsUndeinedBreakTargetofStatementListwithargumentlabelSet.
2.Elsereturnfalse.

DefaultClause : default : StatementList

1.IftheStatementListispresent,returnContainsUndeinedBreakTargetofStatementListwithargumentlabelSet.
2.Elsereturnfalse.

13.12.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

SwitchStatement : switch ( Expression ) CaseBlock

1.ReturnContainsUndeinedContinueTargetofCaseBlockwithargumentsiterationSetand.

CaseBlock : { }

1.Returnfalse.

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.IftheirstCaseClausesispresent,then
a.LethasUndeinedLabelsbeContainsUndeinedContinueTargetoftheirstCaseClauseswithargumentsiterationSet
and.
b.IfhasUndeinedLabelsistrue,returntrue.
2.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofDefaultClausewithargumentsiterationSetand.
3.IfhasUndeinedLabelsistrue,returntrue.
4.IfthesecondCaseClausesisnotpresent,returnfalse.
5.ReturnContainsUndeinedContinueTargetofthesecondCaseClauseswithargumentsiterationSetand.

CaseClauses : CaseClauses CaseClause

1.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofCaseClauseswithargumentsiterationSetand.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedContinueTargetofCaseClausewithargumentsiterationSetand.

CaseClause : case Expression : StatementList

1.IftheStatementListispresent,returnContainsUndeinedContinueTargetofStatementListwithargumentsiterationSet
and.
2.Elsereturnfalse.

DefaultClause : default : StatementList

1.IftheStatementListispresent,returnContainsUndeinedContinueTargetofStatementListwithargumentsiterationSet
and.
2.Elsereturnfalse.

13.12.5 StaticSemantics:LexicallyDeclaredNames
CaseBlock : { }

1.ReturnanewemptyList.

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.IftheirstCaseClausesispresent,letnamesbetheLexicallyDeclaredNamesoftheirstCaseClauses.
2.ElseletnamesbeanewemptyList.
3.AppendtonamestheelementsoftheLexicallyDeclaredNamesoftheDefaultClause.
4.IfthesecondCaseClausesisnotpresent,returnnames.
5.ElsereturntheresultofappendingtonamestheelementsoftheLexicallyDeclaredNamesofthesecondCaseClauses.

CaseClauses : CaseClauses CaseClause

1.LetnamesbeLexicallyDeclaredNamesofCaseClauses.
2.AppendtonamestheelementsoftheLexicallyDeclaredNamesofCaseClause.
3.Returnnames.

CaseClause : case Expression : StatementList

1.IftheStatementListispresent,returntheLexicallyDeclaredNamesofStatementList.
2.ElsereturnanewemptyList.

DefaultClause : default : StatementList

1.IftheStatementListispresent,returntheLexicallyDeclaredNamesofStatementList.
2.ElsereturnanewemptyList.

13.12.6 StaticSemantics:LexicallyScopedDeclarations
CaseBlock : { }

1.ReturnanewemptyList.

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.IftheirstCaseClausesispresent,letdeclarationsbetheLexicallyScopedDeclarationsoftheirstCaseClauses.
2.ElseletdeclarationsbeanewemptyList.
3.AppendtodeclarationstheelementsoftheLexicallyScopedDeclarationsoftheDefaultClause.
4.IfthesecondCaseClausesisnotpresent,returndeclarations.
5.ElsereturntheresultofappendingtodeclarationstheelementsoftheLexicallyScopedDeclarationsofthesecond
CaseClauses.
CaseClauses : CaseClauses CaseClause

1.LetdeclarationsbeLexicallyScopedDeclarationsofCaseClauses.
2.AppendtodeclarationstheelementsoftheLexicallyScopedDeclarationsofCaseClause.
3.Returndeclarations.

CaseClause : case Expression : StatementList

1.IftheStatementListispresent,returntheLexicallyScopedDeclarationsofStatementList.
2.ElsereturnanewemptyList.

DefaultClause : default : StatementList

1.IftheStatementListispresent,returntheLexicallyScopedDeclarationsofStatementList.
2.ElsereturnanewemptyList.

13.12.7 StaticSemantics:VarDeclaredNames
SwitchStatement : switch ( Expression ) CaseBlock

1.ReturntheVarDeclaredNamesofCaseBlock.

CaseBlock : { }

1.ReturnanewemptyList.

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.IftheirstCaseClausesispresent,letnamesbetheVarDeclaredNamesoftheirstCaseClauses.
2.ElseletnamesbeanewemptyList.
3.AppendtonamestheelementsoftheVarDeclaredNamesoftheDefaultClause.
4.IfthesecondCaseClausesisnotpresent,returnnames.
5.ElsereturntheresultofappendingtonamestheelementsoftheVarDeclaredNamesofthesecondCaseClauses.

CaseClauses : CaseClauses CaseClause

1.LetnamesbeVarDeclaredNamesofCaseClauses.
2.AppendtonamestheelementsoftheVarDeclaredNamesofCaseClause.
3.Returnnames.

CaseClause : case Expression : StatementList

1.IftheStatementListispresent,returntheVarDeclaredNamesofStatementList.
2.ElsereturnanewemptyList.

DefaultClause : default : StatementList

1.IftheStatementListispresent,returntheVarDeclaredNamesofStatementList.
2.ElsereturnanewemptyList.

13.12.8 StaticSemantics:VarScopedDeclarations
SwitchStatement : switch ( Expression ) CaseBlock

1.ReturntheVarScopedDeclarationsofCaseBlock.

CaseBlock : { }

1.ReturnanewemptyList.

CaseBlock : { CaseClauses DefaultClause CaseClauses }


1.IftheirstCaseClausesispresent,letdeclarationsbetheVarScopedDeclarationsoftheirstCaseClauses.
2.ElseletdeclarationsbeanewemptyList.
3.AppendtodeclarationstheelementsoftheVarScopedDeclarationsoftheDefaultClause.
4.IfthesecondCaseClausesisnotpresent,returndeclarations.
5.ElsereturntheresultofappendingtodeclarationstheelementsoftheVarScopedDeclarationsofthesecondCaseClauses
.

CaseClauses : CaseClauses CaseClause

1.LetdeclarationsbeVarScopedDeclarationsofCaseClauses.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofCaseClause.
3.Returndeclarations.

CaseClause : case Expression : StatementList

1.IftheStatementListispresent,returntheVarScopedDeclarationsofStatementList.
2.ElsereturnanewemptyList.

DefaultClause : default : StatementList

1.IftheStatementListispresent,returntheVarScopedDeclarationsofStatementList.
2.ElsereturnanewemptyList.

13.12.9 RuntimeSemantics:CaseBlockEvaluation

Withargumentinput.

CaseBlock : { }

1.ReturnNormalCompletion(undeined).

CaseBlock : { CaseClauses }

1.LetVbeundeined.
2.LetAbetheListofCaseClauseitemsinCaseClauses,insourcetextorder.
3.Letfoundbefalse.
4.RepeatforeachCaseClauseCinA,
a.Iffoundisfalse,then
i.LetclauseSelectorbetheresultofCaseSelectorEvaluationofC.
ii.ReturnIfAbrupt(clauseSelector).
iii.LetfoundbetheresultofperformingStrictEqualityComparisoninput===clauseSelector.[[Value]].
b.Iffoundistrue,then
i.LetRbetheresultofevaluatingC.
ii.IfR.[[Value]]isnotempty,letVbeR.[[Value]].
iii.IfRisanabruptcompletion,returnCompletion(UpdateEmpty(R,V)).
5.ReturnNormalCompletion(V).

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.LetVbeundeined.
2.LetAbetheListofCaseClauseitemsintheirstCaseClauses,insourcetextorder.IftheirstCaseClausesisnotpresent,A
is.
3.Letfoundbefalse.
4.RepeatforeachCaseClauseCinA
a.Iffoundisfalse,then
i.LetclauseSelectorbetheresultofCaseSelectorEvaluationofC.
ii.ReturnIfAbrupt(clauseSelector).
iii.LetfoundbetheresultofperformingStrictEqualityComparisoninput===clauseSelector.[[Value]].
b.Iffoundistrue,then
i.LetRbetheresultofevaluatingC.
ii.IfR.[[Value]]isnotempty,letVbeR.[[Value]].
iii.IfRisanabruptcompletion,returnCompletion(UpdateEmpty(R,V)).
5.LetfoundInBbefalse.
6.LetBbetheListcontainingtheCaseClauseitemsinthesecondCaseClauses,insourcetextorder.Ifthesecond
CaseClausesisnotpresent,Bis.
7.Iffoundisfalse,then
a.RepeatforeachCaseClauseCinB
i.IffoundInBisfalse,then
1.LetclauseSelectorbetheresultofCaseSelectorEvaluationofC.
2.ReturnIfAbrupt(clauseSelector).
3.LetfoundInBbetheresultofperformingStrictEqualityComparisoninput===clauseSelector.[[Value]].
ii.IffoundInBistrue,then
1.LetRbetheresultofevaluatingCaseClauseC.
2.IfR.[[Value]]isnotempty,letVbeR.[[Value]].
3.IfRisanabruptcompletion,returnCompletion(UpdateEmpty(R,V)).
8.IffoundInBistrue,returnNormalCompletion(V).
9.LetRbetheresultofevaluatingDefaultClause.
10.IfR.[[Value]]isnotempty,letVbeR.[[Value]].
11.IfRisanabruptcompletion,returnCompletion(UpdateEmpty(R,V)).
12.RepeatforeachCaseClauseCinB(NOTEthisisanothercompleteiterationofthesecondCaseClauses)
a.LetRbetheresultofevaluatingCaseClauseC.
b.IfR.[[Value]]isnotempty,letVbeR.[[Value]].
c.IfRisanabruptcompletion,returnCompletion(UpdateEmpty(R,V)).
13.ReturnNormalCompletion(V).

13.12.10 RuntimeSemantics:CaseSelectorEvaluation
CaseClause : case Expression : StatementList

1.LetexprRefbetheresultofevaluatingExpression.
2.Return?GetValue(exprRef).

NOTE CaseSelectorEvaluationdoesnotexecutetheassociatedStatementList.ItsimplyevaluatestheExpressionand
returnsthevalue,whichtheCaseBlockalgorithmusestodeterminewhichStatementListtostartexecuting.

13.12.11 RuntimeSemantics:Evaluation
SwitchStatement : switch ( Expression ) CaseBlock

1.LetexprRefbetheresultofevaluatingExpression.
2.LetswitchValuebe?GetValue(exprRef).
3.LetoldEnvbetherunningexecutioncontext'sLexicalEnvironment.
4.LetblockEnvbeNewDeclarativeEnvironment(oldEnv).
5.PerformBlockDeclarationInstantiation(CaseBlock,blockEnv).
6.Settherunningexecutioncontext'sLexicalEnvironmenttoblockEnv.
7.LetRbetheresultofperformingCaseBlockEvaluationofCaseBlockwithargumentswitchValue.
8.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
9.ReturnR.

NOTE NomatterhowcontrolleavestheSwitchStatementtheLexicalEnvironmentisalwaysrestoredtoitsformer
state.

CaseClause : case Expression :

1.ReturnNormalCompletion(empty).
CaseClause : case Expression : StatementList

1.ReturntheresultofevaluatingStatementList.

DefaultClause : default :

1.ReturnNormalCompletion(empty).

DefaultClause : default : StatementList

1.ReturntheresultofevaluatingStatementList.

13.13 LabelledStatements
Syntax

LabelledStatement[Yield,Return] :
LabelIdentiier[?Yield] : LabelledItem[?Yield,?Return]

LabelledItem[Yield,Return] :
Statement[?Yield,?Return]
FunctionDeclaration[?Yield]

NOTE AStatementmaybepreixedbyalabel.Labelledstatementsareonlyusedinconjunctionwithlabelledbreak
andcontinuestatements.ECMAScripthasnogotostatement.AStatementcanbepartofaLabelledStatement,
whichitselfcanbepartofaLabelledStatement,andsoon.Thelabelsintroducedthiswayarecollectively
referredtoasthecurrentlabelsetwhendescribingthesemanticsofindividualstatements.

13.13.1 StaticSemantics:EarlyErrors
LabelledItem : FunctionDeclaration

ItisaSyntaxErrorifanysourcetextmatchesthisrule.

NOTE AnalternativedeinitionforthisruleisprovidedinB.3.2.

13.13.2 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

LabelledStatement : LabelIdentiier : LabelledItem

1.LetlabelbetheStringValueofLabelIdentiier.
2.IflabelisanelementoflabelSet,returntrue.
3.LetnewLabelSetbeacopyoflabelSetwithlabelappended.
4.ReturnContainsDuplicateLabelsofLabelledItemwithargumentnewLabelSet.

LabelledItem : FunctionDeclaration

1.Returnfalse.

13.13.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

LabelledStatement : LabelIdentiier : LabelledItem

1.LetlabelbetheStringValueofLabelIdentiier.
2.LetnewLabelSetbeacopyoflabelSetwithlabelappended.
3.ReturnContainsUndeinedBreakTargetofLabelledItemwithargumentnewLabelSet.
LabelledItem : FunctionDeclaration

1.Returnfalse.

13.13.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

LabelledStatement : LabelIdentiier : LabelledItem

1.LetlabelbetheStringValueofLabelIdentiier.
2.LetnewLabelSetbeacopyoflabelSetwithlabelappended.
3.ReturnContainsUndeinedContinueTargetofLabelledItemwithargumentsiterationSetandnewLabelSet.

LabelledItem : FunctionDeclaration

1.Returnfalse.

13.13.5 StaticSemantics:IsLabelledFunction(stmt)

TheabstractoperationIsLabelledFunctionwithargumentstmtperformsthefollowingsteps:

1.IfstmtisnotaLabelledStatement,returnfalse.
2.LetitembetheLabelledItemcomponentofstmt.
3.IfitemisLabelledItem : FunctionDeclaration ,returntrue.
4.LetsubStmtbetheStatementcomponentofitem.
5.ReturnIsLabelledFunction(subStmt).

13.13.6 StaticSemantics:LexicallyDeclaredNames
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturntheLexicallyDeclaredNamesofLabelledItem.

LabelledItem : Statement

1.ReturnanewemptyList.

LabelledItem : FunctionDeclaration

1.ReturnBoundNamesofFunctionDeclaration.

13.13.7 StaticSemantics:LexicallyScopedDeclarations
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturntheLexicallyScopedDeclarationsofLabelledItem.

LabelledItem : Statement

1.ReturnanewemptyList.

LabelledItem : FunctionDeclaration

1.ReturnanewListcontainingFunctionDeclaration.

13.13.8 StaticSemantics:TopLevelLexicallyDeclaredNames
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturnanewemptyList.
13.13.9 StaticSemantics:TopLevelLexicallyScopedDeclarations
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturnanewemptyList.

13.13.10 StaticSemantics:TopLevelVarDeclaredNames
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturntheTopLevelVarDeclaredNamesofLabelledItem.

LabelledItem : Statement

1.IfStatementisStatement : LabelledStatement ,returnTopLevelVarDeclaredNamesofStatement.


2.ReturnVarDeclaredNamesofStatement.

LabelledItem : FunctionDeclaration

1.ReturnBoundNamesofFunctionDeclaration.

13.13.11 StaticSemantics:TopLevelVarScopedDeclarations
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturntheTopLevelVarScopedDeclarationsofLabelledItem.

LabelledItem : Statement

1.IfStatementisStatement : LabelledStatement ,returnTopLevelVarScopedDeclarationsofStatement.


2.ReturnVarScopedDeclarationsofStatement.

LabelledItem : FunctionDeclaration

1.ReturnanewListcontainingFunctionDeclaration.

13.13.12 StaticSemantics:VarDeclaredNames
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturntheVarDeclaredNamesofLabelledItem.

LabelledItem : FunctionDeclaration

1.ReturnanewemptyList.

13.13.13 StaticSemantics:VarScopedDeclarations
LabelledStatement : LabelIdentiier : LabelledItem

1.ReturntheVarScopedDeclarationsofLabelledItem.

LabelledItem : FunctionDeclaration

1.ReturnanewemptyList.

13.13.14 RuntimeSemantics:LabelledEvaluation

WithargumentlabelSet.

LabelledStatement : LabelIdentiier : LabelledItem

1.LetlabelbetheStringValueofLabelIdentiier.
2.AppendlabelasanelementoflabelSet.
3.LetstmtResultbeLabelledEvaluationofLabelledItemwithargumentlabelSet.
4.IfstmtResult.[[Type]]isbreakandSameValue(stmtResult.[[Target]],label)istrue,then
a.LetstmtResultbeNormalCompletion(stmtResult.[[Value]]).
5.ReturnCompletion(stmtResult).

LabelledItem : Statement

1.IfStatementiseitheraLabelledStatementoraBreakableStatement,then
a.ReturnLabelledEvaluationofStatementwithargumentlabelSet.
2.Else,
a.ReturntheresultofevaluatingStatement.

LabelledItem : FunctionDeclaration

1.ReturntheresultofevaluatingFunctionDeclaration.

13.13.15 RuntimeSemantics:Evaluation
LabelledStatement : LabelIdentiier : LabelledItem

1.LetnewLabelSetbeanewemptyList.
2.ReturnLabelledEvaluationofthisLabelledStatementwithargumentnewLabelSet.

13.14 ThethrowStatement
Syntax

ThrowStatement[Yield] :
throw [noLineTerminatorhere] Expression[In,?Yield] ;

13.14.1 RuntimeSemantics:Evaluation
ThrowStatement : throw Expression ;

1.LetexprRefbetheresultofevaluatingExpression.
2.LetexprValuebe?GetValue(exprRef).
3.ReturnCompletion{[[Type]]:throw,[[Value]]:exprValue,[[Target]]:empty}.

13.15 ThetryStatement
Syntax

TryStatement[Yield,Return] :
try Block[?Yield,?Return] Catch[?Yield,?Return]
try Block[?Yield,?Return] Finally[?Yield,?Return]
try Block[?Yield,?Return] Catch[?Yield,?Return] Finally[?Yield,?Return]

Catch[Yield,Return] :
catch ( CatchParameter[?Yield] ) Block[?Yield,?Return]

Finally[Yield,Return] :
finally Block[?Yield,?Return]

CatchParameter[Yield] :
BindingIdentiier[?Yield]
BindingPattern[?Yield]
NOTE Thetrystatementenclosesablockofcodeinwhichanexceptionalconditioncanoccur,suchasaruntime
errororathrowstatement.Thecatchclauseprovidestheexceptionhandlingcode.Whenacatchclause
catchesanexception,itsCatchParameterisboundtothatexception.

13.15.1 StaticSemantics:EarlyErrors
Catch : catch ( CatchParameter ) Block

ItisaSyntaxErrorifBoundNamesofCatchParametercontainsanyduplicateelements.
ItisaSyntaxErrorifanyelementoftheBoundNamesofCatchParameteralsooccursintheLexicallyDeclaredNamesof
Block.
ItisaSyntaxErrorifanyelementoftheBoundNamesofCatchParameteralsooccursintheVarDeclaredNamesofBlock.

NOTE AnalternativestaticsemanticsforthisproductionisgiveninB.3.5.

13.15.2 StaticSemantics:ContainsDuplicateLabels

WithargumentlabelSet.

TryStatement : try Block Catch

1.LethasDuplicatesbeContainsDuplicateLabelsofBlockwithargumentlabelSet.
2.IfhasDuplicatesistrue,returntrue.
3.ReturnContainsDuplicateLabelsofCatchwithargumentlabelSet.

TryStatement : try Block Finally

1.LethasDuplicatesbeContainsDuplicateLabelsofBlockwithargumentlabelSet.
2.IfhasDuplicatesistrue,returntrue.
3.ReturnContainsDuplicateLabelsofFinallywithargumentlabelSet.

TryStatement : try Block Catch Finally

1.LethasDuplicatesbeContainsDuplicateLabelsofBlockwithargumentlabelSet.
2.IfhasDuplicatesistrue,returntrue.
3.LethasDuplicatesbeContainsDuplicateLabelsofCatchwithargumentlabelSet.
4.IfhasDuplicatesistrue,returntrue.
5.ReturnContainsDuplicateLabelsofFinallywithargumentlabelSet.

Catch : catch ( CatchParameter ) Block

1.ReturnContainsDuplicateLabelsofBlockwithargumentlabelSet.

13.15.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

TryStatement : try Block Catch

1.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofBlockwithargumentlabelSet.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedBreakTargetofCatchwithargumentlabelSet.

TryStatement : try Block Finally

1.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofBlockwithargumentlabelSet.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedBreakTargetofFinallywithargumentlabelSet.

TryStatement : try Block Catch Finally


1.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofBlockwithargumentlabelSet.
2.IfhasUndeinedLabelsistrue,returntrue.
3.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofCatchwithargumentlabelSet.
4.IfhasUndeinedLabelsistrue,returntrue.
5.ReturnContainsUndeinedBreakTargetofFinallywithargumentlabelSet.

Catch : catch ( CatchParameter ) Block

1.ReturnContainsUndeinedBreakTargetofBlockwithargumentlabelSet.

13.15.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

TryStatement : try Block Catch

1.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofBlockwithargumentsiterationSetand.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedContinueTargetofCatchwithargumentsiterationSetand.

TryStatement : try Block Finally

1.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofBlockwithargumentsiterationSetand.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedContinueTargetofFinallywithargumentsiterationSetand.

TryStatement : try Block Catch Finally

1.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofBlockwithargumentsiterationSetand.
2.IfhasUndeinedLabelsistrue,returntrue.
3.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofCatchwithargumentsiterationSetand.
4.IfhasUndeinedLabelsistrue,returntrue.
5.ReturnContainsUndeinedContinueTargetofFinallywithargumentsiterationSetand.

Catch : catch ( CatchParameter ) Block

1.ReturnContainsUndeinedContinueTargetofBlockwithargumentsiterationSetand.

13.15.5 StaticSemantics:VarDeclaredNames
TryStatement : try Block Catch

1.LetnamesbeVarDeclaredNamesofBlock.
2.AppendtonamestheelementsoftheVarDeclaredNamesofCatch.
3.Returnnames.

TryStatement : try Block Finally

1.LetnamesbeVarDeclaredNamesofBlock.
2.AppendtonamestheelementsoftheVarDeclaredNamesofFinally.
3.Returnnames.

TryStatement : try Block Catch Finally

1.LetnamesbeVarDeclaredNamesofBlock.
2.AppendtonamestheelementsoftheVarDeclaredNamesofCatch.
3.AppendtonamestheelementsoftheVarDeclaredNamesofFinally.
4.Returnnames.

Catch : catch ( CatchParameter ) Block


1.ReturntheVarDeclaredNamesofBlock.

13.15.6 StaticSemantics:VarScopedDeclarations
TryStatement : try Block Catch

1.LetdeclarationsbeVarScopedDeclarationsofBlock.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofCatch.
3.Returndeclarations.

TryStatement : try Block Finally

1.LetdeclarationsbeVarScopedDeclarationsofBlock.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofFinally.
3.Returndeclarations.

TryStatement : try Block Catch Finally

1.LetdeclarationsbeVarScopedDeclarationsofBlock.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofCatch.
3.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofFinally.
4.Returndeclarations.

Catch : catch ( CatchParameter ) Block

1.ReturntheVarScopedDeclarationsofBlock.

13.15.7 RuntimeSemantics:CatchClauseEvaluation

withparameterthrownValue

Catch : catch ( CatchParameter ) Block

1.LetoldEnvbetherunningexecutioncontext'sLexicalEnvironment.
2.LetcatchEnvbeNewDeclarativeEnvironment(oldEnv).
3.LetcatchEnvRecbecatchEnv'sEnvironmentRecord.
4.ForeachelementargNameoftheBoundNamesofCatchParameter,do
a.Perform!catchEnvRec.CreateMutableBinding(argName,false).
5.Settherunningexecutioncontext'sLexicalEnvironmenttocatchEnv.
6.LetstatusbetheresultofperformingBindingInitializationforCatchParameterpassingthrownValueandcatchEnvas
arguments.
7.Ifstatusisanabruptcompletion,then
a.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
b.ReturnCompletion(status).
8.LetBbetheresultofevaluatingBlock.
9.Settherunningexecutioncontext'sLexicalEnvironmenttooldEnv.
10.ReturnCompletion(B).

NOTE NomatterhowcontrolleavestheBlocktheLexicalEnvironmentisalwaysrestoredtoitsformerstate.

13.15.8 RuntimeSemantics:Evaluation
TryStatement : try Block Catch

1.LetBbetheresultofevaluatingBlock.
2.IfB.[[Type]]isthrow,letCbeCatchClauseEvaluationofCatchwithparameterB.[[Value]].
3.Else,letCbeB.
4.ReturnCompletion(UpdateEmpty(C,undeined)).
TryStatement : try Block Finally

1.LetBbetheresultofevaluatingBlock.
2.LetFbetheresultofevaluatingFinally.
3.IfF.[[Type]]isnormal,letFbeB.
4.ReturnCompletion(UpdateEmpty(F,undeined)).

TryStatement : try Block Catch Finally

1.LetBbetheresultofevaluatingBlock.
2.IfB.[[Type]]isthrow,letCbeCatchClauseEvaluationofCatchwithparameterB.[[Value]].
3.Else,letCbeB.
4.LetFbetheresultofevaluatingFinally.
5.IfF.[[Type]]isnormal,letFbeC.
6.ReturnCompletion(UpdateEmpty(F,undeined)).

13.16 ThedebuggerStatement
Syntax

DebuggerStatement :
debugger ;

13.16.1 RuntimeSemantics:Evaluation

NOTE EvaluatingtheDebuggerStatementproductionmayallowanimplementationtocauseabreakpointwhenrun
underadebugger.Ifadebuggerisnotpresentoractivethisstatementhasnoobservableeffect.

DebuggerStatement : debugger ;

1.Ifanimplementationdeineddebuggingfacilityisavailableandenabled,then
a.Performanimplementationdeineddebuggingaction.
b.LetresultbeanimplementationdeinedCompletionvalue.
2.Else,
a.LetresultbeNormalCompletion(empty).
3.Returnresult.

14 ECMAScriptLanguage:FunctionsandClasses
NOTE VariousECMAScriptlanguageelementscausethecreationofECMAScriptfunctionobjects(9.2).Evaluationof
suchfunctionsstartswiththeexecutionoftheir[[Call]]internalmethod(9.2.1).

14.1 FunctionDeinitions
Syntax

FunctionDeclaration[Yield,Default] :
function BindingIdentiier[?Yield] ( FormalParameters ) { FunctionBody }
[+Default] function ( FormalParameters ) { FunctionBody }

FunctionExpression :
function BindingIdentiieropt ( FormalParameters ) { FunctionBody }

StrictFormalParameters[Yield] :
FormalParameters[?Yield]
FormalParameters[Yield] :
[empty]
FormalParameterList[?Yield]

FormalParameterList[Yield] :
FunctionRestParameter[?Yield]
FormalsList[?Yield]
FormalsList[?Yield] , FunctionRestParameter[?Yield]

FormalsList[Yield] :
FormalParameter[?Yield]
FormalsList[?Yield] , FormalParameter[?Yield]

FunctionRestParameter[Yield] :
BindingRestElement[?Yield]

FormalParameter[Yield] :
BindingElement[?Yield]

FunctionBody[Yield] :
FunctionStatementList[?Yield]

FunctionStatementList[Yield] :
StatementList[?Yield,Return] opt

14.1.1 DirectiveProloguesandtheUseStrictDirective

ADirectivePrologueisthelongestsequenceofExpressionStatementproductionsoccurringastheinitialStatementListItemor
ModuleItemproductionsofaFunctionBody,aScriptBody,oraModuleBodyandwhereeachExpressionStatementinthe
sequenceconsistsentirelyofaStringLiteraltokenfollowedbyasemicolon.Thesemicolonmayappearexplicitlyormaybe
insertedbyautomaticsemicoloninsertion.ADirectiveProloguemaybeanemptysequence.

AUseStrictDirectiveisanExpressionStatementinaDirectiveProloguewhoseStringLiteraliseithertheexactcodeunit
sequences"usestrict"or'usestrict'.AUseStrictDirectivemaynotcontainanEscapeSequenceorLineContinuation.

ADirectiveProloguemaycontainmorethanoneUseStrictDirective.However,animplementationmayissueawarningifthis
occurs.

NOTE TheExpressionStatementproductionsofaDirectivePrologueareevaluatednormallyduringevaluationofthe
containingproduction.Implementationsmaydeineimplementationspeciicmeaningsfor
ExpressionStatementproductionswhicharenotaUseStrictDirectiveandwhichoccurinaDirectivePrologue.
Ifanappropriatenotiicationmechanismexists,animplementationshouldissueawarningifitencountersina
DirectivePrologueanExpressionStatementthatisnotaUseStrictDirectiveandwhichdoesnothaveameaning
deinedbytheimplementation.

14.1.2 StaticSemantics:EarlyErrors
FunctionDeclaration : function BindingIdentiier ( FormalParameters ) { FunctionBody }
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
FunctionExpression : function BindingIdentiier ( FormalParameters ) { FunctionBody }

Ifthesourcecodematchingthisproductionisstrictcode,theEarlyErrorrulesforStrictFormalParameters :
FormalParameters areapplied.
Ifthesourcecodematchingthisproductionisstrictcode,itisaSyntaxErrorifBindingIdentiieristheIdentiierName
evalortheIdentiierNamearguments.
ItisaSyntaxErrorifContainsUseStrictofFunctionBodyistrueandIsSimpleParameterListofFormalParametersis
false.
ItisaSyntaxErrorifanyelementoftheBoundNamesofFormalParametersalsooccursintheLexicallyDeclaredNames
ofFunctionBody.
ItisaSyntaxErrorifFormalParametersContainsSuperPropertyistrue.
ItisaSyntaxErrorifFunctionBodyContainsSuperPropertyistrue.
ItisaSyntaxErrorifFormalParametersContainsSuperCallistrue.
ItisaSyntaxErrorifFunctionBodyContainsSuperCallistrue.

NOTE1 TheLexicallyDeclaredNamesofaFunctionBodydoesnotincludeidentiiersboundusingvarorfunction
declarations.

StrictFormalParameters : FormalParameters

ItisaSyntaxErrorifBoundNamesofFormalParameterscontainsanyduplicateelements.

FormalParameters : FormalParameterList

ItisaSyntaxErrorifIsSimpleParameterListofFormalParameterListisfalseandBoundNamesofFormalParameterList
containsanyduplicateelements.

NOTE2 MultipleoccurrencesofthesameBindingIdentiierinaFormalParameterListisonlyallowedforfunctionsand
generatorfunctionswhichhavesimpleparameterlistsandwhicharenotdeinedinstrictmodecode.

FunctionBody : FunctionStatementList

ItisaSyntaxErroriftheLexicallyDeclaredNamesofFunctionStatementListcontainsanyduplicateentries.
ItisaSyntaxErrorifanyelementoftheLexicallyDeclaredNamesofFunctionStatementListalsooccursinthe
VarDeclaredNamesofFunctionStatementList.
ItisaSyntaxErrorifContainsDuplicateLabelsofFunctionStatementListwithargumentistrue.
ItisaSyntaxErrorifContainsUndeinedBreakTargetofFunctionStatementListwithargumentistrue.
ItisaSyntaxErrorifContainsUndeinedContinueTargetofFunctionStatementListwithargumentsandistrue.

14.1.3 StaticSemantics:BoundNames
FunctionDeclaration : function BindingIdentiier ( FormalParameters ) { FunctionBody }

1.ReturntheBoundNamesofBindingIdentiier.

FunctionDeclaration : function ( FormalParameters ) { FunctionBody }

1.Return"*default*".

NOTE "*default*"isusedwithinthisspeciicationasasyntheticnameforhoistableanonymousfunctionsthatare
deinedusingexportdeclarations.

FormalParameters : [empty]

1.ReturnanewemptyList.

FormalParameterList : FormalsList , FunctionRestParameter

1.LetnamesbeBoundNamesofFormalsList.
2.AppendtonamestheBoundNamesofFunctionRestParameter.
3.Returnnames.

FormalsList : FormalsList , FormalParameter

1.LetnamesbeBoundNamesofFormalsList.
2.AppendtonamestheelementsofBoundNamesofFormalParameter.
3.Returnnames.

14.1.4 StaticSemantics:Contains

Withparametersymbol.

FunctionDeclaration : function BindingIdentiier ( FormalParameters ) { FunctionBody }


FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
FunctionExpression : function BindingIdentiier ( FormalParameters ) { FunctionBody }

1.Returnfalse.

NOTE Staticsemanticrulesthatdependuponsubstructuregenerallydonotlookintofunctiondeinitions.

14.1.5 StaticSemantics:ContainsExpression
FormalParameters : [empty]

1.Returnfalse.

FormalParameterList : FunctionRestParameter

1.ReturnContainsExpressionofFunctionRestParameter.

FormalParameterList : FormalsList , FunctionRestParameter

1.IfContainsExpressionofFormalsLististrue,returntrue.
2.ReturnContainsExpressionofFunctionRestParameter.

FormalsList : FormalsList , FormalParameter

1.IfContainsExpressionofFormalsLististrue,returntrue.
2.ReturnContainsExpressionofFormalParameter.

14.1.6 StaticSemantics:ContainsUseStrict
FunctionBody : FunctionStatementList

1.IftheDirectivePrologueofFunctionStatementListcontainsaUseStrictDirective,returntrue;otherwise,returnfalse.

14.1.7 StaticSemantics:ExpectedArgumentCount
FormalParameters : [empty]

1.Return0.

FormalParameterList : FunctionRestParameter

1.Return0.

FormalParameterList : FormalsList , FunctionRestParameter

1.ReturntheExpectedArgumentCountofFormalsList.

NOTE TheExpectedArgumentCountofaFormalParameterLististhenumberofFormalParameterstotheleftofeither
therestparameterortheirstFormalParameterwithanInitializer.AFormalParameterwithoutaninitializeris
allowedaftertheirstparameterwithaninitializerbutsuchparametersareconsideredtobeoptionalwith
undeinedastheirdefaultvalue.

FormalsList : FormalParameter

1.IfHasInitializerofFormalParameteristrue,return0.
2.Return1.

FormalsList : FormalsList , FormalParameter

1.LetcountbetheExpectedArgumentCountofFormalsList.
2.IfHasInitializerofFormalsLististrueorHasInitializerofFormalParameteristrue,returncount.
3.Returncount+1.

14.1.8 StaticSemantics:HasInitializer
FormalsList : FormalsList , FormalParameter

1.IfHasInitializerofFormalsLististrue,returntrue.
2.ReturnHasInitializerofFormalParameter.

14.1.9 StaticSemantics:HasName
FunctionExpression : function ( FormalParameters ) { FunctionBody }

1.Returnfalse.

FunctionExpression : function BindingIdentiier ( FormalParameters ) { FunctionBody }

1.Returntrue.

14.1.10 StaticSemantics:IsAnonymousFunctionDeinition(production)

TheabstractoperationIsAnonymousFunctionDeinitiondeterminesifitsargumentisafunctiondeinitionthatdoesnotbind
aname.TheargumentproductionistheresultofparsinganAssignmentExpressionorInitializer.Thefollowingstepsare
taken:

1.IfIsFunctionDeinitionofproductionisfalse,returnfalse.
2.LethasNamebetheresultofHasNameofproduction.
3.IfhasNameistrue,returnfalse.
4.Returntrue.

14.1.11 StaticSemantics:IsConstantDeclaration
FunctionDeclaration : function BindingIdentiier ( FormalParameters ) { FunctionBody }
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }

1.Returnfalse.

14.1.12 StaticSemantics:IsFunctionDeinition
FunctionExpression : function BindingIdentiier ( FormalParameters ) { FunctionBody }

1.Returntrue.

14.1.13 StaticSemantics:IsSimpleParameterList
FormalParameters : [empty]

1.Returntrue.

FormalParameterList : FunctionRestParameter

1.Returnfalse.

FormalParameterList : FormalsList , FunctionRestParameter


1.Returnfalse.

FormalsList : FormalsList , FormalParameter

1.IfIsSimpleParameterListofFormalsListisfalse,returnfalse.
2.ReturnIsSimpleParameterListofFormalParameter.

FormalParameter : BindingElement

1.ReturnIsSimpleParameterListofBindingElement.

14.1.14 StaticSemantics:LexicallyDeclaredNames
FunctionStatementList : [empty]

1.ReturnanewemptyList.

FunctionStatementList : StatementList

1.ReturnTopLevelLexicallyDeclaredNamesofStatementList.

14.1.15 StaticSemantics:LexicallyScopedDeclarations
FunctionStatementList : [empty]

1.ReturnanewemptyList.

FunctionStatementList : StatementList

1.ReturntheTopLevelLexicallyScopedDeclarationsofStatementList.

14.1.16 StaticSemantics:VarDeclaredNames
FunctionStatementList : [empty]

1.ReturnanewemptyList.

FunctionStatementList : StatementList

1.ReturnTopLevelVarDeclaredNamesofStatementList.

14.1.17 StaticSemantics:VarScopedDeclarations
FunctionStatementList : [empty]

1.ReturnanewemptyList.

FunctionStatementList : StatementList

1.ReturntheTopLevelVarScopedDeclarationsofStatementList.

14.1.18 RuntimeSemantics:EvaluateBody

WithparameterfunctionObject.

FunctionBody : FunctionStatementList

1.ReturntheresultofevaluatingFunctionStatementList.

14.1.19 RuntimeSemantics:IteratorBindingInitialization

WithparametersiteratorRecordandenvironment.
NOTE1 WhenundeinedispassedforenvironmentitindicatesthataPutValueoperationshouldbeusedtoassignthe
initializationvalue.Thisisthecaseforformalparameterlistsofnonstrictfunctions.Inthatcasetheformal
parameterbindingsarepreinitializedinordertodealwiththepossibilityofmultipleparameterswiththe
samename.

FormalParameters : [empty]

1.ReturnNormalCompletion(empty).

FormalParameterList : FormalsList , FunctionRestParameter

1.LetrestIndexbetheresultofperformingIteratorBindingInitializationforFormalsListusingiteratorRecordand
environmentasthearguments.
2.ReturnIfAbrupt(restIndex).
3.ReturntheresultofperformingIteratorBindingInitializationforFunctionRestParameterusingiteratorRecordand
environmentasthearguments.

FormalsList : FormalsList , FormalParameter

1.LetstatusbetheresultofperformingIteratorBindingInitializationforFormalsListusingiteratorRecordandenvironment
asthearguments.
2.ReturnIfAbrupt(status).
3.ReturntheresultofperformingIteratorBindingInitializationforFormalParameterusingiteratorRecordand
environmentasthearguments.

FormalParameter : BindingElement

1.IfContainsExpressionofBindingElementisfalse,returntheresultofperformingIteratorBindingInitializationfor
BindingElementusingiteratorRecordandenvironmentasthearguments.
2.LetcurrentContextbetherunningexecutioncontext.
3.LetoriginalEnvbetheVariableEnvironmentofcurrentContext.
4.Assert:TheVariableEnvironmentandLexicalEnvironmentofcurrentContextarethesame.
5.Assert:environmentandoriginalEnvarethesame.
6.LetparamVarEnvbeNewDeclarativeEnvironment(originalEnv).
7.SettheVariableEnvironmentofcurrentContexttoparamVarEnv.
8.SettheLexicalEnvironmentofcurrentContexttoparamVarEnv.
9.LetresultbetheresultofperformingIteratorBindingInitializationforBindingElementusingiteratorRecordand
environmentasthearguments.
10.SettheVariableEnvironmentofcurrentContexttooriginalEnv.
11.SettheLexicalEnvironmentofcurrentContexttooriginalEnv.
12.Returnresult.

NOTE2 ThenewEnvironmentRecordcreatedinstep6isonlyusediftheBindingElementcontainsadirecteval.

FunctionRestParameter : BindingRestElement

1.IfContainsExpressionofBindingRestElementisfalse,returntheresultofperformingIteratorBindingInitializationfor
BindingRestElementusingiteratorRecordandenvironmentasthearguments.
2.LetcurrentContextbetherunningexecutioncontext.
3.LetoriginalEnvbetheVariableEnvironmentofcurrentContext.
4.Assert:TheVariableEnvironmentandLexicalEnvironmentofcurrentContextarethesame.
5.Assert:environmentandoriginalEnvarethesame.
6.LetparamVarEnvbeNewDeclarativeEnvironment(originalEnv).
7.SettheVariableEnvironmentofcurrentContexttoparamVarEnv.
8.SettheLexicalEnvironmentofcurrentContexttoparamVarEnv.
9.LetresultbetheresultofperformingIteratorBindingInitializationforBindingRestElementusingiteratorRecordand
environmentasthearguments.
10.SettheVariableEnvironmentofcurrentContexttooriginalEnv.
11.SettheLexicalEnvironmentofcurrentContexttooriginalEnv.
12.Returnresult.

NOTE3 ThenewEnvironmentRecordcreatedinstep6isonlyusediftheBindingRestElementcontainsadirecteval.

14.1.20 RuntimeSemantics:InstantiateFunctionObject

Withparameterscope.

FunctionDeclaration : function BindingIdentiier ( FormalParameters ) { FunctionBody }

1.IfthefunctioncodeforFunctionDeclarationisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.LetnamebeStringValueofBindingIdentiier.
3.LetFbeFunctionCreate(Normal,FormalParameters,FunctionBody,scope,strict).
4.PerformMakeConstructor(F).
5.PerformSetFunctionName(F,name).
6.ReturnF.

FunctionDeclaration : function ( FormalParameters ) { FunctionBody }

1.IfthefunctioncodeforFunctionDeclarationisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.LetFbeFunctionCreate(Normal,FormalParameters,FunctionBody,scope,strict).
3.PerformMakeConstructor(F).
4.PerformSetFunctionName(F,"default").
5.ReturnF.

NOTE AnanonymousFunctionDeclarationcanonlyoccuraspartofanexportdefaultdeclaration.

14.1.21 RuntimeSemantics:Evaluation
FunctionDeclaration : function BindingIdentiier ( FormalParameters ) { FunctionBody }

1.ReturnNormalCompletion(empty).

NOTE1 AnalternativesemanticsisprovidedinB.3.3.

FunctionDeclaration : function ( FormalParameters ) { FunctionBody }

1.ReturnNormalCompletion(empty).

FunctionExpression : function ( FormalParameters ) { FunctionBody }

1.IfthefunctioncodeforFunctionExpressionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.LetscopebetheLexicalEnvironmentoftherunningexecutioncontext.
3.LetclosurebeFunctionCreate(Normal,FormalParameters,FunctionBody,scope,strict).
4.PerformMakeConstructor(closure).
5.Returnclosure.

FunctionExpression : function BindingIdentiier ( FormalParameters ) { FunctionBody }

1.IfthefunctioncodeforFunctionExpressionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.Letscopebetherunningexecutioncontext'sLexicalEnvironment.
3.LetfuncEnvbeNewDeclarativeEnvironment(scope).
4.LetenvRecbefuncEnv'sEnvironmentRecord.
5.LetnamebeStringValueofBindingIdentiier.
6.PerformenvRec.CreateImmutableBinding(name,false).
7.LetclosurebeFunctionCreate(Normal,FormalParameters,FunctionBody,funcEnv,strict).
8.PerformMakeConstructor(closure).
9.PerformSetFunctionName(closure,name).
10.PerformenvRec.InitializeBinding(name,closure).
11.Returnclosure.

NOTE2 TheBindingIdentiierinaFunctionExpressioncanbereferencedfrominsidetheFunctionExpression's
FunctionBodytoallowthefunctiontocallitselfrecursively.However,unlikeinaFunctionDeclaration,the
BindingIdentiierinaFunctionExpressioncannotbereferencedfromanddoesnotaffectthescopeenclosingthe
FunctionExpression.

NOTE3 AprototypepropertyisautomaticallycreatedforeveryfunctiondeinedusingaFunctionDeclarationor
FunctionExpression,toallowforthepossibilitythatthefunctionwillbeusedasaconstructor.

FunctionStatementList : [empty]

1.ReturnNormalCompletion(undeined).

14.2 ArrowFunctionDeinitions
Syntax

ArrowFunction[In,Yield] :
ArrowParameters[?Yield] [noLineTerminatorhere] => ConciseBody[?In]

ArrowParameters[Yield] :
BindingIdentiier[?Yield]
CoverParenthesizedExpressionAndArrowParameterList[?Yield]

ConciseBody[In] :
[lookahead{] AssignmentExpression[?In]
{ FunctionBody }

SupplementalSyntax

Whentheproduction
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
isrecognizedthefollowinggrammarisusedtoreinetheinterpretationof
CoverParenthesizedExpressionAndArrowParameterList:

ArrowFormalParameters[Yield] :
( StrictFormalParameters[?Yield] )

14.2.1 StaticSemantics:EarlyErrors
ArrowFunction : ArrowParameters => ConciseBody

ItisaSyntaxErrorifArrowParametersContainsYieldExpressionistrue.
ItisaSyntaxErrorifContainsUseStrictofConciseBodyistrueandIsSimpleParameterListofArrowParametersisfalse.
ItisaSyntaxErrorifanyelementoftheBoundNamesofArrowParametersalsooccursintheLexicallyDeclaredNamesof
ConciseBody.

ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

Ifthe[Yield]grammarparameterispresentonArrowParameters,itisaSyntaxErrorifthelexicaltokensequence
matchedbyCoverParenthesizedExpressionAndArrowParameterList[?Yield] cannotbeparsedwithnotokensleftover
usingArrowFormalParameters[Yield] asthegoalsymbol.
Ifthe[Yield]grammarparameterisnotpresentonArrowParameters,itisaSyntaxErrorifthelexicaltokensequence
matchedbyCoverParenthesizedExpressionAndArrowParameterList[?Yield] cannotbeparsedwithnotokensleftover
usingArrowFormalParametersasthegoalsymbol.
AllearlyerrorsrulesforArrowFormalParametersanditsderivedproductionsalsoapplytoCoveredFormalsListof
CoverParenthesizedExpressionAndArrowParameterList[?Yield] .

14.2.2 StaticSemantics:BoundNames
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

1.LetformalsbeCoveredFormalsListofCoverParenthesizedExpressionAndArrowParameterList.
2.ReturntheBoundNamesofformals.

14.2.3 StaticSemantics:Contains

Withparametersymbol.

ArrowFunction : ArrowParameters => ConciseBody

1.IfsymbolisnotoneofNewTarget,SuperProperty,SuperCall,superorthis,returnfalse.
2.IfArrowParametersContainssymbolistrue,returntrue.
3.ReturnConciseBodyContainssymbol.

NOTE Normally,Containsdoesnotlookinsidemostfunctionforms.However,Containsisusedtodetectnew.target,
this,andsuperusagewithinanArrowFunction.

ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

1.LetformalsbeCoveredFormalsListofCoverParenthesizedExpressionAndArrowParameterList.
2.ReturnformalsContainssymbol.

14.2.4 StaticSemantics:ContainsExpression
ArrowParameters : BindingIdentiier

1.Returnfalse.

14.2.5 StaticSemantics:ContainsUseStrict
ConciseBody : AssignmentExpression

1.Returnfalse.

14.2.6 StaticSemantics:ExpectedArgumentCount
ArrowParameters : BindingIdentiier

1.Return1.

14.2.7 StaticSemantics:HasName
ArrowFunction : ArrowParameters => ConciseBody

1.Returnfalse.

14.2.8 StaticSemantics:IsSimpleParameterList
ArrowParameters : BindingIdentiier

1.Returntrue.

ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

1.LetformalsbeCoveredFormalsListofCoverParenthesizedExpressionAndArrowParameterList.
2.ReturnIsSimpleParameterListofformals.

14.2.9 StaticSemantics:CoveredFormalsList
ArrowParameters : BindingIdentiier

1.ReturnthisArrowParameters.

CoverParenthesizedExpressionAndArrowParameterList[Yield] :
( Expression )
( )
( ... BindingIdentiier )
( ... BindingPattern )
( Expression , ... BindingIdentiier )
( Expression , ... BindingPattern )

1.Ifthe[Yield]grammarparameterispresentforCoverParenthesizedExpressionAndArrowParameterList[Yield] ,return
theresultofparsingthelexicaltokenstreammatchedbyCoverParenthesizedExpressionAndArrowParameterList[Yield]
usingArrowFormalParameters[Yield] asthegoalsymbol.
2.Ifthe[Yield]grammarparameterisnotpresentforCoverParenthesizedExpressionAndArrowParameterList[Yield] ,
returntheresultofparsingthelexicaltokenstreammatchedbyCoverParenthesizedExpressionAndArrowParameterList
usingArrowFormalParametersasthegoalsymbol.

14.2.10 StaticSemantics:LexicallyDeclaredNames
ConciseBody : AssignmentExpression

1.ReturnanewemptyList.

14.2.11 StaticSemantics:LexicallyScopedDeclarations
ConciseBody : AssignmentExpression

1.ReturnanewemptyList.

14.2.12 StaticSemantics:VarDeclaredNames
ConciseBody : AssignmentExpression

1.ReturnanewemptyList.

14.2.13 StaticSemantics:VarScopedDeclarations
ConciseBody : AssignmentExpression

1.ReturnanewemptyList.

14.2.14 RuntimeSemantics:IteratorBindingInitialization

WithparametersiteratorRecordandenvironment.

NOTE WhenundeinedispassedforenvironmentitindicatesthataPutValueoperationshouldbeusedtoassignthe
initializationvalue.Thisisthecaseforformalparameterlistsofnonstrictfunctions.Inthatcasetheformal
parameterbindingsarepreinitializedinordertodealwiththepossibilityofmultipleparameterswiththe
samename.

ArrowParameters : BindingIdentiier

1.Assert:iteratorRecord.[[Done]]isfalse.
2.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
3.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
4.ReturnIfAbrupt(next).
5.Ifnextisfalse,setiteratorRecord.[[Done]]totrue.
6.Else,
a.LetvbeIteratorValue(next).
b.Ifvisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(v).
7.IfiteratorRecord.[[Done]]istrue,letvbeundeined.
8.ReturntheresultofperformingBindingInitializationforBindingIdentiierusingvandenvironmentasthearguments.

14.2.15 RuntimeSemantics:EvaluateBody

WithparameterfunctionObject.

ConciseBody : AssignmentExpression

1.LetexprRefbetheresultofevaluatingAssignmentExpression.
2.LetexprValuebe?GetValue(exprRef).
3.ReturnCompletion{[[Type]]:return,[[Value]]:exprValue,[[Target]]:empty}.

14.2.16 RuntimeSemantics:Evaluation
ArrowFunction : ArrowParameters => ConciseBody

1.IfthefunctioncodeforthisArrowFunctionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.LetscopebetheLexicalEnvironmentoftherunningexecutioncontext.
3.LetparametersbeCoveredFormalsListofArrowParameters.
4.LetclosurebeFunctionCreate(Arrow,parameters,ConciseBody,scope,strict).
5.Returnclosure.

NOTE AnArrowFunctiondoesnotdeinelocalbindingsforarguments,super,this,ornew.target.Anyreference
toarguments,super,this,ornew.targetwithinanArrowFunctionmustresolvetoabindinginalexically
enclosingenvironment.TypicallythiswillbetheFunctionEnvironmentofanimmediatelyenclosingfunction.
EventhoughanArrowFunctionmaycontainreferencestosuper,thefunctionobjectcreatedinstep4isnot
madeintoamethodbyperformingMakeMethod.AnArrowFunctionthatreferencessuperisalwayscontained
withinanonArrowFunctionandthenecessarystatetoimplementsuperisaccessibleviathescopethatis
capturedbythefunctionobjectoftheArrowFunction.

14.3 MethodDeinitions
Syntax

MethodDeinition[Yield] :
PropertyName[?Yield] ( StrictFormalParameters ) { FunctionBody }
GeneratorMethod[?Yield]
get PropertyName[?Yield] ( ) { FunctionBody }
set PropertyName[?Yield] ( PropertySetParameterList ) { FunctionBody }

PropertySetParameterList :
FormalParameter

14.3.1 StaticSemantics:EarlyErrors
MethodDeinition : PropertyName ( StrictFormalParameters ) { FunctionBody }

ItisaSyntaxErrorifContainsUseStrictofFunctionBodyistrueandIsSimpleParameterListofStrictFormalParametersis
false.
ItisaSyntaxErrorifanyelementoftheBoundNamesofStrictFormalParametersalsooccursinthe
LexicallyDeclaredNamesofFunctionBody.

MethodDeinition : set PropertyName ( PropertySetParameterList ) { FunctionBody }

ItisaSyntaxErrorifBoundNamesofPropertySetParameterListcontainsanyduplicateelements.
ItisaSyntaxErrorifContainsUseStrictofFunctionBodyistrueandIsSimpleParameterListofPropertySetParameterList
isfalse.
ItisaSyntaxErrorifanyelementoftheBoundNamesofPropertySetParameterListalsooccursinthe
LexicallyDeclaredNamesofFunctionBody.

14.3.2 StaticSemantics:ComputedPropertyContains

Withparametersymbol.

MethodDeinition :
PropertyName ( StrictFormalParameters ) { FunctionBody }
get PropertyName ( ) { FunctionBody }
set PropertyName ( PropertySetParameterList ) { FunctionBody }

1.ReturntheresultofComputedPropertyContainsforPropertyNamewithargumentsymbol.

14.3.3 StaticSemantics:ExpectedArgumentCount
PropertySetParameterList : FormalParameter

1.IfHasInitializerofFormalParameteristrue,return0.
2.Return1.

14.3.4 StaticSemantics:HasComputedPropertyKey

MethodDeinition :
PropertyName ( StrictFormalParameters ) { FunctionBody }
get PropertyName ( ) { FunctionBody }
set PropertyName ( PropertySetParameterList ) { FunctionBody }

1.ReturnIsComputedPropertyKeyofPropertyName.

14.3.5 StaticSemantics:HasDirectSuper
MethodDeinition : PropertyName ( StrictFormalParameters ) { FunctionBody }

1.IfStrictFormalParametersContainsSuperCallistrue,returntrue.
2.ReturnFunctionBodyContainsSuperCall.

MethodDeinition : get PropertyName ( ) { FunctionBody }

1.ReturnFunctionBodyContainsSuperCall.

MethodDeinition : set PropertyName ( PropertySetParameterList ) { FunctionBody }

1.IfPropertySetParameterListContainsSuperCallistrue,returntrue.
2.ReturnFunctionBodyContainsSuperCall.

14.3.6 StaticSemantics:PropName

MethodDeinition :
PropertyName ( StrictFormalParameters ) { FunctionBody }
get PropertyName ( ) { FunctionBody }
set PropertyName ( PropertySetParameterList ) { FunctionBody }

1.ReturnPropNameofPropertyName.

14.3.7 StaticSemantics:SpecialMethod
MethodDeinition : PropertyName ( StrictFormalParameters ) { FunctionBody }

1.Returnfalse.

MethodDeinition :
GeneratorMethod
get PropertyName ( ) { FunctionBody }
set PropertyName ( PropertySetParameterList ) { FunctionBody }

1.Returntrue.

14.3.8 RuntimeSemantics:DeineMethod

WithparametersobjectandoptionalparameterfunctionPrototype.

MethodDeinition : PropertyName ( StrictFormalParameters ) { FunctionBody }

1.LetpropKeybetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(propKey).
3.IfthefunctioncodeforthisMethodDeinitionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
4.Letscopebetherunningexecutioncontext'sLexicalEnvironment.
5.IffunctionPrototypewaspassedasaparameter,letkindbeNormal;otherwiseletkindbeMethod.
6.LetclosurebeFunctionCreate(kind,StrictFormalParameters,FunctionBody,scope,strict).IffunctionPrototypewas
passedasaparameter,thenpassitsvalueastheprototypeoptionalargumentofFunctionCreate.
7.PerformMakeMethod(closure,object).
8.ReturntheRecord{[[Key]]:propKey,[[Closure]]:closure}.

14.3.9 RuntimeSemantics:PropertyDeinitionEvaluation

Withparametersobjectandenumerable.

MethodDeinition : PropertyName ( StrictFormalParameters ) { FunctionBody }

1.LetmethodDefbeDeineMethodofMethodDeinitionwithargumentobject.
2.ReturnIfAbrupt(methodDef).
3.PerformSetFunctionName(methodDef.[[Closure]],methodDef.[[Key]]).
4.LetdescbethePropertyDescriptor{[[Value]]:methodDef.[[Closure]],[[Writable]]:true,[[Enumerable]]:enumerable,
[[Conigurable]]:true}.
5.Return?DeinePropertyOrThrow(object,methodDef.[[Key]],desc).

MethodDeinition : GeneratorMethod

See14.4.

MethodDeinition : get PropertyName ( ) { FunctionBody }

1.LetpropKeybetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(propKey).
3.IfthefunctioncodeforthisMethodDeinitionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
4.Letscopebetherunningexecutioncontext'sLexicalEnvironment.
5.LetformalParameterListbetheproductionFormalParameters : [empty] .
6.LetclosurebeFunctionCreate(Method,formalParameterList,FunctionBody,scope,strict).
7.PerformMakeMethod(closure,object).
8.PerformSetFunctionName(closure,propKey,"get").
9.LetdescbethePropertyDescriptor{[[Get]]:closure,[[Enumerable]]:enumerable,[[Conigurable]]:true}.
10.Return?DeinePropertyOrThrow(object,propKey,desc).

MethodDeinition : set PropertyName ( PropertySetParameterList ) { FunctionBody }

1.LetpropKeybetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(propKey).
3.IfthefunctioncodeforthisMethodDeinitionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
4.Letscopebetherunningexecutioncontext'sLexicalEnvironment.
5.LetclosurebeFunctionCreate(Method,PropertySetParameterList,FunctionBody,scope,strict).
6.PerformMakeMethod(closure,object).
7.PerformSetFunctionName(closure,propKey,"set").
8.LetdescbethePropertyDescriptor{[[Set]]:closure,[[Enumerable]]:enumerable,[[Conigurable]]:true}.
9.Return?DeinePropertyOrThrow(object,propKey,desc).

14.4 GeneratorFunctionDeinitions
Syntax

GeneratorMethod[Yield] :
* PropertyName[?Yield] ( StrictFormalParameters[Yield] ) { GeneratorBody }

GeneratorDeclaration[Yield,Default] :
function * BindingIdentiier[?Yield] ( FormalParameters[Yield] ) { GeneratorBody }
[+Default] function * ( FormalParameters[Yield] ) { GeneratorBody }

GeneratorExpression :
function * BindingIdentiier[Yield] opt ( FormalParameters[Yield] ) { GeneratorBody }

GeneratorBody :
FunctionBody[Yield]

YieldExpression[In] :
yield
yield [noLineTerminatorhere] AssignmentExpression[?In,Yield]
yield [noLineTerminatorhere] * AssignmentExpression[?In,Yield]

NOTE1 ThesyntacticcontextimmediatelyfollowingyieldrequiresuseoftheInputElementRegExpOrTemplateTail
lexicalgoal.

NOTE2 YieldExpressioncannotbeusedwithintheFormalParametersofageneratorfunctionbecauseanyexpressions
thatarepartofFormalParametersareevaluatedbeforetheresultinggeneratorobjectisinaresumablestate.

NOTE3 Abstractoperationsrelatingtogeneratorobjectsaredeinedin25.3.3.

14.4.1 StaticSemantics:EarlyErrors
GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody }

ItisaSyntaxErrorifHasDirectSuperofGeneratorMethodistrue.
ItisaSyntaxErrorifStrictFormalParametersContainsYieldExpressionistrue.
ItisaSyntaxErrorifContainsUseStrictofGeneratorBodyistrueandIsSimpleParameterListofStrictFormalParameters
isfalse.
ItisaSyntaxErrorifanyelementoftheBoundNamesofStrictFormalParametersalsooccursinthe
LexicallyDeclaredNamesofGeneratorBody.
GeneratorDeclaration : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
GeneratorExpression : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }

Ifthesourcecodematchingthisproductionisstrictcode,theEarlyErrorrulesforStrictFormalParameters :
FormalParameters areapplied.
Ifthesourcecodematchingthisproductionisstrictcode,itisaSyntaxErrorifBindingIdentiieristheIdentiierName
evalortheIdentiierNamearguments.
ItisaSyntaxErrorifContainsUseStrictofGeneratorBodyistrueandIsSimpleParameterListofFormalParametersis
false.
ItisaSyntaxErrorifanyelementoftheBoundNamesofFormalParametersalsooccursintheLexicallyDeclaredNames
ofGeneratorBody.
ItisaSyntaxErrorifFormalParametersContainsYieldExpressionistrue.
ItisaSyntaxErrorifFormalParametersContainsSuperPropertyistrue.
ItisaSyntaxErrorifGeneratorBodyContainsSuperPropertyistrue.
ItisaSyntaxErrorifFormalParametersContainsSuperCallistrue.
ItisaSyntaxErrorifGeneratorBodyContainsSuperCallistrue.

14.4.2 StaticSemantics:BoundNames
GeneratorDeclaration : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }

1.ReturntheBoundNamesofBindingIdentiier.

GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }

1.Return"*default*".

NOTE "*default*"isusedwithinthisspeciicationasasyntheticnameforhoistableanonymousfunctionsthatare
deinedusingexportdeclarations.

14.4.3 StaticSemantics:ComputedPropertyContains

Withparametersymbol.

GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody }

1.ReturntheresultofComputedPropertyContainsforPropertyNamewithargumentsymbol.

14.4.4 StaticSemantics:Contains

Withparametersymbol.

GeneratorDeclaration : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }


GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
GeneratorExpression : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }

1.Returnfalse.

NOTE Staticsemanticrulesthatdependuponsubstructuregenerallydonotlookintofunctiondeinitions.

14.4.5 StaticSemantics:HasComputedPropertyKey
GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody }

1.ReturnIsComputedPropertyKeyofPropertyName.

14.4.6 StaticSemantics:HasDirectSuper
GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody }
1.IfStrictFormalParametersContainsSuperCallistrue,returntrue.
2.ReturnGeneratorBodyContainsSuperCall.

14.4.7 StaticSemantics:HasName
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }

1.Returnfalse.

GeneratorExpression : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }

1.Returntrue.

14.4.8 StaticSemantics:IsConstantDeclaration
GeneratorDeclaration : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }

1.Returnfalse.

14.4.9 StaticSemantics:IsFunctionDeinition
GeneratorExpression : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }

1.Returntrue.

14.4.10 StaticSemantics:PropName
GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody }

1.ReturnPropNameofPropertyName.

14.4.11 RuntimeSemantics:EvaluateBody

WithparameterfunctionObject.

GeneratorBody : FunctionBody

1.LetGbe?OrdinaryCreateFromConstructor(functionObject,"%GeneratorPrototype%",[[GeneratorState]],
[[GeneratorContext]]).
2.PerformGeneratorStart(G,FunctionBody).
3.ReturnCompletion{[[Type]]:return,[[Value]]:G,[[Target]]:empty}.

14.4.12 RuntimeSemantics:InstantiateFunctionObject

Withparameterscope.

GeneratorDeclaration : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }

1.IfthefunctioncodeforGeneratorDeclarationisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.LetnamebeStringValueofBindingIdentiier.
3.LetFbeGeneratorFunctionCreate(Normal,FormalParameters,GeneratorBody,scope,strict).
4.LetprototypebeObjectCreate(%GeneratorPrototype%).
5.PerformDeinePropertyOrThrow(F,"prototype",PropertyDescriptor{[[Value]]:prototype,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:false}).
6.PerformSetFunctionName(F,name).
7.ReturnF.

GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }


1.IfthefunctioncodeforGeneratorDeclarationisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.LetFbeGeneratorFunctionCreate(Normal,FormalParameters,GeneratorBody,scope,strict).
3.LetprototypebeObjectCreate(%GeneratorPrototype%).
4.PerformDeinePropertyOrThrow(F,"prototype",PropertyDescriptor{[[Value]]:prototype,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:false}).
5.PerformSetFunctionName(F,"default").
6.ReturnF.

NOTE AnanonymousGeneratorDeclarationcanonlyoccuraspartofanexportdefaultdeclaration.

14.4.13 RuntimeSemantics:PropertyDeinitionEvaluation

Withparameterobjectandenumerable.

GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody }

1.LetpropKeybetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(propKey).
3.IfthefunctioncodeforthisGeneratorMethodisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
4.Letscopebetherunningexecutioncontext'sLexicalEnvironment.
5.LetclosurebeGeneratorFunctionCreate(Method,StrictFormalParameters,GeneratorBody,scope,strict).
6.PerformMakeMethod(closure,object).
7.LetprototypebeObjectCreate(%GeneratorPrototype%).
8.PerformDeinePropertyOrThrow(closure,"prototype",PropertyDescriptor{[[Value]]:prototype,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:false}).
9.PerformSetFunctionName(closure,propKey).
10.LetdescbethePropertyDescriptor{[[Value]]:closure,[[Writable]]:true,[[Enumerable]]:enumerable,[[Conigurable]]:
true}.
11.Return?DeinePropertyOrThrow(object,propKey,desc).

14.4.14 RuntimeSemantics:Evaluation
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }

1.IfthefunctioncodeforthisGeneratorExpressionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.LetscopebetheLexicalEnvironmentoftherunningexecutioncontext.
3.LetclosurebeGeneratorFunctionCreate(Normal,FormalParameters,GeneratorBody,scope,strict).
4.LetprototypebeObjectCreate(%GeneratorPrototype%).
5.PerformDeinePropertyOrThrow(closure,"prototype",PropertyDescriptor{[[Value]]:prototype,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:false}).
6.Returnclosure.

GeneratorExpression : function * BindingIdentiier ( FormalParameters ) { GeneratorBody }

1.IfthefunctioncodeforthisGeneratorExpressionisstrictmodecode,letstrictbetrue.Otherwiseletstrictbefalse.
2.Letscopebetherunningexecutioncontext'sLexicalEnvironment.
3.LetfuncEnvbeNewDeclarativeEnvironment(scope).
4.LetenvRecbefuncEnv'sEnvironmentRecord.
5.LetnamebeStringValueofBindingIdentiier.
6.PerformenvRec.CreateImmutableBinding(name,false).
7.LetclosurebeGeneratorFunctionCreate(Normal,FormalParameters,GeneratorBody,funcEnv,strict).
8.LetprototypebeObjectCreate(%GeneratorPrototype%).
9.PerformDeinePropertyOrThrow(closure,"prototype",PropertyDescriptor{[[Value]]:prototype,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:false}).
10.PerformSetFunctionName(closure,name).
11.PerformenvRec.InitializeBinding(name,closure).
12.Returnclosure.

NOTE TheBindingIdentiierinaGeneratorExpressioncanbereferencedfrominsidetheGeneratorExpression's
FunctionBodytoallowthegeneratorcodetocallitselfrecursively.However,unlikeinaGeneratorDeclaration,
theBindingIdentiierinaGeneratorExpressioncannotbereferencedfromanddoesnotaffectthescope
enclosingtheGeneratorExpression.

YieldExpression : yield

1.Return?GeneratorYield(CreateIterResultObject(undeined,false)).

YieldExpression : yield AssignmentExpression

1.LetexprRefbetheresultofevaluatingAssignmentExpression.
2.Letvaluebe?GetValue(exprRef).
3.Return?GeneratorYield(CreateIterResultObject(value,false)).

YieldExpression : yield * AssignmentExpression

1.LetexprRefbetheresultofevaluatingAssignmentExpression.
2.Letvaluebe?GetValue(exprRef).
3.Letiteratorbe?GetIterator(value).
4.LetreceivedbeNormalCompletion(undeined).
5.Repeat
a.Ifreceived.[[Type]]isnormal,then
i.LetinnerResultbe?IteratorNext(iterator,received.[[Value]]).
ii.Letdonebe?IteratorComplete(innerResult).
iii.Ifdoneistrue,then
1.Return?IteratorValue(innerResult).
iv.LetreceivedbeGeneratorYield(innerResult).
b.Elseifreceived.[[Type]]isthrow,then
i.Letthrowbe?GetMethod(iterator,"throw").
ii.Ifthrowisnotundeined,then
1.LetinnerResultbe?Call(throw,iterator,received.[[Value]]).
2.NOTE:Exceptionsfromtheinneriteratorthrowmethodarepropagated.Normalcompletionsfroman
innerthrowmethodareprocessedsimilarlytoaninnernext.
3.IfType(innerResult)isnotObject,throwaTypeErrorexception.
4.Letdonebe?IteratorComplete(innerResult).
5.Ifdoneistrue,then
a.Return?IteratorValue(innerResult).
6.LetreceivedbeGeneratorYield(innerResult).
iii.Else,
1.NOTE:Ifiteratordoesnothaveathrowmethod,thisthrowisgoingtoterminatetheyield*loop.But
irstweneedtogiveiteratorachancetocleanup.
2.Perform?IteratorClose(iterator,Completion{[[Type]]:normal,[[Value]]:empty,[[Target]]:empty}).
3.NOTE:ThenextstepthrowsaTypeErrortoindicatethattherewasayield*protocolviolation:
iteratordoesnothaveathrowmethod.
4.ThrowaTypeErrorexception.
c.Else,
i.Assert:received.[[Type]]isreturn.
ii.Letreturnbe?GetMethod(iterator,"return").
iii.Ifreturnisundeined,returnCompletion(received).
iv.LetinnerReturnResultbe?Call(return,iterator,received.[[Value]]).
v.IfType(innerReturnResult)isnotObject,throwaTypeErrorexception.
vi.Letdonebe?IteratorComplete(innerReturnResult).
vii.Ifdoneistrue,then
1.Letvaluebe?IteratorValue(innerReturnResult).
2.ReturnCompletion{[[Type]]:return,[[Value]]:value,[[Target]]:empty}.
viii.LetreceivedbeGeneratorYield(innerReturnResult).

14.5 ClassDeinitions
Syntax

ClassDeclaration[Yield,Default] :
class BindingIdentiier[?Yield] ClassTail[?Yield]
[+Default] class ClassTail[?Yield]

ClassExpression[Yield] :
class BindingIdentiier[?Yield] opt ClassTail[?Yield]

ClassTail[Yield] :
ClassHeritage[?Yield] opt { ClassBody[?Yield] opt }

ClassHeritage[Yield] :
extends LeftHandSideExpression[?Yield]

ClassBody[Yield] :
ClassElementList[?Yield]

ClassElementList[Yield] :
ClassElement[?Yield]
ClassElementList[?Yield] ClassElement[?Yield]

ClassElement[Yield] :
MethodDeinition[?Yield]
static MethodDeinition[?Yield]
;

NOTE Aclassdeinitionisalwaysstrictcode.

14.5.1 StaticSemantics:EarlyErrors
ClassTail : ClassHeritage { ClassBody }

ItisaSyntaxErrorifClassHeritageisnotpresentandthefollowingalgorithmevaluatestotrue:

1.LetconstructorbeConstructorMethodofClassBody.
2.Ifconstructorisempty,returnfalse.
3.ReturnHasDirectSuperofconstructor.

ClassBody : ClassElementList

ItisaSyntaxErrorifPrototypePropertyNameListofClassElementListcontainsmorethanoneoccurrenceof
"constructor".

ClassElement : MethodDeinition

ItisaSyntaxErrorifPropNameofMethodDeinitionisnot"constructor"andHasDirectSuperofMethodDeinitionis
true.
ItisaSyntaxErrorifPropNameofMethodDeinitionis"constructor"andSpecialMethodofMethodDeinitionistrue.

ClassElement : static MethodDeinition


ItisaSyntaxErrorifHasDirectSuperofMethodDeinitionistrue.
ItisaSyntaxErrorifPropNameofMethodDeinitionis"prototype".

14.5.2 StaticSemantics:BoundNames
ClassDeclaration : class BindingIdentiier ClassTail

1.ReturntheBoundNamesofBindingIdentiier.

ClassDeclaration : class ClassTail

1.Return"*default*".

14.5.3 StaticSemantics:ConstructorMethod
ClassElementList : ClassElement

1.IfClassElementistheproductionClassElement : ; ,returnempty.
2.IfIsStaticofClassElementistrue,returnempty.
3.IfPropNameofClassElementisnot"constructor",returnempty.
4.ReturnClassElement.

ClassElementList : ClassElementList ClassElement

1.LetheadbeConstructorMethodofClassElementList.
2.Ifheadisnotempty,returnhead.
3.IfClassElementistheproductionClassElement : ; ,returnempty.
4.IfIsStaticofClassElementistrue,returnempty.
5.IfPropNameofClassElementisnot"constructor",returnempty.
6.ReturnClassElement.

NOTE EarlyErrorrulesensurethatthereisonlyonemethoddeinitionnamed"constructor"andthatitisnotan
accessorpropertyorgeneratordeinition.

14.5.4 StaticSemantics:Contains

Withparametersymbol.

ClassTail : ClassHeritage { ClassBody }

1.IfsymbolisClassBody,returntrue.
2.IfsymbolisClassHeritage,then
a.IfClassHeritageispresent,returntrue;otherwisereturnfalse.
3.LetinHeritagebeClassHeritageContainssymbol.
4.IfinHeritageistrue,returntrue.
5.ReturntheresultofComputedPropertyContainsforClassBodywithargumentsymbol.

NOTE Staticsemanticrulesthatdependuponsubstructuregenerallydonotlookintoclassbodiesexceptfor
PropertyNameproductions.

14.5.5 StaticSemantics:ComputedPropertyContains

Withparametersymbol.

ClassElementList : ClassElementList ClassElement

1.LetinListbetheresultofComputedPropertyContainsforClassElementListwithargumentsymbol.
2.IfinLististrue,returntrue.
3.ReturntheresultofComputedPropertyContainsforClassElementwithargumentsymbol.
ClassElement : MethodDeinition

1.ReturntheresultofComputedPropertyContainsforMethodDeinitionwithargumentsymbol.

ClassElement : static MethodDeinition

1.ReturntheresultofComputedPropertyContainsforMethodDeinitionwithargumentsymbol.

ClassElement : ;

1.Returnfalse.

14.5.6 StaticSemantics:HasName
ClassExpression : class ClassTail

1.Returnfalse.

ClassExpression : class BindingIdentiier ClassTail

1.Returntrue.

14.5.7 StaticSemantics:IsConstantDeclaration
ClassDeclaration : class BindingIdentiier ClassTail
ClassDeclaration : class ClassTail

1.Returnfalse.

14.5.8 StaticSemantics:IsFunctionDeinition
ClassExpression : class BindingIdentiier ClassTail

1.Returntrue.

14.5.9 StaticSemantics:IsStatic
ClassElement : MethodDeinition

1.Returnfalse.

ClassElement : static MethodDeinition

1.Returntrue.

ClassElement : ;

1.Returnfalse.

14.5.10 StaticSemantics:NonConstructorMethodDeinitions
ClassElementList : ClassElement

1.IfClassElementistheproductionClassElement : ; ,returnanewemptyList.
2.IfIsStaticofClassElementisfalseandPropNameofClassElementis"constructor",returnanewemptyList.
3.ReturnaListcontainingClassElement.

ClassElementList : ClassElementList ClassElement

1.LetlistbeNonConstructorMethodDeinitionsofClassElementList.
2.IfClassElementistheproductionClassElement : ; ,returnlist.
3.IfIsStaticofClassElementisfalseandPropNameofClassElementis"constructor",returnlist.
4.AppendClassElementtotheendoflist.
5.Returnlist.

14.5.11 StaticSemantics:PrototypePropertyNameList
ClassElementList : ClassElement

1.IfPropNameofClassElementisempty,returnanewemptyList.
2.IfIsStaticofClassElementistrue,returnanewemptyList.
3.ReturnaListcontainingPropNameofClassElement.

ClassElementList : ClassElementList ClassElement

1.LetlistbePrototypePropertyNameListofClassElementList.
2.IfPropNameofClassElementisempty,returnlist.
3.IfIsStaticofClassElementistrue,returnlist.
4.AppendPropNameofClassElementtotheendoflist.
5.Returnlist.

14.5.12 StaticSemantics:PropName
ClassElement : ;

1.Returnempty.

14.5.13 StaticSemantics:StaticPropertyNameList
ClassElementList : ClassElement

1.IfPropNameofClassElementisempty,returnanewemptyList.
2.IfIsStaticofClassElementisfalse,returnanewemptyList.
3.ReturnaListcontainingPropNameofClassElement.

ClassElementList : ClassElementList ClassElement

1.LetlistbeStaticPropertyNameListofClassElementList.
2.IfPropNameofClassElementisempty,returnlist.
3.IfIsStaticofClassElementisfalse,returnlist.
4.AppendPropNameofClassElementtotheendoflist.
5.Returnlist.

14.5.14 RuntimeSemantics:ClassDeinitionEvaluation

WithparameterclassName.

ClassTail : ClassHeritage { ClassBody }

1.LetlexbetheLexicalEnvironmentoftherunningexecutioncontext.
2.LetclassScopebeNewDeclarativeEnvironment(lex).
3.LetclassScopeEnvRecbeclassScope'sEnvironmentRecord.
4.IfclassNameisnotundeined,then
a.PerformclassScopeEnvRec.CreateImmutableBinding(className,true).
5.IfClassHeritageopt isnotpresent,then
a.LetprotoParentbetheintrinsicobject%ObjectPrototype%.
b.LetconstructorParentbetheintrinsicobject%FunctionPrototype%.
6.Else,
a.Settherunningexecutioncontext'sLexicalEnvironmenttoclassScope.
b.LetsuperclassbetheresultofevaluatingClassHeritage.
c.Settherunningexecutioncontext'sLexicalEnvironmenttolex.
d.ReturnIfAbrupt(superclass).
e.Ifsuperclassisnull,then
i.LetprotoParentbenull.
ii.LetconstructorParentbetheintrinsicobject%FunctionPrototype%.
f.ElseifIsConstructor(superclass)isfalse,throwaTypeErrorexception.
g.Else,
i.LetprotoParentbe?Get(superclass,"prototype").
ii.IfType(protoParent)isneitherObjectnorNull,throwaTypeErrorexception.
iii.LetconstructorParentbesuperclass.
7.LetprotobeObjectCreate(protoParent).
8.IfClassBodyopt isnotpresent,letconstructorbeempty.
9.Else,letconstructorbeConstructorMethodofClassBody.
10.Ifconstructorisempty,then
a.IfClassHeritageopt ispresent,then
i.Letconstructorbetheresultofparsingthesourcetext

constructor(...args){super(...args);}

usingthesyntacticgrammarwiththegoalsymbolMethodDeinition.
b.Else,
i.Letconstructorbetheresultofparsingthesourcetext

constructor(){}

usingthesyntacticgrammarwiththegoalsymbolMethodDeinition.
11.Settherunningexecutioncontext'sLexicalEnvironmenttoclassScope.
12.LetconstructorInfobetheresultofperformingDeineMethodforconstructorwithargumentsprotoand
constructorParentastheoptionalfunctionPrototypeargument.
13.Assert:constructorInfoisnotanabruptcompletion.
14.LetFbeconstructorInfo.[[Closure]].
15.IfClassHeritageopt ispresent,setF's[[ConstructorKind]]internalslotto"derived".
16.PerformMakeConstructor(F,false,proto).
17.PerformMakeClassConstructor(F).
18.PerformCreateMethodProperty(proto,"constructor",F).
19.IfClassBodyopt isnotpresent,letmethodsbeanewemptyList.
20.Else,letmethodsbeNonConstructorMethodDeinitionsofClassBody.
21.ForeachClassElementminorderfrommethods
a.IfIsStaticofmisfalse,then
i.LetstatusbetheresultofperformingPropertyDeinitionEvaluationformwithargumentsprotoandfalse.
b.Else,
i.LetstatusbetheresultofperformingPropertyDeinitionEvaluationformwithargumentsFandfalse.
c.Ifstatusisanabruptcompletion,then
i.Settherunningexecutioncontext'sLexicalEnvironmenttolex.
ii.ReturnCompletion(status).
22.Settherunningexecutioncontext'sLexicalEnvironmenttolex.
23.IfclassNameisnotundeined,then
a.PerformclassScopeEnvRec.InitializeBinding(className,F).
24.ReturnF.

14.5.15 RuntimeSemantics:BindingClassDeclarationEvaluation
ClassDeclaration : class BindingIdentiier ClassTail

1.LetclassNamebeStringValueofBindingIdentiier.
2.LetvaluebetheresultofClassDeinitionEvaluationofClassTailwithargumentclassName.
3.ReturnIfAbrupt(value).
4.LethasNamePropertybe?HasOwnProperty(value,"name").
5.IfhasNamePropertyisfalse,performSetFunctionName(value,className).
6.Letenvbetherunningexecutioncontext'sLexicalEnvironment.
7.Perform?InitializeBoundName(className,value,env).
8.Returnvalue.

ClassDeclaration : class ClassTail

1.ReturntheresultofClassDeinitionEvaluationofClassTailwithargumentundeined.

NOTE ClassDeclaration : class ClassTail onlyoccursaspartofanExportDeclarationandthesettingofaname


propertyandestablishingitsbindingarehandledaspartoftheevaluationactionforthatproduction.See
15.2.3.11.

14.5.16 RuntimeSemantics:Evaluation
ClassDeclaration : class BindingIdentiier ClassTail

1.LetstatusbetheresultofBindingClassDeclarationEvaluationofthisClassDeclaration.
2.ReturnIfAbrupt(status).
3.ReturnNormalCompletion(empty).

NOTE1 ClassDeclaration : class ClassTail onlyoccursaspartofanExportDeclarationandisneverdirectly


evaluated.

ClassExpression : class BindingIdentiier ClassTail

1.IfBindingIdentiieropt isnotpresent,letclassNamebeundeined.
2.Else,letclassNamebeStringValueofBindingIdentiier.
3.LetvaluebetheresultofClassDeinitionEvaluationofClassTailwithargumentclassName.
4.ReturnIfAbrupt(value).
5.IfclassNameisnotundeined,then
a.LethasNamePropertybe?HasOwnProperty(value,"name").
b.IfhasNamePropertyisfalse,then
i.PerformSetFunctionName(value,className).
6.ReturnNormalCompletion(value).

NOTE2 Iftheclassdeinitionincludedanamestaticmethodthenthatmethodisnotoverwrittenwithanamedata
propertyfortheclassname.

14.6 TailPositionCalls
14.6.1 StaticSemantics:IsInTailPosition(nonterminal)

TheabstractoperationIsInTailPositionwithargumentnonterminalperformsthefollowingsteps:

1.Assert:nonterminalisaparsedgrammarproduction.
2.Ifthesourcecodematchingnonterminalisnotstrictcode,returnfalse.
3.IfnonterminalisnotcontainedwithinaFunctionBodyorConciseBody,returnfalse.
4.LetbodybetheFunctionBodyorConciseBodythatmostcloselycontainsnonterminal.
5.IfbodyistheFunctionBodyofaGeneratorBody,returnfalse.
6.ReturntheresultofHasProductionInTailPositionofbodywithargumentnonterminal.

NOTE TailPositioncallsareonlydeinedinstrictmodecodebecauseofacommonnonstandardlanguageextension
(see9.2.7)thatenablesobservationofthechainofcallercontexts.

14.6.2 StaticSemantics:HasProductionInTailPosition
Withparameternonterminal.

NOTE nonterminalisaparsedgrammarproductionthatrepresentsaspeciicrangeofsourcetext.Whenthe
followingalgorithmscomparenonterminaltoothergrammarsymbolstheyaretestingwhetherthesame
sourcetextwasmatchedbybothsymbols.

14.6.2.1 StatementRules

ConciseBody : AssignmentExpression

1.ReturnHasProductionInTailPositionofAssignmentExpressionwithargumentnonterminal.

StatementList : StatementList StatementListItem

1.LethasbeHasProductionInTailPositionofStatementListwithargumentnonterminal.
2.Ifhasistrue,returntrue.
3.ReturnHasProductionInTailPositionofStatementListItemwithargumentnonterminal.

FunctionStatementList : [empty]
StatementListItem : Declaration

Statement :
VariableStatement
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ThrowStatement
DebuggerStatement

Block : { }
ReturnStatement : return ;
LabelledItem : FunctionDeclaration

IterationStatement :
for ( LeftHandSideExpression in Expression ) Statement
for ( var ForBinding in Expression ) Statement
for ( ForDeclaration in Expression ) Statement
for ( LeftHandSideExpression of AssignmentExpression ) Statement
for ( var ForBinding of AssignmentExpression ) Statement
for ( ForDeclaration of AssignmentExpression ) Statement

CaseBlock : { }

1.Returnfalse.

IfStatement : if ( Expression ) Statement else Statement

1.LethasbeHasProductionInTailPositionoftheirstStatementwithargumentnonterminal.
2.Ifhasistrue,returntrue.
3.ReturnHasProductionInTailPositionofthesecondStatementwithargumentnonterminal.

IfStatement : if ( Expression ) Statement

IterationStatement :
do Statement while ( Expression ) ;
while ( Expression ) Statement
for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

WithStatement : with ( Expression ) Statement

1.ReturnHasProductionInTailPositionofStatementwithargumentnonterminal.

LabelledStatement :
LabelIdentiier : LabelledItem

1.ReturnHasProductionInTailPositionofLabelledItemwithargumentnonterminal.

ReturnStatement : return Expression ;

1.ReturnHasProductionInTailPositionofExpressionwithargumentnonterminal.

SwitchStatement : switch ( Expression ) CaseBlock

1.ReturnHasProductionInTailPositionofCaseBlockwithargumentnonterminal.

CaseBlock : { CaseClauses DefaultClause CaseClauses }

1.Lethasbefalse.
2.IftheirstCaseClausesispresent,lethasbeHasProductionInTailPositionoftheirstCaseClauseswithargument
nonterminal.
3.Ifhasistrue,returntrue.
4.LethasbeHasProductionInTailPositionoftheDefaultClausewithargumentnonterminal.
5.Ifhasistrue,returntrue.
6.IfthesecondCaseClausesispresent,lethasbeHasProductionInTailPositionofthesecondCaseClauseswithargument
nonterminal.
7.Returnhas.

CaseClauses : CaseClauses CaseClause

1.LethasbeHasProductionInTailPositionofCaseClauseswithargumentnonterminal.
2.Ifhasistrue,returntrue.
3.ReturnHasProductionInTailPositionofCaseClausewithargumentnonterminal.

CaseClause : case Expression : StatementList


DefaultClause : default : StatementList

1.IfStatementListispresent,returnHasProductionInTailPositionofStatementListwithargumentnonterminal.
2.Returnfalse.

TryStatement : try Block Catch

1.ReturnHasProductionInTailPositionofCatchwithargumentnonterminal.

TryStatement : try Block Finally


TryStatement : try Block Catch Finally

1.ReturnHasProductionInTailPositionofFinallywithargumentnonterminal.

Catch : catch ( CatchParameter ) Block

1.ReturnHasProductionInTailPositionofBlockwithargumentnonterminal.

14.6.2.2 ExpressionRules

NOTE ApotentialtailpositioncallthatisimmediatelyfollowedbyreturnGetValueofthecallresultisalsoapossible
tailpositioncall.Functioncallscannotreturnreferencevalues,sosuchaGetValueoperationwillalways
returnsthesamevalueastheactualfunctioncallresult.
AssignmentExpression :
YieldExpression
ArrowFunction
LeftHandSideExpression = AssignmentExpression
LeftHandSideExpression AssignmentOperator AssignmentExpression

BitwiseANDExpression : BitwiseANDExpression & EqualityExpression


BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression

EqualityExpression :
EqualityExpression == RelationalExpression
EqualityExpression != RelationalExpression
EqualityExpression === RelationalExpression
EqualityExpression !== RelationalExpression

RelationalExpression :
RelationalExpression < ShiftExpression
RelationalExpression > ShiftExpression
RelationalExpression <= ShiftExpression
RelationalExpression >= ShiftExpression
RelationalExpression instanceof ShiftExpression
RelationalExpression in ShiftExpression

ShiftExpression :
ShiftExpression << AdditiveExpression
ShiftExpression >> AdditiveExpression
ShiftExpression >>> AdditiveExpression

AdditiveExpression :
AdditiveExpression + MultiplicativeExpression
AdditiveExpression MultiplicativeExpression

MultiplicativeExpression :
MultiplicativeExpression MultiplicativeOperator ExponentiationExpression

ExponentiationExpression :
UpdateExpression ** ExponentiationExpression

UpdateExpression :
LeftHandSideExpression ++
LeftHandSideExpression
++ UnaryExpression
UnaryExpression

UnaryExpression :
delete UnaryExpression
void UnaryExpression
typeof UnaryExpression
+ UnaryExpression
UnaryExpression
~ UnaryExpression
! UnaryExpression

CallExpression :
SuperCall
CallExpression [ Expression ]
CallExpression . IdentiierName

NewExpression : new NewExpression

MemberExpression :
MemberExpression [ Expression ]
MemberExpression . IdentiierName
SuperProperty
MetaProperty
new MemberExpression Arguments

PrimaryExpression :
this
IdentiierReference
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
RegularExpressionLiteral
TemplateLiteral

1.Returnfalse.

Expression :
AssignmentExpression
Expression , AssignmentExpression

1.ReturnHasProductionInTailPositionofAssignmentExpressionwithargumentnonterminal.

ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression

1.LethasbeHasProductionInTailPositionoftheirstAssignmentExpressionwithargumentnonterminal.
2.Ifhasistrue,returntrue.
3.ReturnHasProductionInTailPositionofthesecondAssignmentExpressionwithargumentnonterminal.

LogicalANDExpression : LogicalANDExpression && BitwiseORExpression

1.ReturnHasProductionInTailPositionofBitwiseORExpressionwithargumentnonterminal.

LogicalORExpression : LogicalORExpression || LogicalANDExpression

1.ReturnHasProductionInTailPositionofLogicalANDExpressionwithargumentnonterminal.

CallExpression :
MemberExpression Arguments
CallExpression Arguments
CallExpression TemplateLiteral

1.IfthisCallExpressionisnonterminal,returntrue.
2.Returnfalse.

MemberExpression :
MemberExpression TemplateLiteral

1.IfthisMemberExpressionisnonterminal,returntrue.
2.Returnfalse.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

1.LetexprbeCoveredParenthesizedExpressionofCoverParenthesizedExpressionAndArrowParameterList.
2.ReturnHasProductionInTailPositionofexprwithargumentnonterminal.

ParenthesizedExpression :
( Expression )

1.ReturnHasProductionInTailPositionofExpressionwithargumentnonterminal.

14.6.3 RuntimeSemantics:PrepareForTailCall()

TheabstractoperationPrepareForTailCallperformsthefollowingsteps:

1.LetleafContextbetherunningexecutioncontext.
2.SuspendleafContext.
3.PopleafContextfromtheexecutioncontextstack.Theexecutioncontextnowonthetopofthestackbecomesthe
runningexecutioncontext.
4.Assert:leafContexthasnofurtheruse.Itwillneverbeactivatedastherunningexecutioncontext.

Atailpositioncallmusteitherreleaseanytransientinternalresourcesassociatedwiththecurrentlyexecutingfunction
executioncontextbeforeinvokingthetargetfunctionorreusethoseresourcesinsupportofthetargetfunction.

NOTE Forexample,atailpositioncallshouldonlygrowanimplementation'sactivationrecordstackbytheamount
thatthesizeofthetargetfunction'sactivationrecordexceedsthesizeofthecallingfunction'sactivation
record.Ifthetargetfunction'sactivationrecordissmaller,thenthetotalsizeofthestackshoulddecrease.

15 ECMAScriptLanguage:ScriptsandModules
15.1 Scripts
Syntax

Script :
ScriptBodyopt

ScriptBody :
StatementList

15.1.1 StaticSemantics:EarlyErrors
Script : ScriptBody

ItisaSyntaxErroriftheLexicallyDeclaredNamesofScriptBodycontainsanyduplicateentries.
ItisaSyntaxErrorifanyelementoftheLexicallyDeclaredNamesofScriptBodyalsooccursintheVarDeclaredNamesof
ScriptBody.

ScriptBody : StatementList

ItisaSyntaxErrorifStatementListContainssuperunlessthesourcecodecontainingsuperisevalcodethatisbeing
processedbyadirectevalthatiscontainedinfunctioncodethatisnotthefunctioncodeofanArrowFunction.
ItisaSyntaxErrorifStatementListContainsNewTargetunlessthesourcecodecontainingNewTargetisevalcodethatis
beingprocessedbyadirectevalthatiscontainedinfunctioncodethatisnotthefunctioncodeofanArrowFunction.
ItisaSyntaxErrorifContainsDuplicateLabelsofStatementListwithargumentistrue.
ItisaSyntaxErrorifContainsUndeinedBreakTargetofStatementListwithargumentistrue.
ItisaSyntaxErrorifContainsUndeinedContinueTargetofStatementListwithargumentsandistrue.
15.1.2 StaticSemantics:IsStrict
ScriptBody : StatementList

1.IftheDirectivePrologueofStatementListcontainsaUseStrictDirective,returntrue;otherwise,returnfalse.

15.1.3 StaticSemantics:LexicallyDeclaredNames
ScriptBody : StatementList

1.ReturnTopLevelLexicallyDeclaredNamesofStatementList.

NOTE AtthetoplevelofaScript,functiondeclarationsaretreatedlikevardeclarationsratherthanlikelexical
declarations.

15.1.4 StaticSemantics:LexicallyScopedDeclarations
ScriptBody : StatementList

1.ReturnTopLevelLexicallyScopedDeclarationsofStatementList.

15.1.5 StaticSemantics:VarDeclaredNames
ScriptBody : StatementList

1.ReturnTopLevelVarDeclaredNamesofStatementList.

15.1.6 StaticSemantics:VarScopedDeclarations
ScriptBody : StatementList

1.ReturnTopLevelVarScopedDeclarationsofStatementList.

15.1.7 RuntimeSemantics:Evaluation
Script : [empty]

1.ReturnNormalCompletion(undeined).

15.1.8 ScriptRecords

AScriptRecordencapsulatesinformationaboutascriptbeingevaluated.EachscriptrecordcontainstheieldslistedinTable
36.

Table36:ScriptRecordFields
FieldName ValueType Meaning

[[Realm]] RealmRecord| Therealmwithinwhichthisscriptwascreated.undeinedifnotyet


undeined assigned.

[[Environment]] LexicalEnvironment TheLexicalEnvironmentcontainingthetoplevelbindingsforthisscript.This


|undeined ieldissetwhenthescriptisinstantiated.

[[ECMAScriptCode]] aparseresult TheresultofparsingthesourcetextofthismoduleusingScriptasthegoal


symbol.

[[HostDeined]] Any,defaultvalueis Fieldreservedforusebyhostenvironmentsthatneedtoassociateadditional


undeined. informationwithascript.

15.1.9 ParseScript(sourceText,realm,hostDeined)
TheabstractoperationParseScriptwithargumentssourceText,realm,andhostDeinedcreatesaScriptRecordbasedupon
theresultofparsingsourceTextasaScript.ParseScriptperformsthefollowingsteps:

1.Assert:sourceTextisanECMAScriptsourcetext(seeclause10).
2.ParsesourceTextusingScriptasthegoalsymbolandanalyzetheparseresultforanyEarlyErrorconditions.Iftheparse
wassuccessfulandnoearlyerrorswerefound,letbodybetheresultingparsetree.Otherwise,letbodybeaListofone
ormoreSyntaxErrororReferenceErrorobjectsrepresentingtheparsingerrorsand/orearlyerrors.Parsingandearly
errordetectionmaybeinterweavedinanimplementationdependentmanner.Ifmorethanoneparsingerrororearly
errorispresent,thenumberandorderingoferrorobjectsinthelistisimplementationdependent,butatleastonemust
bepresent.
3.IfbodyisaListoferrors,thenreturnbody.
4.ReturnScriptRecord{[[Realm]]:realm,[[Environment]]:undeined,[[ECMAScriptCode]]:body,[[HostDeined]]:
hostDeined}.

NOTE AnimplementationmayparsescriptsourcetextandanalyzeitforEarlyErrorconditionspriortoevaluationof
ParseScriptforthatscriptsourcetext.However,thereportingofanyerrorsmustbedeferreduntilthepoint
wherethisspeciicationactuallyperformsParseScriptuponthatsourcetext.

15.1.10 ScriptEvaluation(scriptRecord)

1.LetglobalEnvbescriptRecord.[[Realm]].[[GlobalEnv]].
2.LetscriptCxtbeanewECMAScriptcodeexecutioncontext.
3.SettheFunctionofscriptCxttonull.
4.SettheRealmofscriptCxttoscriptRecord.[[Realm]].
5.SettheScriptOrModuleofscriptCxttoscriptRecord.
6.SettheVariableEnvironmentofscriptCxttoglobalEnv.
7.SettheLexicalEnvironmentofscriptCxttoglobalEnv.
8.Suspendthecurrentlyrunningexecutioncontext.
9.PushscriptCxtontotheexecutioncontextstack;scriptCxtisnowtherunningexecutioncontext.
10.LetresultbeGlobalDeclarationInstantiation(ScriptBody,globalEnv).
11.Ifresult.[[Type]]isnormal,then
a.LetresultbetheresultofevaluatingScriptBody.
12.Ifresult.[[Type]]isnormalandresult.[[Value]]isempty,then
a.LetresultbeNormalCompletion(undeined).
13.SuspendscriptCxtandremoveitfromtheexecutioncontextstack.
14.Assert:theexecutioncontextstackisnotempty.
15.Resumethecontextthatisnowonthetopoftheexecutioncontextstackastherunningexecutioncontext.
16.ReturnCompletion(result).

15.1.11 RuntimeSemantics:GlobalDeclarationInstantiation(script,env)

NOTE1 Whenanexecutioncontextisestablishedforevaluatingscripts,declarationsareinstantiatedinthecurrent
globalenvironment.Eachglobalbindingdeclaredinthecodeisinstantiated.

GlobalDeclarationInstantiationisperformedasfollowsusingargumentsscriptandenv.scriptistheScriptBodyforwhichthe
executioncontextisbeingestablished.envisthegloballexicalenvironmentinwhichbindingsaretobecreated.

1.LetenvRecbeenv'sEnvironmentRecord.
2.Assert:envRecisaglobalEnvironmentRecord.
3.LetlexNamesbetheLexicallyDeclaredNamesofscript.
4.LetvarNamesbetheVarDeclaredNamesofscript.
5.ForeachnameinlexNames,do
a.IfenvRec.HasVarDeclaration(name)istrue,throwaSyntaxErrorexception.
b.IfenvRec.HasLexicalDeclaration(name)istrue,throwaSyntaxErrorexception.
c.LethasRestrictedGlobalbe?envRec.HasRestrictedGlobalProperty(name).
d.IfhasRestrictedGlobalistrue,throwaSyntaxErrorexception.
6.ForeachnameinvarNames,do
a.IfenvRec.HasLexicalDeclaration(name)istrue,throwaSyntaxErrorexception.
7.LetvarDeclarationsbetheVarScopedDeclarationsofscript.
8.LetfunctionsToInitializebeanewemptyList.
9.LetdeclaredFunctionNamesbeanewemptyList.
10.ForeachdinvarDeclarations,inreverselistorderdo
a.IfdisneitheraVariableDeclarationoraForBinding,then
i.Assert:diseitheraFunctionDeclarationoraGeneratorDeclaration.
ii.NOTEIftherearemultipleFunctionDeclarationsforthesamename,thelastdeclarationisused.
iii.LetfnbethesoleelementoftheBoundNamesofd.
iv.IffnisnotanelementofdeclaredFunctionNames,then
1.LetfnDeinablebe?envRec.CanDeclareGlobalFunction(fn).
2.IffnDeinableisfalse,throwaTypeErrorexception.
3.AppendfntodeclaredFunctionNames.
4.InsertdastheirstelementoffunctionsToInitialize.
11.LetdeclaredVarNamesbeanewemptyList.
12.ForeachdinvarDeclarations,do
a.IfdisaVariableDeclarationoraForBinding,then
i.ForeachStringvnintheBoundNamesofd,do
1.IfvnisnotanelementofdeclaredFunctionNames,then
a.LetvnDeinablebe?envRec.CanDeclareGlobalVar(vn).
b.IfvnDeinableisfalse,throwaTypeErrorexception.
c.IfvnisnotanelementofdeclaredVarNames,then
i.AppendvntodeclaredVarNames.
13.NOTE:Noabnormalterminationsoccurafterthisalgorithmstepiftheglobalobjectisanordinaryobject.However,if
theglobalobjectisaProxyexoticobjectitmayexhibitbehavioursthatcauseabnormalterminationsinsomeofthe
followingsteps.
14.NOTE:AnnexB.3.3.2addsadditionalstepsatthispoint.
15.LetlexDeclarationsbetheLexicallyScopedDeclarationsofscript.
16.ForeachelementdinlexDeclarationsdo
a.NOTELexicallydeclarednamesareonlyinstantiatedherebutnotinitialized.
b.ForeachelementdnoftheBoundNamesofddo
i.IfIsConstantDeclarationofdistrue,then
1.Perform?envRec.CreateImmutableBinding(dn,true).
ii.Else,
1.Perform?envRec.CreateMutableBinding(dn,false).
17.ForeachproductionfinfunctionsToInitialize,do
a.LetfnbethesoleelementoftheBoundNamesoff.
b.LetfobetheresultofperformingInstantiateFunctionObjectforfwithargumentenv.
c.Perform?envRec.CreateGlobalFunctionBinding(fn,fo,false).
18.ForeachStringvnindeclaredVarNames,inlistorderdo
a.Perform?envRec.CreateGlobalVarBinding(vn,false).
19.ReturnNormalCompletion(empty).

NOTE2 Earlyerrorsspeciiedin15.1.1preventnameconlictsbetweenfunction/vardeclarationsandlet/const/class
declarationsaswellasredeclarationoflet/const/classbindingsfordeclarationcontainedwithinasingleScript
.However,suchconlictsandredeclarationsthatspanmorethanoneScriptaredetectedasruntimeerrors
duringGlobalDeclarationInstantiation.Ifanysucherrorsaredetected,nobindingsareinstantiatedforthe
script.However,iftheglobalobjectisdeinedusingProxyexoticobjectsthentheruntimetestsforconlicting
declarationsmaybeunreliableresultinginanabruptcompletionandsomeglobaldeclarationsnotbeing
instantiated.Ifthisoccurs,thecodefortheScriptisnotevaluated.

Unlikeexplicitvarorfunctiondeclarations,propertiesthataredirectlycreatedontheglobalobjectresultin
globalbindingsthatmaybeshadowedbylet/const/classdeclarations.
15.1.12 RuntimeSemantics:ScriptEvaluationJob(sourceText,hostDeined)

ThejobScriptEvaluationJobwithparameterssourceTextandhostDeinedparses,validates,andevaluatessourceTextasa
Script.

1.Assert:sourceTextisanECMAScriptsourcetext(seeclause10).
2.LetrealmbethecurrentRealmRecord.
3.LetsbeParseScript(sourceText,realm,hostDeined).
4.IfsisaListoferrors,then
a.PerformHostReportErrors(s).
b.NextJobNormalCompletion(undeined).
5.LetstatusbeScriptEvaluation(s).
6.NextJobCompletion(status).

15.2 Modules
Syntax

Module :
ModuleBodyopt

ModuleBody :
ModuleItemList

ModuleItemList :
ModuleItem
ModuleItemList ModuleItem

ModuleItem :
ImportDeclaration
ExportDeclaration
StatementListItem

15.2.1 ModuleSemantics

15.2.1.1 StaticSemantics:EarlyErrors

ModuleBody : ModuleItemList

ItisaSyntaxErroriftheLexicallyDeclaredNamesofModuleItemListcontainsanyduplicateentries.
ItisaSyntaxErrorifanyelementoftheLexicallyDeclaredNamesofModuleItemListalsooccursinthe
VarDeclaredNamesofModuleItemList.
ItisaSyntaxErroriftheExportedNamesofModuleItemListcontainsanyduplicateentries.
ItisaSyntaxErrorifanyelementoftheExportedBindingsofModuleItemListdoesnotalsooccurineitherthe
VarDeclaredNamesofModuleItemList,ortheLexicallyDeclaredNamesofModuleItemList.
ItisaSyntaxErrorifModuleItemListcontainssuper.
ItisaSyntaxErrorifModuleItemListcontainsNewTarget.
ItisaSyntaxErrorifContainsDuplicateLabelsofModuleItemListwithargumentistrue.
ItisaSyntaxErrorifContainsUndeinedBreakTargetofModuleItemListwithargumentistrue.
ItisaSyntaxErrorifContainsUndeinedContinueTargetofModuleItemListwithargumentsandistrue.

NOTE TheduplicateExportedNamesruleimpliesthatmultipleexportdefaultExportDeclarationitemswithina
ModuleBodyisaSyntaxError.Additionalerrorconditionsrelatingtoconlictingorduplicatedeclarationsare
checkedduringmodulelinkingpriortoevaluationofaModule.IfanysucherrorsaredetectedtheModuleis
notevaluated.

15.2.1.2 StaticSemantics:ContainsDuplicateLabels
WithargumentlabelSet.

ModuleItemList : ModuleItemList ModuleItem

1.LethasDuplicatesbeContainsDuplicateLabelsofModuleItemListwithargumentlabelSet.
2.IfhasDuplicatesistrue,returntrue.
3.ReturnContainsDuplicateLabelsofModuleItemwithargumentlabelSet.

ModuleItem :
ImportDeclaration
ExportDeclaration

1.Returnfalse.

15.2.1.3 StaticSemantics:ContainsUndeinedBreakTarget

WithargumentlabelSet.

ModuleItemList : ModuleItemList ModuleItem

1.LethasUndeinedLabelsbeContainsUndeinedBreakTargetofModuleItemListwithargumentlabelSet.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedBreakTargetofModuleItemwithargumentlabelSet.

ModuleItem :
ImportDeclaration
ExportDeclaration

1.Returnfalse.

15.2.1.4 StaticSemantics:ContainsUndeinedContinueTarget

WithargumentsiterationSetandlabelSet.

ModuleItemList : ModuleItemList ModuleItem

1.LethasUndeinedLabelsbeContainsUndeinedContinueTargetofModuleItemListwithargumentsiterationSetand.
2.IfhasUndeinedLabelsistrue,returntrue.
3.ReturnContainsUndeinedContinueTargetofModuleItemwithargumentsiterationSetand.

ModuleItem :
ImportDeclaration
ExportDeclaration

1.Returnfalse.

15.2.1.5 StaticSemantics:ExportedBindings

NOTE ExportedBindingsarethelocallyboundnamesthatareexplicitlyassociatedwithaModule'sExportedNames.

ModuleItemList : ModuleItemList ModuleItem

1.LetnamesbeExportedBindingsofModuleItemList.
2.AppendtonamestheelementsoftheExportedBindingsofModuleItem.
3.Returnnames.

ModuleItem :
ImportDeclaration
StatementListItem

1.ReturnanewemptyList.
15.2.1.6 StaticSemantics:ExportedNames

NOTE ExportedNamesaretheexternallyvisiblenamesthataModuleexplicitlymapstooneofitslocalname
bindings.

ModuleItemList : ModuleItemList ModuleItem

1.LetnamesbeExportedNamesofModuleItemList.
2.AppendtonamestheelementsoftheExportedNamesofModuleItem.
3.Returnnames.

ModuleItem : ExportDeclaration

1.ReturntheExportedNamesofExportDeclaration.

ModuleItem :
ImportDeclaration
StatementListItem

1.ReturnanewemptyList.

15.2.1.7 StaticSemantics:ExportEntries

Module : [empty]

1.ReturnanewemptyList.

ModuleItemList : ModuleItemList ModuleItem

1.LetentriesbeExportEntriesofModuleItemList.
2.AppendtoentriestheelementsoftheExportEntriesofModuleItem.
3.Returnentries.

ModuleItem :
ImportDeclaration
StatementListItem

1.ReturnanewemptyList.

15.2.1.8 StaticSemantics:ImportEntries

Module : [empty]

1.ReturnanewemptyList.

ModuleItemList : ModuleItemList ModuleItem

1.LetentriesbeImportEntriesofModuleItemList.
2.AppendtoentriestheelementsoftheImportEntriesofModuleItem.
3.Returnentries.

ModuleItem :
ExportDeclaration
StatementListItem

1.ReturnanewemptyList.

15.2.1.9 StaticSemantics:ImportedLocalNames(importEntries)

TheabstractoperationImportedLocalNameswithargumentimportEntriescreatesaListofallofthelocalnamebindings
deinedbyaListofImportEntryRecords(seeTable40).ImportedLocalNamesperformsthefollowingsteps:
1.LetlocalNamesbeanewemptyList.
2.ForeachImportEntryRecordiinimportEntries,do
a.Appendi.[[LocalName]]tolocalNames.
3.ReturnlocalNames.

15.2.1.10 StaticSemantics:ModuleRequests

Module : [empty]

1.ReturnanewemptyList.

ModuleItemList : ModuleItem

1.ReturnModuleRequestsofModuleItem.

ModuleItemList : ModuleItemList ModuleItem

1.LetmoduleNamesbeModuleRequestsofModuleItemList.
2.LetadditionalNamesbeModuleRequestsofModuleItem.
3.AppendtomoduleNameseachelementofadditionalNamesthatisnotalreadyanelementofmoduleNames.
4.ReturnmoduleNames.

ModuleItem : StatementListItem

1.ReturnanewemptyList.

15.2.1.11 StaticSemantics:LexicallyDeclaredNames

NOTE1 TheLexicallyDeclaredNamesofaModuleincludesthenamesofallofitsimportedbindings.

ModuleItemList : ModuleItemList ModuleItem

1.LetnamesbeLexicallyDeclaredNamesofModuleItemList.
2.AppendtonamestheelementsoftheLexicallyDeclaredNamesofModuleItem.
3.Returnnames.

ModuleItem : ImportDeclaration

1.ReturntheBoundNamesofImportDeclaration.

ModuleItem : ExportDeclaration

1.IfExportDeclarationisexportVariableStatement,returnanewemptyList.
2.ReturntheBoundNamesofExportDeclaration.

ModuleItem : StatementListItem

1.ReturnLexicallyDeclaredNamesofStatementListItem.

NOTE2 AtthetoplevelofaModule,functiondeclarationsaretreatedlikelexicaldeclarationsratherthanlikevar
declarations.

15.2.1.12 StaticSemantics:LexicallyScopedDeclarations

Module : [empty]

1.ReturnanewemptyList.

ModuleItemList : ModuleItemList ModuleItem

1.LetdeclarationsbeLexicallyScopedDeclarationsofModuleItemList.
2.AppendtodeclarationstheelementsoftheLexicallyScopedDeclarationsofModuleItem.
3.Returndeclarations.

ModuleItem : ImportDeclaration

1.ReturnanewemptyList.

15.2.1.13 StaticSemantics:VarDeclaredNames

Module : [empty]

1.ReturnanewemptyList.

ModuleItemList : ModuleItemList ModuleItem

1.LetnamesbeVarDeclaredNamesofModuleItemList.
2.AppendtonamestheelementsoftheVarDeclaredNamesofModuleItem.
3.Returnnames.

ModuleItem : ImportDeclaration

1.ReturnanewemptyList.

ModuleItem : ExportDeclaration

1.IfExportDeclarationisexportVariableStatement,returnBoundNamesofExportDeclaration.
2.ReturnanewemptyList.

15.2.1.14 StaticSemantics:VarScopedDeclarations

Module : [empty]

1.ReturnanewemptyList.

ModuleItemList : ModuleItemList ModuleItem

1.LetdeclarationsbeVarScopedDeclarationsofModuleItemList.
2.AppendtodeclarationstheelementsoftheVarScopedDeclarationsofModuleItem.
3.Returndeclarations.

ModuleItem : ImportDeclaration

1.ReturnanewemptyList.

ModuleItem : ExportDeclaration

1.IfExportDeclarationisexportVariableStatement,returnVarScopedDeclarationsofVariableStatement.
2.ReturnanewemptyList.

15.2.1.15 AbstractModuleRecords

AModuleRecordencapsulatesstructuralinformationabouttheimportsandexportsofasinglemodule.Thisinformationis
usedtolinktheimportsandexportsofsetsofconnectedmodules.AModuleRecordincludesfourieldsthatareonlyused
whenevaluatingamodule.

ForspeciicationpurposesModuleRecordvaluesarevaluesoftheRecordspeciicationtypeandcanbethoughtofasexisting
inasimpleobjectorientedhierarchywhereModuleRecordisanabstractclasswithconcretesubclasses.Thisspeciication
onlydeinesasingleModuleRecordconcretesubclassnamedSourceTextModuleRecord.Otherspeciicationsand
implementationsmaydeineadditionalModuleRecordsubclassescorrespondingtoalternativemoduledeinitionfacilities
thattheydeined.

ModuleRecorddeinestheieldslistedinTable37.AllModuleDeinitionsubclassesincludeatleastthoseields.Module
RecordalsodeinestheabstractmethodlistinTable38.AllModuledeinitionsubclassesmustprovideconcrete
implementationsoftheseabstractmethods.

Table37:ModuleRecordFields
FieldName ValueType Meaning

[[Realm]] RealmRecord| TheRealmwithinwhichthismodulewascreated.undeinedifnotyetassigned.


undeined

[[Environment]] Lexical TheLexicalEnvironmentcontainingthetoplevelbindingsforthismodule.This


Environment| ieldissetwhenthemoduleisinstantiated.
undeined

[[Namespace]] Object|undeined TheModuleNamespaceObject(26.3)ifonehasbeencreatedforthismodule.


Otherwiseundeined.

[[Evaluated]] Boolean Initiallyfalse,trueifevaluationofthismodulehasstarted.Remainstruewhen


evaluationcompletes,evenifitisanabruptcompletion.

[[HostDeined]] Any,defaultvalueis Fieldreservedforusebyhostenvironmentsthatneedtoassociateadditional


undeined. informationwithamodule.

Table38:AbstractMethodsofModuleRecords
Method Purpose

GetExportedNames(exportStarSet) Returnalistofallnamesthatareeitherdirectlyorindirectlyexportedfromthis
module.

ResolveExport(exportName, Returnthebindingofanameexportedbythismodule.Bindingsarerepresentedbya
resolveSet,exportStarSet) Recordoftheform{[[Module]]:ModuleRecord,[[BindingName]]:String}

ModuleDeclarationInstantiation() TransitivelyresolveallmoduledependenciesandcreateamoduleEnvironment
Recordforthemodule.

ModuleEvaluation() Donothingifthismodulehasalreadybeenevaluated.Otherwise,transitivelyevaluate
allmoduledependencesofthismoduleandthenevaluatethismodule.

ModuleDeclarationInstantiationmustbecompletedpriortoinvokingthismethod.

15.2.1.16 SourceTextModuleRecords

ASourceTextModuleRecordisusedtorepresentinformationaboutamodulethatwasdeinedfromECMAScriptsourcetext
(10)thatwasparsedusingthegoalsymbolModule.Itsieldscontaindigestedinformationaboutthenamesthatare
importedbythemoduleanditsconcretemethodsusethisdigesttolink,instantiate,andevaluatethemodule.

Inadditiontotheields,deinedinTable37,SourceTextModuleRecordshavetheadditionalieldslistedinTable39.Eachof
theseieldsinitiallyhasthevalueundeined.
Table39:AdditionalFieldsofSourceTextModuleRecords
FieldName ValueType Meaning

[[ECMAScriptCode]] aparse TheresultofparsingthesourcetextofthismoduleusingModuleasthegoal


result symbol.

[[RequestedModules]] Listof AListofalltheModuleSpeciierstringsusedbythemodulerepresentedbythis


String recordtorequesttheimportationofamodule.TheListissourcecode
occurrenceordered.

[[ImportEntries]] Listof AListofImportEntryrecordsderivedfromthecodeofthismodule.


ImportEntry
Records

[[LocalExportEntries]] Listof AListofExportEntryrecordsderivedfromthecodeofthismodulethat


ExportEntry correspondtodeclarationsthatoccurwithinthemodule.
Records

[[IndirectExportEntries]] Listof AListofExportEntryrecordsderivedfromthecodeofthismodulethat


ExportEntry correspondtoreexportedimportsthatoccurwithinthemodule.
Records

[[StarExportEntries]] Listof AListofExportEntryrecordsderivedfromthecodeofthismodulethat


ExportEntry correspondtoexport*declarationsthatoccurwithinthemodule.
Records

AnImportEntryRecordisaRecordthatdigestsinformationaboutasingledeclarativeimport.EachImportEntryRecordhas
theieldsdeinedinTable40:

Table40:ImportEntryRecordFields
FieldName Value Meaning
Type

[[ModuleRequest]] String StringvalueoftheModuleSpeciieroftheImportDeclaration.

[[ImportName]] String Thenameunderwhichthedesiredbindingisexportedbythemoduleidentiiedby


[[ModuleRequest]].Thevalue"*"indicatesthattheimportrequestisforthetargetmodule's
namespaceobject.

[[LocalName]] String Thenamethatisusedtolocallyaccesstheimportedvaluefromwithintheimportingmodule.

NOTE1 Table41givesexamplesofImportEntryrecordsieldsusedtorepresentthesyntacticimportforms:

Table41(Informative):ImportFormsMappingstoImportEntryRecords
ImportStatementForm [[ModuleRequest]] [[ImportName]] [[LocalName]]

importvfrom"mod"; "mod" "default" "v"

import*asnsfrom"mod"; "mod" "*" "ns"

import{x}from"mod"; "mod" "x" "x"

import{xasv}from"mod"; "mod" "x" "v"

import"mod"; AnImportEntryRecordisnotcreated.
AnExportEntryRecordisaRecordthatdigestsinformationaboutasingledeclarativeexport.EachExportEntryRecordhas
theieldsdeinedinTable42:

Table42:ExportEntryRecordFields
FieldName Value Meaning
Type

[[ExportName]] String Thenameusedtoexportthisbindingbythismodule.

[[ModuleRequest]] String TheStringvalueoftheModuleSpeciieroftheExportDeclaration.nulliftheExportDeclaration


|null doesnothaveaModuleSpeciier.

[[ImportName]] String Thenameunderwhichthedesiredbindingisexportedbythemoduleidentiiedby


|null [[ModuleRequest]].nulliftheExportDeclarationdoesnothaveaModuleSpeciier."*"
indicatesthattheexportrequestisforallexportedbindings.

[[LocalName]] String Thenamethatisusedtolocallyaccesstheexportedvaluefromwithintheimportingmodule.


|null nulliftheexportedvalueisnotlocallyaccessiblefromwithinthemodule.

NOTE2 Table43givesexamplesoftheExportEntryrecordieldsusedtorepresentthesyntacticexportforms:

Table43(Informative):ExportFormsMappingstoExportEntryRecords
ExportStatementForm [[ExportName]] [[ModuleRequest]] [[ImportName]] [[LocalName]]

exportvarv; "v" null null "v"

exportdefaultfunctionf(){} "default" null null "f"

exportdefaultfunction(){} "default" null null "*default*"

exportdefault42; "default" null null "*default*"

export{x}; "x" null null "x"

export{vasx}; "x" null null "v"

export{x}from"mod"; "x" "mod" "x" null

export{vasx}from"mod"; "x" "mod" "v" null

export*from"mod"; null "mod" "*" null

ThefollowingdeinitionsspecifytherequiredconcretemethodsandotherabstractoperationsforSourceTextModule
Records

15.2.1.16.1 ParseModule(sourceText,realm,hostDeined)

TheabstractoperationParseModulewithargumentssourceText,realm,andhostDeinedcreatesaSourceTextModuleRecord
basedupontheresultofparsingsourceTextasaModule.ParseModuleperformsthefollowingsteps:

1.Assert:sourceTextisanECMAScriptsourcetext(seeclause10).
2.ParsesourceTextusingModuleasthegoalsymbolandanalyzetheparseresultforanyEarlyErrorconditions.Ifthe
parsewassuccessfulandnoearlyerrorswerefound,letbodybetheresultingparsetree.Otherwise,letbodybeaListof
oneormoreSyntaxErrororReferenceErrorobjectsrepresentingtheparsingerrorsand/orearlyerrors.Parsingand
earlyerrordetectionmaybeinterweavedinanimplementationdependentmanner.Ifmorethanoneparsingerroror
earlyerrorispresent,thenumberandorderingoferrorobjectsinthelistisimplementationdependent,butatleastone
mustbepresent.
3.IfbodyisaListoferrors,thenreturnbody.
4.LetrequestedModulesbetheModuleRequestsofbody.
5.LetimportEntriesbeImportEntriesofbody.
6.LetimportedBoundNamesbeImportedLocalNames(importEntries).
7.LetindirectExportEntriesbeanewemptyList.
8.LetlocalExportEntriesbeanewemptyList.
9.LetstarExportEntriesbeanewemptyList.
10.LetexportEntriesbeExportEntriesofbody.
11.ForeachrecordeeinexportEntries,do
a.Ifee.[[ModuleRequest]]isnull,then
i.Ifee.[[LocalName]]isnotanelementofimportedBoundNames,then
1.AppendeetolocalExportEntries.
ii.Else,
1.LetiebetheelementofimportEntrieswhose[[LocalName]]isthesameasee.[[LocalName]].
2.Ifie.[[ImportName]]is"*",then
a.Assert:thisisareexportofanimportedmodulenamespaceobject.
b.AppendeetolocalExportEntries.
3.Else,thisisareexportofasinglename
a.AppendtoindirectExportEntriestheRecord{[[ModuleRequest]]:ie.[[ModuleRequest]],
[[ImportName]]:ie.[[ImportName]],[[LocalName]]:null,[[ExportName]]:ee.[[ExportName]]}.
b.Else,ifee.[[ImportName]]is"*",then
i.AppendeetostarExportEntries.
c.Else,
i.AppendeetoindirectExportEntries.
12.ReturnSourceTextModuleRecord{[[Realm]]:realm,[[Environment]]:undeined,[[HostDeined]]:hostDeined,
[[Namespace]]:undeined,[[Evaluated]]:false,[[ECMAScriptCode]]:body,[[RequestedModules]]:requestedModules,
[[ImportEntries]]:importEntries,[[LocalExportEntries]]:localExportEntries,[[StarExportEntries]]:starExportEntries,
[[IndirectExportEntries]]:indirectExportEntries}.

NOTE AnimplementationmayparsemodulesourcetextandanalyzeitforEarlyErrorconditionspriortothe
evaluationofParseModuleforthatmodulesourcetext.However,thereportingofanyerrorsmustbedeferred
untilthepointwherethisspeciicationactuallyperformsParseModuleuponthatsourcetext.

15.2.1.16.2 GetExportedNames(exportStarSet)ConcreteMethod

TheGetExportedNamesconcretemethodofaSourceTextModuleRecordwithargumentexportStarSetperformsthe
followingsteps:

1.LetmodulebethisSourceTextModuleRecord.
2.IfexportStarSetcontainsmodule,then
a.Assert:We'vereachedthestartingpointofanimport*circularity.
b.ReturnanewemptyList.
3.AppendmoduletoexportStarSet.
4.LetexportedNamesbeanewemptyList.
5.ForeachExportEntryRecordeinmodule.[[LocalExportEntries]],do
a.Assert:moduleprovidesthedirectbindingforthisexport.
b.Appende.[[ExportName]]toexportedNames.
6.ForeachExportEntryRecordeinmodule.[[IndirectExportEntries]],do
a.Assert:moduleimportsaspeciicbindingforthisexport.
b.Appende.[[ExportName]]toexportedNames.
7.ForeachExportEntryRecordeinmodule.[[StarExportEntries]],do
a.LetrequestedModulebe?HostResolveImportedModule(module,e.[[ModuleRequest]]).
b.LetstarNamesbe?requestedModule.GetExportedNames(exportStarSet).
c.ForeachelementnofstarNames,do
i.IfSameValue(n,"default")isfalse,then
1.IfnisnotanelementofexportedNames,then
a.AppendntoexportedNames.
8.ReturnexportedNames.

NOTE GetExportedNamesdoesnotilteroutorthrowanexceptionfornamesthathaveambiguousstarexport
bindings.

15.2.1.16.3 ResolveExport(exportName,resolveSet,exportStarSet)ConcreteMethod

TheResolveExportconcretemethodofaSourceTextModuleRecordwithargumentsexportName,resolveSet,and
exportStarSetperformsthefollowingsteps:

1.LetmodulebethisSourceTextModuleRecord.
2.ForeachRecord{[[Module]],[[ExportName]]}rinresolveSet,do:
a.Ifmoduleandr.[[Module]]arethesameModuleRecordandSameValue(exportName,r.[[ExportName]])istrue,
then
i.Assert:thisisacircularimportrequest.
ii.Returnnull.
3.AppendtheRecord{[[Module]]:module,[[ExportName]]:exportName}toresolveSet.
4.ForeachExportEntryRecordeinmodule.[[LocalExportEntries]],do
a.IfSameValue(exportName,e.[[ExportName]])istrue,then
i.Assert:moduleprovidesthedirectbindingforthisexport.
ii.ReturnRecord{[[Module]]:module,[[BindingName]]:e.[[LocalName]]}.
5.ForeachExportEntryRecordeinmodule.[[IndirectExportEntries]],do
a.IfSameValue(exportName,e.[[ExportName]])istrue,then
i.Assert:moduleimportsaspeciicbindingforthisexport.
ii.LetimportedModulebe?HostResolveImportedModule(module,e.[[ModuleRequest]]).
iii.LetindirectResolutionbe?importedModule.ResolveExport(e.[[ImportName]],resolveSet,exportStarSet).
iv.IfindirectResolutionisnotnull,returnindirectResolution.
6.IfSameValue(exportName,"default")istrue,then
a.Assert:Adefaultexportwasnotexplicitlydeinedbythismodule.
b.ThrowaSyntaxErrorexception.
c.NOTEAdefaultexportcannotbeprovidedbyanexport*.
7.IfexportStarSetcontainsmodule,returnnull.
8.AppendmoduletoexportStarSet.
9.LetstarResolutionbenull.
10.ForeachExportEntryRecordeinmodule.[[StarExportEntries]],do
a.LetimportedModulebe?HostResolveImportedModule(module,e.[[ModuleRequest]]).
b.Letresolutionbe?importedModule.ResolveExport(exportName,resolveSet,exportStarSet).
c.Ifresolutionis"ambiguous",return"ambiguous".
d.Ifresolutionisnotnull,then
i.IfstarResolutionisnull,letstarResolutionberesolution.
ii.Else,
1.Assert:thereismorethanone*importthatincludestherequestedname.
2.Ifresolution.[[Module]]andstarResolution.[[Module]]arenotthesameModuleRecordor
SameValue(resolution.[[BindingName]],starResolution.[[BindingName]])isfalse,return"ambiguous".
11.ReturnstarResolution.

NOTE ResolveExportattemptstoresolveanimportedbindingtotheactualdeiningmoduleandlocalbindingname.
ThedeiningmodulemaybethemodulerepresentedbytheModuleRecordthismethodwasinvokedonor
someothermodulethatisimportedbythatmodule.TheparameterresolveSetisusetodetectunresolved
circularimport/exportpaths.IfapairconsistingofspeciicModuleRecordandexportNameisreachedthatis
alreadyinresolveSet,animportcircularityhasbeenencountered.BeforerecursivelycallingResolveExport,a
pairconsistingofmoduleandexportNameisaddedtoresolveSet.

IfadeiningmoduleisfoundaRecord{[[Module]],[[BindingName]]}isreturned.Thisrecordidentiiesthe
resolvedbindingoftheoriginallyrequestedexport.Ifnodeinitionwasfoundortherequestisfoundtobe
circular,nullisreturned.Iftherequestisfoundtobeambiguous,thestring"ambiguous"isreturned.

15.2.1.16.4 ModuleDeclarationInstantiation()ConcreteMethod

TheModuleDeclarationInstantiationconcretemethodofaSourceTextModuleRecordperformsthefollowingsteps:

1.LetmodulebethisSourceTextModuleRecord.
2.Letrealmbemodule.[[Realm]].
3.Assert:realmisnotundeined.
4.Letcodebemodule.[[ECMAScriptCode]].
5.Ifmodule.[[Environment]]isnotundeined,returnNormalCompletion(empty).
6.LetenvbeNewModuleEnvironment(realm.[[GlobalEnv]]).
7.Setmodule.[[Environment]]toenv.
8.ForeachStringrequiredthatisanelementofmodule.[[RequestedModules]]do,
a.NOTE:Beforeinstantiatingamodule,allofthemodulesitrequestedmustbeavailable.Animplementationmay
performthistestatanytimepriortothispoint.
b.LetrequiredModulebe?HostResolveImportedModule(module,required).
c.Perform?requiredModule.ModuleDeclarationInstantiation().
9.ForeachExportEntryRecordeinmodule.[[IndirectExportEntries]],do
a.Letresolutionbe?module.ResolveExport(e.[[ExportName]],,).
b.Ifresolutionisnullorresolutionis"ambiguous",throwaSyntaxErrorexception.
10.Assert:allnamedexportsfrommoduleareresolvable.
11.LetenvRecbeenv'sEnvironmentRecord.
12.ForeachImportEntryRecordininmodule.[[ImportEntries]],do
a.LetimportedModulebe?HostResolveImportedModule(module,in.[[ModuleRequest]]).
b.Ifin.[[ImportName]]is"*",then
i.Letnamespacebe?GetModuleNamespace(importedModule).
ii.Perform!envRec.CreateImmutableBinding(in.[[LocalName]],true).
iii.CallenvRec.InitializeBinding(in.[[LocalName]],namespace).
c.Else,
i.Letresolutionbe?importedModule.ResolveExport(in.[[ImportName]],,).
ii.Ifresolutionisnullorresolutionis"ambiguous",throwaSyntaxErrorexception.
iii.CallenvRec.CreateImportBinding(in.[[LocalName]],resolution.[[Module]],resolution.[[BindingName]]).
13.LetvarDeclarationsbetheVarScopedDeclarationsofcode.
14.LetdeclaredVarNamesbeanewemptyList.
15.ForeachelementdinvarDeclarationsdo
a.ForeachelementdnoftheBoundNamesofddo
i.IfdnisnotanelementofdeclaredVarNames,then
1.Perform!envRec.CreateMutableBinding(dn,false).
2.CallenvRec.InitializeBinding(dn,undeined).
3.AppenddntodeclaredVarNames.
16.LetlexDeclarationsbetheLexicallyScopedDeclarationsofcode.
17.ForeachelementdinlexDeclarationsdo
a.ForeachelementdnoftheBoundNamesofddo
i.IfIsConstantDeclarationofdistrue,then
1.Perform!envRec.CreateImmutableBinding(dn,true).
ii.Else,
1.Perform!envRec.CreateMutableBinding(dn,false).
iii.IfdisaGeneratorDeclarationproductionoraFunctionDeclarationproduction,then
1.LetfobetheresultofperformingInstantiateFunctionObjectfordwithargumentenv.
2.CallenvRec.InitializeBinding(dn,fo).
18.ReturnNormalCompletion(empty).

15.2.1.16.5 ModuleEvaluation()ConcreteMethod
TheModuleEvaluationconcretemethodofaSourceTextModuleRecordperformsthefollowingsteps:

1.LetmodulebethisSourceTextModuleRecord.
2.Assert:ModuleDeclarationInstantiationhasalreadybeeninvokedonmoduleandsuccessfullycompleted.
3.Assert:module.[[Realm]]isnotundeined.
4.Ifmodule.[[Evaluated]]istrue,returnundeined.
5.Setmodule.[[Evaluated]]totrue.
6.ForeachStringrequiredthatisanelementofmodule.[[RequestedModules]]do,
a.LetrequiredModulebe?HostResolveImportedModule(module,required).
b.Perform?requiredModule.ModuleEvaluation().
7.LetmoduleCxtbeanewECMAScriptcodeexecutioncontext.
8.SettheFunctionofmoduleCxttonull.
9.SettheRealmofmoduleCxttomodule.[[Realm]].
10.SettheScriptOrModuleofmoduleCxttomodule.
11.Assert:modulehasbeenlinkedanddeclarationsinitsmoduleenvironmenthavebeeninstantiated.
12.SettheVariableEnvironmentofmoduleCxttomodule.[[Environment]].
13.SettheLexicalEnvironmentofmoduleCxttomodule.[[Environment]].
14.Suspendthecurrentlyrunningexecutioncontext.
15.PushmoduleCxtontotheexecutioncontextstack;moduleCxtisnowtherunningexecutioncontext.
16.Letresultbetheresultofevaluatingmodule.[[ECMAScriptCode]].
17.SuspendmoduleCxtandremoveitfromtheexecutioncontextstack.
18.Resumethecontextthatisnowonthetopoftheexecutioncontextstackastherunningexecutioncontext.
19.ReturnCompletion(result).

15.2.1.17 RuntimeSemantics:HostResolveImportedModule(referencingModule,speciier)

HostResolveImportedModuleisanimplementationdeinedabstractoperationthatprovidestheconcreteModuleRecord
subclassinstancethatcorrespondstotheModuleSpeciierString,speciier,occurringwithinthecontextofthemodule
representedbytheModuleRecordreferencingModule.

TheimplementationofHostResolveImportedModulemustconformtothefollowingrequirements:

ThenormalreturnvaluemustbeaninstanceofaconcretesubclassofModuleRecord.
IfaModuleRecordcorrespondingtothepairreferencingModule,speciierdoesnotexistorcannotbecreated,an
exceptionmustbethrown.
Thisoperationmustbeidempotentifitcompletesnormally.EachtimeitiscalledwithaspeciicreferencingModule,
speciierpairasargumentsitmustreturnthesameModuleRecordinstance.

MultipledifferentreferencingModule,speciierpairsmaymaptothesameModuleRecordinstance.Theactualmapping
semanticisimplementationdeinedbuttypicallyanormalizationprocessisappliedtospeciieraspartofthemapping
process.Atypicalnormalizationprocesswouldincludeactionssuchasalphabeticcasefoldingandexpansionofrelativeand
abbreviatedpathspeciiers.

15.2.1.18 RuntimeSemantics:GetModuleNamespace(module)

TheabstractoperationGetModuleNamespacecalledwithargumentmoduleperformsthefollowingsteps:

1.Assert:moduleisaninstanceofaconcretesubclassofModuleRecord.
2.Letnamespacebemodule.[[Namespace]].
3.Ifnamespaceisundeined,then
a.LetexportedNamesbe?module.GetExportedNames().
b.LetunambiguousNamesbeanewemptyList.
c.ForeachnamethatisanelementofexportedNames,
i.Letresolutionbe?module.ResolveExport(name,,).
ii.Ifresolutionisnull,throwaSyntaxErrorexception.
iii.Ifresolutionisnot"ambiguous",appendnametounambiguousNames.
d.LetnamespacebeModuleNamespaceCreate(module,unambiguousNames).
4.Returnnamespace.

15.2.1.19 RuntimeSemantics:TopLevelModuleEvaluationJob(sourceText,hostDeined)

ATopLevelModuleEvaluationJobwithparameterssourceTextandhostDeinedisajobthatparses,validates,andevaluates
sourceTextasaModule.

1.Assert:sourceTextisanECMAScriptsourcetext(seeclause10).
2.LetrealmbethecurrentRealmRecord.
3.LetmbeParseModule(sourceText,realm,hostDeined).
4.IfmisaListoferrors,then
a.PerformHostReportErrors(m).
b.NextJobNormalCompletion(undeined).
5.Letstatusbem.ModuleDeclarationInstantiation().
6.Ifstatusisnotanabruptcompletion,then
a.Assert:alldependenciesofmhavebeentransitivelyresolvedandmisreadyforevaluation.
b.Letstatusbem.ModuleEvaluation().
7.NextJobCompletion(status).

NOTE AnimplementationmayparseasourceTextasaModule,analyzeitforEarlyErrorconditions,andinstantiateit
priortotheexecutionoftheTopLevelModuleEvaluationJobforthatsourceText.Animplementationmayalso
resolve,preparseandpreanalyze,andpreinstantiatemoduledependenciesofsourceText.However,the
reportingofanyerrorsdetectedbytheseactionsmustbedeferreduntiltheTopLevelModuleEvaluationJobis
actuallyexecuted.

15.2.1.20 RuntimeSemantics:Evaluation

Module : [empty]

1.ReturnNormalCompletion(undeined).

ModuleBody : ModuleItemList

1.LetresultbetheresultofevaluatingModuleItemList.
2.Ifresult.[[Type]]isnormalandresult.[[Value]]isempty,then
a.ReturnNormalCompletion(undeined).
3.ReturnCompletion(result).

ModuleItemList : ModuleItemList ModuleItem

1.LetslbetheresultofevaluatingModuleItemList.
2.ReturnIfAbrupt(sl).
3.LetsbetheresultofevaluatingModuleItem.
4.ReturnCompletion(UpdateEmpty(s,sl.[[Value]])).

NOTE ThevalueofaModuleItemLististhevalueofthelastvalueproducingitemintheModuleItemList.

ModuleItem : ImportDeclaration

1.ReturnNormalCompletion(empty).

15.2.2 Imports

Syntax

ImportDeclaration :
import ImportClause FromClause ;
import ModuleSpeciier ;
ImportClause :
ImportedDefaultBinding
NameSpaceImport
NamedImports
ImportedDefaultBinding , NameSpaceImport
ImportedDefaultBinding , NamedImports

ImportedDefaultBinding :
ImportedBinding

NameSpaceImport :
* as ImportedBinding

NamedImports :
{ }
{ ImportsList }
{ ImportsList , }

FromClause :
from ModuleSpeciier

ImportsList :
ImportSpeciier
ImportsList , ImportSpeciier

ImportSpeciier :
ImportedBinding
IdentiierName as ImportedBinding

ModuleSpeciier :
StringLiteral

ImportedBinding :
BindingIdentiier

15.2.2.1 StaticSemantics:EarlyErrors

ModuleItem : ImportDeclaration

ItisaSyntaxErroriftheBoundNamesofImportDeclarationcontainsanyduplicateentries.

15.2.2.2 StaticSemantics:BoundNames

ImportDeclaration : import ImportClause FromClause ;

1.ReturntheBoundNamesofImportClause.

ImportDeclaration : import ModuleSpeciier ;

1.ReturnanewemptyList.

ImportClause : ImportedDefaultBinding , NameSpaceImport

1.LetnamesbetheBoundNamesofImportedDefaultBinding.
2.AppendtonamestheelementsoftheBoundNamesofNameSpaceImport.
3.Returnnames.

ImportClause : ImportedDefaultBinding , NamedImports

1.LetnamesbetheBoundNamesofImportedDefaultBinding.
2.AppendtonamestheelementsoftheBoundNamesofNamedImports.
3.Returnnames.

NamedImports : { }

1.ReturnanewemptyList.

ImportsList : ImportsList , ImportSpeciier

1.LetnamesbetheBoundNamesofImportsList.
2.AppendtonamestheelementsoftheBoundNamesofImportSpeciier.
3.Returnnames.

ImportSpeciier : IdentiierName as ImportedBinding

1.ReturntheBoundNamesofImportedBinding.

15.2.2.3 StaticSemantics:ImportEntries

ImportDeclaration : import ImportClause FromClause ;

1.LetmodulebethesoleelementofModuleRequestsofFromClause.
2.ReturnImportEntriesForModuleofImportClausewithargumentmodule.

ImportDeclaration : import ModuleSpeciier ;

1.ReturnanewemptyList.

15.2.2.4 StaticSemantics:ImportEntriesForModule

Withparametermodule.

ImportClause : ImportedDefaultBinding , NameSpaceImport

1.LetentriesbeImportEntriesForModuleofImportedDefaultBindingwithargumentmodule.
2.AppendtoentriestheelementsoftheImportEntriesForModuleofNameSpaceImportwithargumentmodule.
3.Returnentries.

ImportClause : ImportedDefaultBinding , NamedImports

1.LetentriesbeImportEntriesForModuleofImportedDefaultBindingwithargumentmodule.
2.AppendtoentriestheelementsoftheImportEntriesForModuleofNamedImportswithargumentmodule.
3.Returnentries.

ImportedDefaultBinding : ImportedBinding

1.LetlocalNamebethesoleelementofBoundNamesofImportedBinding.
2.LetdefaultEntrybetheRecord{[[ModuleRequest]]:module,[[ImportName]]:"default",[[LocalName]]:localName}.
3.ReturnanewListcontainingdefaultEntry.

NameSpaceImport : * as ImportedBinding

1.LetlocalNamebetheStringValueofImportedBinding.
2.LetentrybetheRecord{[[ModuleRequest]]:module,[[ImportName]]:"*",[[LocalName]]:localName}.
3.ReturnanewListcontainingentry.

NamedImports : { }

1.ReturnanewemptyList.

ImportsList : ImportsList , ImportSpeciier


1.LetspecsbetheImportEntriesForModuleofImportsListwithargumentmodule.
2.AppendtospecstheelementsoftheImportEntriesForModuleofImportSpeciierwithargumentmodule.
3.Returnspecs.

ImportSpeciier : ImportedBinding

1.LetlocalNamebethesoleelementofBoundNamesofImportedBinding.
2.LetentrybetheRecord{[[ModuleRequest]]:module,[[ImportName]]:localName,[[LocalName]]:localName}.
3.ReturnanewListcontainingentry.

ImportSpeciier : IdentiierName as ImportedBinding

1.LetimportNamebetheStringValueofIdentiierName.
2.LetlocalNamebetheStringValueofImportedBinding.
3.LetentrybetheRecord{[[ModuleRequest]]:module,[[ImportName]]:importName,[[LocalName]]:localName}.
4.ReturnanewListcontainingentry.

15.2.2.5 StaticSemantics:ModuleRequests

ImportDeclaration : import ImportClause FromClause ;

1.ReturnModuleRequestsofFromClause.

ModuleSpeciier : StringLiteral

1.ReturnaListcontainingtheStringValueofStringLiteral.

15.2.3 Exports

Syntax

ExportDeclaration :
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;
export VariableStatement
export Declaration
export default HoistableDeclaration[Default]
export default ClassDeclaration[Default]
export default [lookahead{function ,class}] AssignmentExpression[In] ;

ExportClause :
{ }
{ ExportsList }
{ ExportsList , }

ExportsList :
ExportSpeciier
ExportsList , ExportSpeciier

ExportSpeciier :
IdentiierName
IdentiierName as IdentiierName

15.2.3.1 StaticSemantics:EarlyErrors

ExportDeclaration : export ExportClause ;


ForeachIdentiierNameninReferencedBindingsofExportClause:ItisaSyntaxErrorifStringValueofnisa
ReservedWordoriftheStringValueofnisoneof:"implements","interface","let","package","private",
"protected","public",or"static".

NOTE TheaboverulemeansthateachReferencedBindingsofExportClauseistreatedasanIdentiierReference.

15.2.3.2 StaticSemantics:BoundNames

ExportDeclaration :
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;

1.ReturnanewemptyList.

ExportDeclaration : export VariableStatement

1.ReturntheBoundNamesofVariableStatement.

ExportDeclaration : export Declaration

1.ReturntheBoundNamesofDeclaration.

ExportDeclaration : export default HoistableDeclaration

1.LetdeclarationNamesbetheBoundNamesofHoistableDeclaration.
2.IfdeclarationNamesdoesnotincludetheelement"*default*",append"*default*"todeclarationNames.
3.ReturndeclarationNames.

ExportDeclaration : export default ClassDeclaration

1.LetdeclarationNamesbetheBoundNamesofClassDeclaration.
2.IfdeclarationNamesdoesnotincludetheelement"*default*",append"*default*"todeclarationNames.
3.ReturndeclarationNames.

ExportDeclaration : export default AssignmentExpression ;

1.Return"*default*".

15.2.3.3 StaticSemantics:ExportedBindings

ExportDeclaration :
export ExportClause FromClause ;
export * FromClause ;

1.ReturnanewemptyList.

ExportDeclaration : export ExportClause ;

1.ReturntheExportedBindingsofExportClause.

ExportDeclaration : export VariableStatement

1.ReturntheBoundNamesofVariableStatement.

ExportDeclaration : export Declaration

1.ReturntheBoundNamesofDeclaration.

ExportDeclaration : export default HoistableDeclaration


ExportDeclaration : export default ClassDeclaration
ExportDeclaration : export default AssignmentExpression ;

1.ReturntheBoundNamesofthisExportDeclaration.

ExportClause : { }

1.ReturnanewemptyList.

ExportsList : ExportsList , ExportSpeciier

1.LetnamesbetheExportedBindingsofExportsList.
2.AppendtonamestheelementsoftheExportedBindingsofExportSpeciier.
3.Returnnames.

ExportSpeciier : IdentiierName

1.ReturnaListcontainingtheStringValueofIdentiierName.

ExportSpeciier : IdentiierName as IdentiierName

1.ReturnaListcontainingtheStringValueoftheirstIdentiierName.

15.2.3.4 StaticSemantics:ExportedNames

ExportDeclaration : export * FromClause ;

1.ReturnanewemptyList.

ExportDeclaration :
export ExportClause FromClause ;
export ExportClause ;

1.ReturntheExportedNamesofExportClause.

ExportDeclaration : export VariableStatement

1.ReturntheBoundNamesofVariableStatement.

ExportDeclaration : export Declaration

1.ReturntheBoundNamesofDeclaration.

ExportDeclaration : export default HoistableDeclaration


ExportDeclaration : export default ClassDeclaration
ExportDeclaration : export default AssignmentExpression ;

1.Return"default".

ExportClause : { }

1.ReturnanewemptyList.

ExportsList : ExportsList , ExportSpeciier

1.LetnamesbetheExportedNamesofExportsList.
2.AppendtonamestheelementsoftheExportedNamesofExportSpeciier.
3.Returnnames.

ExportSpeciier : IdentiierName

1.ReturnaListcontainingtheStringValueofIdentiierName.
ExportSpeciier : IdentiierName as IdentiierName

1.ReturnaListcontainingtheStringValueofthesecondIdentiierName.

15.2.3.5 StaticSemantics:ExportEntries

ExportDeclaration : export * FromClause ;

1.LetmodulebethesoleelementofModuleRequestsofFromClause.
2.LetentrybetheRecord{[[ModuleRequest]]:module,[[ImportName]]:"*",[[LocalName]]:null,[[ExportName]]:null}.
3.ReturnanewListcontainingentry.

ExportDeclaration : export ExportClause FromClause ;

1.LetmodulebethesoleelementofModuleRequestsofFromClause.
2.ReturnExportEntriesForModuleofExportClausewithargumentmodule.

ExportDeclaration : export ExportClause ;

1.ReturnExportEntriesForModuleofExportClausewithargumentnull.

ExportDeclaration : export VariableStatement

1.LetentriesbeanewemptyList.
2.LetnamesbetheBoundNamesofVariableStatement.
3.Repeatforeachnameinnames,
a.AppendtoentriestheRecord{[[ModuleRequest]]:null,[[ImportName]]:null,[[LocalName]]:name,
[[ExportName]]:name}.
4.Returnentries.

ExportDeclaration : export Declaration

1.LetentriesbeanewemptyList.
2.LetnamesbetheBoundNamesofDeclaration.
3.Repeatforeachnameinnames,
a.AppendtoentriestheRecord{[[ModuleRequest]]:null,[[ImportName]]:null,[[LocalName]]:name,
[[ExportName]]:name}.
4.Returnentries.

ExportDeclaration : export default HoistableDeclaration

1.LetnamesbeBoundNamesofHoistableDeclaration.
2.LetlocalNamebethesoleelementofnames.
3.ReturnanewListcontainingtheRecord{[[ModuleRequest]]:null,[[ImportName]]:null,[[LocalName]]:localName,
[[ExportName]]:"default"}.

ExportDeclaration : export default ClassDeclaration

1.LetnamesbeBoundNamesofClassDeclaration.
2.LetlocalNamebethesoleelementofnames.
3.ReturnanewListcontainingtheRecord{[[ModuleRequest]]:null,[[ImportName]]:null,[[LocalName]]:localName,
[[ExportName]]:"default"}.

ExportDeclaration : export default AssignmentExpression ;

1.LetentrybetheRecord{[[ModuleRequest]]:null,[[ImportName]]:null,[[LocalName]]:"*default*",
[[ExportName]]:"default"}.
2.ReturnanewListcontainingentry.

NOTE "*default*"isusedwithinthisspeciicationasasyntheticnameforanonymousdefaultexportvalues.
15.2.3.6 StaticSemantics:ExportEntriesForModule

Withparametermodule.

ExportClause : { }

1.ReturnanewemptyList.

ExportsList : ExportsList , ExportSpeciier

1.LetspecsbetheExportEntriesForModuleofExportsListwithargumentmodule.
2.AppendtospecstheelementsoftheExportEntriesForModuleofExportSpeciierwithargumentmodule.
3.Returnspecs.

ExportSpeciier : IdentiierName

1.LetsourceNamebetheStringValueofIdentiierName.
2.Ifmoduleisnull,then
a.LetlocalNamebesourceName.
b.LetimportNamebenull.
3.Else,
a.LetlocalNamebenull.
b.LetimportNamebesourceName.
4.ReturnanewListcontainingtheRecord{[[ModuleRequest]]:module,[[ImportName]]:importName,[[LocalName]]:
localName,[[ExportName]]:sourceName}.

ExportSpeciier : IdentiierName as IdentiierName

1.LetsourceNamebetheStringValueoftheirstIdentiierName.
2.LetexportNamebetheStringValueofthesecondIdentiierName.
3.Ifmoduleisnull,then
a.LetlocalNamebesourceName.
b.LetimportNamebenull.
4.Else,
a.LetlocalNamebenull.
b.LetimportNamebesourceName.
5.ReturnanewListcontainingtheRecord{[[ModuleRequest]]:module,[[ImportName]]:importName,[[LocalName]]:
localName,[[ExportName]]:exportName}.

15.2.3.7 StaticSemantics:IsConstantDeclaration

ExportDeclaration :
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;
export default AssignmentExpression ;

1.Returnfalse.

NOTE ItisnotnecessarytotreatexportdefaultAssignmentExpressionasaconstantdeclarationbecausethereis
nosyntaxthatpermitsassignmenttotheinternalboundnameusedtoreferenceamodule'sdefaultobject.

15.2.3.8 StaticSemantics:LexicallyScopedDeclarations

ExportDeclaration :
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;
export VariableStatement

1.ReturnanewemptyList.

ExportDeclaration : export Declaration

1.ReturnanewListcontainingDeclarationPartofDeclaration.

ExportDeclaration : export default HoistableDeclaration

1.ReturnanewListcontainingDeclarationPartofHoistableDeclaration.

ExportDeclaration : export default ClassDeclaration

1.ReturnanewListcontainingClassDeclaration.

ExportDeclaration : export default AssignmentExpression ;

1.ReturnanewListcontainingthisExportDeclaration.

15.2.3.9 StaticSemantics:ModuleRequests

ExportDeclaration : export * FromClause ;


ExportDeclaration : export ExportClause FromClause ;

1.ReturntheModuleRequestsofFromClause.

ExportDeclaration :
export ExportClause ;
export VariableStatement
export Declaration
export default HoistableDeclaration
export default ClassDeclaration
export default AssignmentExpression ;

1.ReturnanewemptyList.

15.2.3.10 StaticSemantics:ReferencedBindings

ExportClause : { }

1.ReturnanewemptyList.

ExportsList : ExportsList , ExportSpeciier

1.LetnamesbetheReferencedBindingsofExportsList.
2.AppendtonamestheelementsoftheReferencedBindingsofExportSpeciier.
3.Returnnames.

ExportSpeciier : IdentiierName

1.ReturnaListcontainingtheIdentiierName.

ExportSpeciier : IdentiierName as IdentiierName

1.ReturnaListcontainingtheirstIdentiierName.

15.2.3.11 RuntimeSemantics:Evaluation

ExportDeclaration :
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;

1.ReturnNormalCompletion(empty).

ExportDeclaration : export VariableStatement

1.ReturntheresultofevaluatingVariableStatement.

ExportDeclaration : export Declaration

1.ReturntheresultofevaluatingDeclaration.

ExportDeclaration : export default HoistableDeclaration

1.ReturntheresultofevaluatingHoistableDeclaration.

ExportDeclaration : export default ClassDeclaration

1.LetvaluebetheresultofBindingClassDeclarationEvaluationofClassDeclaration.
2.ReturnIfAbrupt(value).
3.LetclassNamebethesoleelementofBoundNamesofClassDeclaration.
4.IfclassNameis"*default*",then
a.LethasNamePropertybe?HasOwnProperty(value,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(value,"default").
c.Letenvbetherunningexecutioncontext'sLexicalEnvironment.
d.Perform?InitializeBoundName("*default*",value,env).
5.ReturnNormalCompletion(empty).

ExportDeclaration : export default AssignmentExpression ;

1.LetrhsbetheresultofevaluatingAssignmentExpression.
2.Letvaluebe?GetValue(rhs).
3.IfIsAnonymousFunctionDeinition(AssignmentExpression)istrue,then
a.LethasNamePropertybe?HasOwnProperty(value,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(value,"default").
4.Letenvbetherunningexecutioncontext'sLexicalEnvironment.
5.Perform?InitializeBoundName("*default*",value,env).
6.ReturnNormalCompletion(empty).

16 ErrorHandlingandLanguageExtensions
AnimplementationmustreportmosterrorsatthetimetherelevantECMAScriptlanguageconstructisevaluated.Anearly
errorisanerrorthatcanbedetectedandreportedpriortotheevaluationofanyconstructintheScriptcontainingtheerror.
Thepresenceofanearlyerrorpreventstheevaluationoftheconstruct.Animplementationmustreportearlyerrorsina
ScriptaspartofparsingthatScriptinParseScript.EarlyerrorsinaModulearereportedatthepointwhentheModulewould
beevaluatedandtheModuleisneverinitialized.Earlyerrorsinevalcodearereportedatthetimeevaliscalledandprevent
evaluationoftheevalcode.Allerrorsthatarenotearlyerrorsareruntimeerrors.

AnimplementationmustreportasanearlyerroranyoccurrenceofaconditionthatislistedinaStaticSemantics:Early
Errorssubclauseofthisspeciication.

Animplementationshallnottreatotherkindsoferrorsasearlyerrorsevenifthecompilercanprovethataconstructcannot
executewithouterrorunderanycircumstances.Animplementationmayissueanearlywarninginsuchacase,butitshould
notreporttheerroruntiltherelevantconstructisactuallyexecuted.

Animplementationshallreportallerrorsasspeciied,exceptforthefollowing:
Exceptasrestrictedin16.2,animplementationmayextendScriptsyntax,Modulesyntax,andregularexpressionpattern
orlagsyntax.Topermitthis,alloperations(suchascallingeval,usingaregularexpressionliteral,orusingthe
FunctionorRegExpconstructor)thatareallowedtothrowSyntaxErrorarepermittedtoexhibitimplementation
deinedbehaviourinsteadofthrowingSyntaxErrorwhentheyencounteranimplementationdeinedextensiontothe
scriptsyntaxorregularexpressionpatternorlagsyntax.
Exceptasrestrictedin16.2,animplementationmayprovideadditionaltypes,values,objects,properties,andfunctions
beyondthosedescribedinthisspeciication.Thismaycauseconstructs(suchaslookingupavariableintheglobal
scope)tohaveimplementationdeinedbehaviourinsteadofthrowinganerror(suchasReferenceError).

AnimplementationmaydeinebehaviourotherthanthrowingRangeErrorfortoFixed,toExponential,and
toPrecisionwhenthefractionDigitsorprecisionargumentisoutsidethespeciiedrange.

16.1 HostReportErrors(errorList)
HostReportErrorsisanimplementationdeinedabstractoperationthatallowshostenvironmentstoreportparsingerrors,
earlyerrors,andruntimeerrors.

AnimplementationofHostReportErrorsmustcompletenormallyinallcases.Thedefaultimplementationof
HostReportErrorsistodonothing.

NOTE errorListwillbeaListofECMAScriptlanguagevalues.Iftheerrorsareparsingerrorsorearlyerrors,thesewill
alwaysbeSyntaxErrororReferenceErrorobjects.Runtimeerrors,however,canbeanyECMAScriptvalue.

16.2 ForbiddenExtensions
Animplementationmustnotextendthisspeciicationinthefollowingways:

Otherthanasdeinedinthisspeciication,ECMAScriptFunctionobjectsdeinedusingsyntacticconstructorsinstrict
modecodemustnotbecreatedwithownpropertiesnamed"caller"or"arguments"otherthanthosethatare
createdbyapplyingtheAddRestrictedFunctionPropertiesabstractoperationtothefunction.Suchownpropertiesalso
mustnotbecreatedforfunctionobjectsdeinedusinganArrowFunction,MethodDeinition,GeneratorDeclaration,
GeneratorExpression,ClassDeclaration,orClassExpressionregardlessofwhetherthedeinitioniscontainedinstrict
modecode.Builtinfunctions,strictmodefunctionscreatedusingtheFunctionconstructor,generatorfunctions
createdusingtheGeneratorconstructor,andfunctionscreatedusingthebindmethodalsomustnotbecreatedwith
suchownproperties.
Ifanimplementationextendsnonstrictorbuiltinfunctionobjectswithanownpropertynamed"caller"thevalueof
thatproperty,asobservedusing[[Get]]or[[GetOwnProperty]],mustnotbeastrictfunctionobject.Ifitisanaccessor
property,thefunctionthatisthevalueoftheproperty's[[Get]]attributemustneverreturnastrictfunctionwhen
called.
ThebehaviourofthefollowingmethodsmustnotbeextendedexceptasspeciiedinECMA402:
Object.prototype.toLocaleString,Array.prototype.toLocaleString,
Number.prototype.toLocaleString,Date.prototype.toLocaleDateString,
Date.prototype.toLocaleString,Date.prototype.toLocaleTimeString,
String.prototype.localeCompare,%TypedArray%.prototype.toLocaleString.
TheRegExppatterngrammarsin21.2.1andB.1.4mustnotbeextendedtorecognizeanyofthesourcecharactersAZor
azasIdentityEscape[U] whentheUgrammarparameterispresent.
TheSyntacticGrammarmustnotbeextendedinanymannerthatallowsthetoken:toimmediatefollowsourcetext
thatmatchestheBindingIdentiiernonterminalsymbol.
Whenprocessingstrictmodecode,thesyntaxofNumericLiteralmustnotbeextendedtoinclude
LegacyOctalIntegerLiteralandthesyntaxofDecimalIntegerLiteralmustnotbeextendedtoinclude
NonOctalDecimalIntegerLiteralasdescribedinB.1.1.
TemplateCharactermustnotbeextendedtoincludeLegacyOctalEscapeSequenceasdeinedinB.1.2.
Whenprocessingstrictmodecode,theextensionsdeinedinB.3.2,B.3.3,andB.3.4mustnotbesupported.
WhenparsingfortheModulegoalsymbol,thelexicalgrammarextensionsdeinedinB.1.3mustnotbesupported.
17 ECMAScriptStandardBuiltinObjects
TherearecertainbuiltinobjectsavailablewheneveranECMAScriptScriptorModulebeginsexecution.One,theglobal
object,ispartofthelexicalenvironmentoftheexecutingprogram.Othersareaccessibleasinitialpropertiesoftheglobal
objectorindirectlyaspropertiesofaccessiblebuiltinobjects.

Unlessspeciiedotherwise,abuiltinobjectthatiscallableasafunctionisabuiltinFunctionobjectwiththecharacteristics
describedin9.3.Unlessspeciiedotherwise,the[[Extensible]]internalslotofabuiltinobjectinitiallyhasthevaluetrue.
EverybuiltinFunctionobjecthasa[[Realm]]internalslotwhosevalueistheRealmRecordoftherealmforwhichtheobject
wasinitiallycreated.

Manybuiltinobjectsarefunctions:theycanbeinvokedwitharguments.Someofthemfurthermoreareconstructors:they
arefunctionsintendedforusewiththenewoperator.Foreachbuiltinfunction,thisspeciicationdescribesthearguments
requiredbythatfunctionandthepropertiesofthatfunctionobject.Foreachbuiltinconstructor,thisspeciication
furthermoredescribespropertiesoftheprototypeobjectofthatconstructorandpropertiesofspeciicobjectinstances
returnedbyanewexpressionthatinvokesthatconstructor.

Unlessotherwisespeciiedinthedescriptionofaparticularfunction,ifabuiltinfunctionorconstructorisgivenfewer
argumentsthanthefunctionisspeciiedtorequire,thefunctionorconstructorshallbehaveexactlyasifithadbeengiven
suficientadditionalarguments,eachsuchargumentbeingtheundeinedvalue.Suchmissingargumentsareconsideredto
benotpresentandmaybeidentiiedinthatmannerbyspeciicationalgorithms.Inthedescriptionofaparticularfunction,
thetermsthisvalueandNewTargethavethemeaningsgivenin9.3.

Unlessotherwisespeciiedinthedescriptionofaparticularfunction,ifabuiltinfunctionorconstructordescribedisgiven
moreargumentsthanthefunctionisspeciiedtoallow,theextraargumentsareevaluatedbythecallandthenignoredbythe
function.However,animplementationmaydeineimplementationspeciicbehaviourrelatingtosuchargumentsaslongas
thebehaviourisnotthethrowingofaTypeErrorexceptionthatispredicatedsimplyonthepresenceofanextraargument.

NOTE1 Implementationsthataddadditionalcapabilitiestothesetofbuiltinfunctionsareencouragedtodosoby
addingnewfunctionsratherthanaddingnewparameterstoexistingfunctions.

UnlessotherwisespeciiedeverybuiltinfunctionandeverybuiltinconstructorhastheFunctionprototypeobject,whichis
theinitialvalueoftheexpressionFunction.prototype(19.2.3),asthevalueofits[[Prototype]]internalslot.

UnlessotherwisespeciiedeverybuiltinprototypeobjecthastheObjectprototypeobject,whichistheinitialvalueofthe
expressionObject.prototype(19.1.3),asthevalueofits[[Prototype]]internalslot,excepttheObjectprototypeobject
itself.

Builtinfunctionobjectsthatarenotidentiiedasconstructorsdonotimplementthe[[Construct]]internalmethodunless
otherwisespeciiedinthedescriptionofaparticularfunction.

Unlessotherwisespeciied,eachbuiltinfunctiondeinedinthisspeciicationiscreatedasifbycallingthe
CreateBuiltinFunctionabstractoperation(9.3.3).

EverybuiltinFunctionobject,includingconstructors,hasalengthpropertywhosevalueisaninteger.Unlessotherwise
speciied,thisvalueisequaltothelargestnumberofnamedargumentsshowninthesubclauseheadingsforthefunction
description.Optionalparameters(whichareindicatedwithbrackets:[])orrestparameters(whichareshownusingthe
form...name)arenotincludedinthedefaultargumentcount.

NOTE2 Forexample,thefunctionobjectthatistheinitialvalueofthemappropertyoftheArrayprototypeobjectis
describedunderthesubclauseheadingArray.prototype.map(callbackFn[,thisArg])whichshowsthetwo
namedargumentscallbackFnandthisArg,thelatterbeingoptional;thereforethevalueofthelengthproperty
ofthatFunctionobjectis1.

Unlessotherwisespeciied,thelengthpropertyofabuiltinFunctionobjecthastheattributes{[[Writable]]:false,
[[Enumerable]]:false,[[Conigurable]]:true}.
EverybuiltinFunctionobject,includingconstructors,thatisnotidentiiedasananonymousfunctionhasanameproperty
whosevalueisaString.Unlessotherwisespeciied,thisvalueisthenamethatisgiventothefunctioninthisspeciication.
Forfunctionsthatarespeciiedaspropertiesofobjects,thenamevalueisthepropertynamestringusedtoaccessthe
function.Functionsthatarespeciiedasgetorsetaccessorfunctionsofbuiltinpropertieshave"get"or"set"
prependedtothepropertynamestring.Thevalueofthenamepropertyisexplicitlyspeciiedforeachbuiltinfunctions
whosepropertykeyisaSymbolvalue.

Unlessotherwisespeciied,thenamepropertyofabuiltinFunctionobject,ifitexists,hastheattributes{[[Writable]]:false,
[[Enumerable]]:false,[[Conigurable]]:true}.

Everyotherdatapropertydescribedinclauses18through26andinAnnexB.2hastheattributes{[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:true}unlessotherwisespeciied.

Everyaccessorpropertydescribedinclauses18through26andinAnnexB.2hastheattributes{[[Enumerable]]:false,
[[Conigurable]]:true}unlessotherwisespeciied.Ifonlyagetaccessorfunctionisdescribed,thesetaccessorfunctionis
thedefaultvalue,undeined.Ifonlyasetaccessorisdescribedthegetaccessoristhedefaultvalue,undeined.

18 TheGlobalObject
Theuniqueglobalobjectiscreatedbeforecontrolentersanyexecutioncontext.

Theglobalobjectdoesnothavea[[Construct]]internalmethod;itisnotpossibletousetheglobalobjectasaconstructor
withthenewoperator.

Theglobalobjectdoesnothavea[[Call]]internalmethod;itisnotpossibletoinvoketheglobalobjectasafunction.

Thevalueofthe[[Prototype]]internalslotoftheglobalobjectisimplementationdependent.

Inadditiontothepropertiesdeinedinthisspeciicationtheglobalobjectmayhaveadditionalhostdeinedproperties.This
mayincludeapropertywhosevalueistheglobalobjectitself;forexample,intheHTMLdocumentobjectmodelthewindow
propertyoftheglobalobjectistheglobalobjectitself.

18.1 ValuePropertiesoftheGlobalObject
18.1.1 Ininity

ThevalueofInfinityis+(see6.1.6).Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,
[[Conigurable]]:false}.

18.1.2 NaN

ThevalueofNaNisNaN(see6.1.6).Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,
[[Conigurable]]:false}.

18.1.3 undeined

Thevalueofundefinedisundeined(see6.1.1).Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:
false,[[Conigurable]]:false}.

18.2 FunctionPropertiesoftheGlobalObject
18.2.1 eval(x)

Theevalfunctionisthe%eval%intrinsicobject.Whentheevalfunctioniscalledwithoneargumentx,thefollowingsteps
aretaken:

1.LetevalRealmbethevalueoftheactivefunctionobject's[[Realm]]internalslot.
2.LetstrictCallerbefalse.
3.LetdirectEvalbefalse.
4.Return?PerformEval(x,evalRealm,strictCaller,directEval).

18.2.1.1 RuntimeSemantics:PerformEval(x,evalRealm,strictCaller,direct)

TheabstractoperationPerformEvalwithargumentsx,evalRealm,strictCaller,anddirectperformsthefollowingsteps:

1.Assert:Ifdirectisfalse,thenstrictCallerisalsofalse.
2.IfType(x)isnotString,returnx.
3.LetscriptbetheECMAScriptcodethatistheresultofparsingx,interpretedasUTF16encodedUnicodetextas
describedin6.1.4,forthegoalsymbolScript.Iftheparsefails,throwaSyntaxErrorexception.Ifanyearlyerrorsare
detected,throwaSyntaxErrororaReferenceErrorexception,dependingonthetypeoftheerror(butseealsoclause
16).Parsingandearlyerrordetectionmaybeinterweavedinanimplementationdependentmanner.
4.IfscriptContainsScriptBodyisfalse,returnundeined.
5.LetbodybetheScriptBodyofscript.
6.IfstrictCalleristrue,letstrictEvalbetrue.
7.Else,letstrictEvalbeIsStrictofscript.
8.Letctxbetherunningexecutioncontext.Ifdirectistrue,ctxwillbetheexecutioncontextthatperformedthedirect
eval.Ifdirectisfalse,ctxwillbetheexecutioncontextfortheinvocationoftheevalfunction.
9.Ifdirectistrue,then
a.LetlexEnvbeNewDeclarativeEnvironment(ctx'sLexicalEnvironment).
b.LetvarEnvbectx'sVariableEnvironment.
10.Else,
a.LetlexEnvbeNewDeclarativeEnvironment(evalRealm.[[GlobalEnv]]).
b.LetvarEnvbeevalRealm.[[GlobalEnv]].
11.IfstrictEvalistrue,letvarEnvbelexEnv.
12.Ifctxisnotalreadysuspended,suspendctx.
13.LetevalCxtbeanewECMAScriptcodeexecutioncontext.
14.SettheevalCxt'sFunctiontonull.
15.SettheevalCxt'sRealmtoevalRealm.
16.SettheevalCxt'sScriptOrModuletoctx'sScriptOrModule.
17.SettheevalCxt'sVariableEnvironmenttovarEnv.
18.SettheevalCxt'sLexicalEnvironmenttolexEnv.
19.PushevalCxtontotheexecutioncontextstack;evalCxtisnowtherunningexecutioncontext.
20.LetresultbeEvalDeclarationInstantiation(body,varEnv,lexEnv,strictEval).
21.Ifresult.[[Type]]isnormal,then
a.Letresultbetheresultofevaluatingbody.
22.Ifresult.[[Type]]isnormalandresult.[[Value]]isempty,then
a.LetresultbeNormalCompletion(undeined).
23.SuspendevalCxtandremoveitfromtheexecutioncontextstack.
24.Resumethecontextthatisnowonthetopoftheexecutioncontextstackastherunningexecutioncontext.
25.ReturnCompletion(result).

NOTE Theevalcodecannotinstantiatevariableorfunctionbindingsinthevariableenvironmentofthecalling
contextthatinvokedtheevalifthecallingcontextisevaluatingformalparameterinitializersorifeitherthe
codeofthecallingcontextortheevalcodeisstrictcode.Insteadsuchbindingsareinstantiatedinanew
VariableEnvironmentthatisonlyaccessibletotheevalcode.Bindingsintroducedbylet,const,orclass
declarationsarealwaysinstantiatedinanewLexicalEnvironment.

18.2.1.2 RuntimeSemantics:EvalDeclarationInstantiation(body,varEnv,lexEnv,strict)

WhentheabstractoperationEvalDeclarationInstantiationiscalledwithargumentsbody,varEnv,lexEnv,andstrict,the
followingstepsaretaken:

1.LetvarNamesbetheVarDeclaredNamesofbody.
2.LetvarDeclarationsbetheVarScopedDeclarationsofbody.
3.LetlexEnvRecbelexEnv'sEnvironmentRecord.
4.LetvarEnvRecbevarEnv'sEnvironmentRecord.
5.Ifstrictisfalse,then
a.IfvarEnvRecisaglobalEnvironmentRecord,then
i.ForeachnameinvarNames,do
1.IfvarEnvRec.HasLexicalDeclaration(name)istrue,throwaSyntaxErrorexception.
2.NOTE:evalwillnotcreateaglobalvardeclarationthatwouldbeshadowedbyagloballexical
declaration.
b.LetthisLexbelexEnv.
c.Assert:thefollowingloopwillterminate.
d.RepeatwhilethisLexisnotthesameasvarEnv,
i.LetthisEnvRecbethisLex'sEnvironmentRecord.
ii.IfthisEnvRecisnotanobjectEnvironmentRecord,then
1.NOTE:Theenvironmentofwithstatementscannotcontainanylexicaldeclarationsoitdoesn'tneedto
becheckedforvar/lethoistingconlicts.
2.ForeachnameinvarNames,do
a.IfthisEnvRec.HasBinding(name)istrue,then
i.ThrowaSyntaxErrorexception.
b.NOTE:Adirectevalwillnothoistvardeclarationoveralikenamedlexicaldeclaration.
iii.LetthisLexbethisLex'souterenvironmentreference.
6.LetfunctionsToInitializebeanewemptyList.
7.LetdeclaredFunctionNamesbeanewemptyList.
8.ForeachdinvarDeclarations,inreverselistorderdo
a.IfdisneitheraVariableDeclarationoraForBinding,then
i.Assert:diseitheraFunctionDeclarationoraGeneratorDeclaration.
ii.NOTEIftherearemultipleFunctionDeclarationsforthesamename,thelastdeclarationisused.
iii.LetfnbethesoleelementoftheBoundNamesofd.
iv.IffnisnotanelementofdeclaredFunctionNames,then
1.IfvarEnvRecisaglobalEnvironmentRecord,then
a.LetfnDeinablebe?varEnvRec.CanDeclareGlobalFunction(fn).
b.IffnDeinableisfalse,throwaTypeErrorexception.
2.AppendfntodeclaredFunctionNames.
3.InsertdastheirstelementoffunctionsToInitialize.
9.NOTE:AnnexB.3.3.3addsadditionalstepsatthispoint.
10.LetdeclaredVarNamesbeanewemptyList.
11.ForeachdinvarDeclarations,do
a.IfdisaVariableDeclarationoraForBinding,then
i.ForeachStringvnintheBoundNamesofd,do
1.IfvnisnotanelementofdeclaredFunctionNames,then
a.IfvarEnvRecisaglobalEnvironmentRecord,then
i.LetvnDeinablebe?varEnvRec.CanDeclareGlobalVar(vn).
ii.IfvnDeinableisfalse,throwaTypeErrorexception.
b.IfvnisnotanelementofdeclaredVarNames,then
i.AppendvntodeclaredVarNames.
12.NOTE:NoabnormalterminationsoccurafterthisalgorithmstepunlessvarEnvRecisaglobalEnvironmentRecordand
theglobalobjectisaProxyexoticobject.
13.LetlexDeclarationsbetheLexicallyScopedDeclarationsofbody.
14.ForeachelementdinlexDeclarationsdo
a.NOTELexicallydeclarednamesareonlyinstantiatedherebutnotinitialized.
b.ForeachelementdnoftheBoundNamesofddo
i.IfIsConstantDeclarationofdistrue,then
1.Perform?lexEnvRec.CreateImmutableBinding(dn,true).
ii.Else,
1.Perform?lexEnvRec.CreateMutableBinding(dn,false).
15.ForeachproductionfinfunctionsToInitialize,do
a.LetfnbethesoleelementoftheBoundNamesoff.
b.LetfobetheresultofperformingInstantiateFunctionObjectforfwithargumentlexEnv.
c.IfvarEnvRecisaglobalEnvironmentRecord,then
i.Perform?varEnvRec.CreateGlobalFunctionBinding(fn,fo,true).
d.Else,
i.LetbindingExistsbevarEnvRec.HasBinding(fn).
ii.IfbindingExistsisfalse,then
1.Letstatusbe!varEnvRec.CreateMutableBinding(fn,true).
2.Assert:statusisnotanabruptcompletionbecauseofvalidationprecedingstep12.
3.Perform!varEnvRec.InitializeBinding(fn,fo).
iii.Else,
1.Perform!varEnvRec.SetMutableBinding(fn,fo,false).
16.ForeachStringvnindeclaredVarNames,inlistorderdo
a.IfvarEnvRecisaglobalEnvironmentRecord,then
i.Perform?varEnvRec.CreateGlobalVarBinding(vn,true).
b.Else,
i.LetbindingExistsbevarEnvRec.HasBinding(vn).
ii.IfbindingExistsisfalse,then
1.Letstatusbe!varEnvRec.CreateMutableBinding(vn,true).
2.Assert:statusisnotanabruptcompletionbecauseofvalidationprecedingstep12.
3.Perform!varEnvRec.InitializeBinding(vn,undeined).
17.ReturnNormalCompletion(empty).

NOTE AnalternativeversionofthisalgorithmisdescribedinB.3.5.

18.2.2 isFinite(number)

TheisFinitefunctionisthe%isFinite%intrinsicobject.WhentheisFinitefunctioniscalledwithoneargumentnumber,
thefollowingstepsaretaken:

1.Letnumbe?ToNumber(number).
2.IfnumisNaN,+,or,returnfalse.
3.Otherwise,returntrue.

18.2.3 isNaN(number)

TheisNaNfunctionisthe%isNaN%intrinsicobject.WhentheisNaNfunctioniscalledwithoneargumentnumber,the
followingstepsaretaken:

1.Letnumbe?ToNumber(number).
2.IfnumisNaN,returntrue.
3.Otherwise,returnfalse.

NOTE AreliablewayforECMAScriptcodetotestifavalueXisaNaNisanexpressionoftheformX!==X.The
resultwillbetrueifandonlyifXisaNaN.

18.2.4 parseFloat(string)

TheparseFloatfunctionproducesaNumbervaluedictatedbyinterpretationofthecontentsofthestringargumentasa
decimalliteral.

TheparseFloatfunctionisthe%parseFloat%intrinsicobject.WhentheparseFloatfunctioniscalledwithoneargument
string,thefollowingstepsaretaken:

1.LetinputStringbe?ToString(string).
2.LettrimmedStringbeasubstringofinputStringconsistingoftheleftmostcodeunitthatisnotaStrWhiteSpaceCharand
allcodeunitstotherightofthatcodeunit.(Inotherwords,removeleadingwhitespace.)IfinputStringdoesnotcontain
anysuchcodeunits,lettrimmedStringbetheemptystring.
3.IfneithertrimmedStringnoranypreixoftrimmedStringsatisiesthesyntaxofaStrDecimalLiteral(see7.1.3.1),return
NaN.
4.LetnumberStringbethelongestpreixoftrimmedString,whichmightbetrimmedStringitself,thatsatisiesthesyntaxof
aStrDecimalLiteral.
5.LetmathFloatbeMVofnumberString.
6.IfmathFloat=0,then
a.IftheirstcodeunitoftrimmedStringis"",return0.
b.Return+0.
7.ReturntheNumbervalueformathFloat.

NOTE parseFloatmayinterpretonlyaleadingportionofstringasaNumbervalue;itignoresanycodeunitsthat
cannotbeinterpretedaspartofthenotationofandecimalliteral,andnoindicationisgiventhatanysuchcode
unitswereignored.

18.2.5 parseInt(string,radix)

TheparseIntfunctionproducesanintegervaluedictatedbyinterpretationofthecontentsofthestringargumentaccording
tothespeciiedradix.Leadingwhitespaceinstringisignored.Ifradixisundeinedor0,itisassumedtobe10exceptwhen
thenumberbeginswiththecodeunitpairs0xor0X,inwhichcasearadixof16isassumed.Ifradixis16,thenumbermay
alsooptionallybeginwiththecodeunitpairs0xor0X.

TheparseIntfunctionisthe%parseInt%intrinsicobject.WhentheparseIntfunctioniscalled,thefollowingstepsare
taken:

1.LetinputStringbe?ToString(string).
2.LetSbeanewlycreatedsubstringofinputStringconsistingoftheirstcodeunitthatisnotaStrWhiteSpaceCharandall
codeunitsfollowingthatcodeunit.(Inotherwords,removeleadingwhitespace.)IfinputStringdoesnotcontainany
suchcodeunit,letSbetheemptystring.
3.Letsignbe1.
4.IfSisnotemptyandtheirstcodeunitofSis0x002D(HYPHENMINUS),letsignbe1.
5.IfSisnotemptyandtheirstcodeunitofSis0x002B(PLUSSIGN)or0x002D(HYPHENMINUS),removetheirstcode
unitfromS.
6.LetRbe?ToInt32(radix).
7.LetstripPreixbetrue.
8.IfR0,then
a.IfR<2orR>36,returnNaN.
b.IfR16,letstripPreixbefalse.
9.ElseR=0,
a.LetRbe10.
10.IfstripPreixistrue,then
a.IfthelengthofSisatleast2andtheirsttwocodeunitsofSareeither"0x"or"0X",removetheirsttwocode
unitsfromSandletRbe16.
11.IfScontainsacodeunitthatisnotaradixRdigit,letZbethesubstringofSconsistingofallcodeunitsbeforetheirst
suchcodeunit;otherwise,letZbeS.
12.IfZisempty,returnNaN.
13.LetmathIntbethemathematicalintegervaluethatisrepresentedbyZinradixRnotation,usingthelettersAZandaz
fordigitswithvalues10through35.(However,ifRis10andZcontainsmorethan20signiicantdigits,everysigniicant
digitafterthe20thmaybereplacedbya0digit,attheoptionoftheimplementation;andifRisnot2,4,8,10,16,or32,
thenmathIntmaybeanimplementationdependentapproximationtothemathematicalintegervaluethatis
representedbyZinradixRnotation.)
14.IfmathInt=0,then
a.Ifsign=1,return0.
b.Return+0.
15.LetnumberbetheNumbervalueformathInt.
16.Returnsignnumber.

NOTE parseIntmayinterpretonlyaleadingportionofstringasanintegervalue;itignoresanycodeunitsthat
cannotbeinterpretedaspartofthenotationofaninteger,andnoindicationisgiventhatanysuchcodeunits
wereignored.

18.2.6 URIHandlingFunctions

UniformResourceIdentiiers,orURIs,areStringsthatidentifyresources(e.g.webpagesoriles)andtransportprotocolsby
whichtoaccessthem(e.g.HTTPorFTP)ontheInternet.TheECMAScriptlanguageitselfdoesnotprovideanysupportfor
usingURIsexceptforfunctionsthatencodeanddecodeURIsasdescribedin18.2.6.2,18.2.6.3,18.2.6.4and18.2.6.5

NOTE ManyimplementationsofECMAScriptprovideadditionalfunctionsandmethodsthatmanipulatewebpages;
thesefunctionsarebeyondthescopeofthisstandard.

18.2.6.1 URISyntaxandSemantics

AURIiscomposedofasequenceofcomponentsseparatedbycomponentseparators.Thegeneralformis:

Scheme:First/Second;Third?Fourth

wheretheitalicizednamesrepresentcomponentsand:,/,;and?arereservedforuseasseparators.TheencodeURI
anddecodeURIfunctionsareintendedtoworkwithcompleteURIs;theyassumethatanyreservedcodeunitsintheURIare
intendedtohavespecialmeaningandsoarenotencoded.TheencodeURIComponentanddecodeURIComponentfunctions
areintendedtoworkwiththeindividualcomponentpartsofaURI;theyassumethatanyreservedcodeunitsrepresenttext
andsomustbeencodedsothattheyarenotinterpretedasreservedcodeunitswhenthecomponentispartofacomplete
URI.

ThefollowinglexicalgrammarspeciiestheformofencodedURIs.

Syntax

uri :::
uriCharactersopt

uriCharacters :::
uriCharacter uriCharactersopt

uriCharacter :::
uriReserved
uriUnescaped
uriEscaped

uriReserved ::: oneof


; / ? : @ & = + $ ,

uriUnescaped :::
uriAlpha
DecimalDigit
uriMark

uriEscaped :::
% HexDigit HexDigit

uriAlpha ::: oneof


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
uriMark ::: oneof
_ . ! ~ * ' ( )

NOTE TheabovesyntaxisbaseduponRFC2396anddoesnotrelectchangesintroducedbythemorerecentRFC
3986.

RuntimeSemantics

WhenacodeunittobeincludedinaURIisnotlistedaboveorisnotintendedtohavethespecialmeaningsometimesgiven
tothereservedcodeunits,thatcodeunitmustbeencoded.ThecodeunitistransformedintoitsUTF8encoding,with
surrogatepairsirstconvertedfromUTF16tothecorrespondingcodepointvalue.(Notethatforcodeunitsintherange
[0,127]thisresultsinasingleoctetwiththesamevalue.)TheresultingsequenceofoctetsisthentransformedintoaString
witheachoctetrepresentedbyanescapesequenceoftheform"%xx".

18.2.6.1.1 RuntimeSemantics:Encode(string,unescapedSet)

TheencodingandescapingprocessisdescribedbytheabstractoperationEncodetakingtwoStringargumentsstringand
unescapedSet.

1.LetstrLenbethenumberofcodeunitsinstring.
2.LetRbetheemptyString.
3.Letkbe0.
4.Repeat
a.IfkequalsstrLen,returnR.
b.LetCbethecodeunitatindexkwithinstring.
c.IfCisinunescapedSet,then
i.LetSbeaStringcontainingonlythecodeunitC.
ii.LetRbeanewStringvaluecomputedbyconcatenatingthepreviousvalueofRandS.
d.ElseCisnotinunescapedSet,
i.IfthecodeunitvalueofCisnotlessthan0xDC00andnotgreaterthan0xDFFF,throwaURIErrorexception.
ii.IfthecodeunitvalueofCislessthan0xD800orgreaterthan0xDBFF,then
1.LetVbethecodeunitvalueofC.
iii.Else,
1.Increasekby1.
2.IfkequalsstrLen,throwaURIErrorexception.
3.LetkCharbethecodeunitvalueofthecodeunitatindexkwithinstring.
4.IfkCharislessthan0xDC00orgreaterthan0xDFFF,throwaURIErrorexception.
5.LetVbeUTF16Decode(C,kChar).
iv.LetOctetsbethearrayofoctetsresultingbyapplyingtheUTF8transformationtoV,andletLbethearray
size.
v.Letjbe0.
vi.Repeat,whilej<L
1.LetjOctetbethevalueatindexjwithinOctets.
2.LetSbeaStringcontainingthreecodeunits"%XY"whereXYaretwouppercasehexadecimaldigits
encodingthevalueofjOctet.
3.LetRbeanewStringvaluecomputedbyconcatenatingthepreviousvalueofRandS.
4.Increasejby1.
e.Increasekby1.

18.2.6.1.2 RuntimeSemantics:Decode(string,reservedSet)

TheunescapinganddecodingprocessisdescribedbytheabstractoperationDecodetakingtwoStringargumentsstringand
reservedSet.

1.LetstrLenbethenumberofcodeunitsinstring.
2.LetRbetheemptyString.
3.Letkbe0.
4.Repeat
a.IfkequalsstrLen,returnR.
b.LetCbethecodeunitatindexkwithinstring.
c.IfCisnot"%",then
i.LetSbetheStringcontainingonlythecodeunitC.
d.ElseCis"%",
i.Letstartbek.
ii.Ifk+2isgreaterthanorequaltostrLen,throwaURIErrorexception.
iii.Ifthecodeunitsatindex(k+1)and(k+2)withinstringdonotrepresenthexadecimaldigits,throwa
URIErrorexception.
iv.LetBbethe8bitvaluerepresentedbythetwohexadecimaldigitsatindex(k+1)and(k+2).
v.Incrementkby2.
vi.IfthemostsigniicantbitinBis0,then
1.LetCbethecodeunitwithcodeunitvalueB.
2.IfCisnotinreservedSet,then
a.LetSbetheStringcontainingonlythecodeunitC.
3.ElseCisinreservedSet,
a.LetSbethesubstringofstringfromindexstarttoindexkinclusive.
vii.ElsethemostsigniicantbitinBis1,
1.Letnbethesmallestnonnegativeintegersuchthat(B<<n)&0x80isequalto0.
2.Ifnequals1ornisgreaterthan4,throwaURIErrorexception.
3.LetOctetsbeanarrayof8bitintegersofsizen.
4.PutBintoOctetsatindex0.
5.Ifk+(3(n1))isgreaterthanorequaltostrLen,throwaURIErrorexception.
6.Letjbe1.
7.Repeat,whilej<n
a.Incrementkby1.
b.Ifthecodeunitatindexkwithinstringisnot"%",throwaURIErrorexception.
c.Ifthecodeunitsatindex(k+1)and(k+2)withinstringdonotrepresenthexadecimaldigits,
throwaURIErrorexception.
d.LetBbethe8bitvaluerepresentedbythetwohexadecimaldigitsatindex(k+1)and(k+2).
e.IfthetwomostsigniicantbitsinBarenot10,throwaURIErrorexception.
f.Incrementkby2.
g.PutBintoOctetsatindexj.
h.Incrementjby1.
8.LetVbethevalueobtainedbyapplyingtheUTF8transformationtoOctets,thatis,fromanarrayof
octetsintoa21bitvalue.IfOctetsdoesnotcontainavalidUTF8encodingofaUnicodecodepoint,
throwaURIErrorexception.
9.IfV<0x10000,then
a.LetCbethecodeunitV.
b.IfCisnotinreservedSet,then
i.LetSbetheStringcontainingonlythecodeunitC.
c.ElseCisinreservedSet,
i.LetSbethesubstringofstringfromindexstarttoindexkinclusive.
10.ElseV0x10000,
a.LetLbe(((V0x10000)&0x3FF)+0xDC00).
b.LetHbe((((V0x10000)>>10)&0x3FF)+0xD800).
c.LetSbetheStringcontainingthetwocodeunitsHandL.
e.LetRbeanewStringvaluecomputedbyconcatenatingthepreviousvalueofRandS.
f.Increasekby1.

NOTE ThissyntaxofUniformResourceIdentiiersisbaseduponRFC2396anddoesnotrelectthemorerecentRFC
3986whichreplacesRFC2396.AformaldescriptionandimplementationofUTF8isgiveninRFC3629.
InUTF8,charactersareencodedusingsequencesof1to6octets.Theonlyoctetofasequenceofonehasthe
higherorderbitsetto0,theremaining7bitsbeingusedtoencodethecharactervalue.Inasequenceofn
octets,n>1,theinitialoctethasthenhigherorderbitssetto1,followedbyabitsetto0.Theremainingbitsof
thatoctetcontainbitsfromthevalueofthecharactertobeencoded.Thefollowingoctetsallhavethehigher
orderbitsetto1andthefollowingbitsetto0,leaving6bitsineachtocontainbitsfromthecharactertobe
encoded.ThepossibleUTF8encodingsofECMAScriptcharactersarespeciiedinTable44.

Table44(Informative):UTF8Encodings

CodeUnitValue Representation 1stOctet 2ndOctet 3rdOctet 4thOctet

0x00000x007F 000000000zzzzzzz 0zzzzzzz

0x00800x07FF 00000yyyyyzzzzzz 110yyyyy 10zzzzzz

0x08000xD7FF xxxxyyyyyyzzzzzz 1110xxxx 10yyyyyy 10zzzzzz

0xD8000xDBFF 110110vvvvwwwwxx 11110uuu 10uuwwww 10xxyyyy 10zzzzzz


followedby followedby
0xDC000xDFFF 110111yyyyzzzzzz

0xD8000xDBFF causesURIError
notfollowedby
0xDC000xDFFF

0xDC000xDFFF causesURIError

0xE0000xFFFF xxxxyyyyyyzzzzzz 1110xxxx 10yyyyyy 10zzzzzz

Where
uuuuu=vvvv+1
toaccountfortheadditionof0x10000asinSurrogates,section3.8,oftheUnicodeStandard.

Therangeofcodeunitvalues0xD8000xDFFFisusedtoencodesurrogatepairs;theabovetransformation
combinesaUTF16surrogatepairintoaUTF32representationandencodestheresulting21bitvalueinUTF
8.Decodingreconstructsthesurrogatepair.

RFC3629prohibitsthedecodingofinvalidUTF8octetsequences.Forexample,theinvalidsequenceC080
mustnotdecodeintothecodeunit0x0000.ImplementationsoftheDecodealgorithmarerequiredtothrowa
URIErrorwhenencounteringsuchinvalidsequences.

18.2.6.2 decodeURI(encodedURI)

ThedecodeURIfunctioncomputesanewversionofaURIinwhicheachescapesequenceandUTF8encodingofthesort
thatmightbeintroducedbytheencodeURIfunctionisreplacedwiththeUTF16encodingofthecodepointsthatit
represents.EscapesequencesthatcouldnothavebeenintroducedbyencodeURIarenotreplaced.

ThedecodeURIfunctionisthe%decodeURI%intrinsicobject.WhenthedecodeURIfunctioniscalledwithoneargument
encodedURI,thefollowingstepsaretaken:

1.LeturiStringbe?ToString(encodedURI).
2.LetreservedURISetbeaStringcontainingoneinstanceofeachcodeunitvalidinuriReservedplus"#".
3.Return?Decode(uriString,reservedURISet).

NOTE Thecodepoint"#"isnotdecodedfromescapesequenceseventhoughitisnotareservedURIcodepoint.

18.2.6.3 decodeURIComponent(encodedURIComponent)
ThedecodeURIComponentfunctioncomputesanewversionofaURIinwhicheachescapesequenceandUTF8encodingof
thesortthatmightbeintroducedbytheencodeURIComponentfunctionisreplacedwiththeUTF16encodingofthecode
pointsthatitrepresents.

ThedecodeURIComponentfunctionisthe%decodeURIComponent%intrinsicobject.WhenthedecodeURIComponent
functioniscalledwithoneargumentencodedURIComponent,thefollowingstepsaretaken:

1.LetcomponentStringbe?ToString(encodedURIComponent).
2.LetreservedURIComponentSetbetheemptyString.
3.Return?Decode(componentString,reservedURIComponentSet).

18.2.6.4 encodeURI(uri)

TheencodeURIfunctioncomputesanewversionofaUTF16encoded(6.1.4)URIinwhicheachinstanceofcertaincode
pointsisreplacedbyone,two,three,orfourescapesequencesrepresentingtheUTF8encodingofthecodepoints.

TheencodeURIfunctionisthe%encodeURI%intrinsicobject.WhentheencodeURIfunctioniscalledwithoneargument
uri,thefollowingstepsaretaken:

1.LeturiStringbe?ToString(uri).
2.LetunescapedURISetbeaStringcontainingoneinstanceofeachcodeunitvalidinuriReservedanduriUnescapedplus
"#".
3.Return?Encode(uriString,unescapedURISet).

NOTE Thecodeunit"#"isnotencodedtoanescapesequenceeventhoughitisnotareservedorunescapedURI
codepoint.

18.2.6.5 encodeURIComponent(uriComponent)

TheencodeURIComponentfunctioncomputesanewversionofaUTF16encoded(6.1.4)URIinwhicheachinstanceof
certaincodepointsisreplacedbyone,two,three,orfourescapesequencesrepresentingtheUTF8encodingofthecode
point.

TheencodeURIComponentfunctionisthe%encodeURIComponent%intrinsicobject.WhentheencodeURIComponent
functioniscalledwithoneargumenturiComponent,thefollowingstepsaretaken:

1.LetcomponentStringbe?ToString(uriComponent).
2.LetunescapedURIComponentSetbeaStringcontainingoneinstanceofeachcodeunitvalidinuriUnescaped.
3.Return?Encode(componentString,unescapedURIComponentSet).

18.3 ConstructorPropertiesoftheGlobalObject
18.3.1 Array(...)

See22.1.1.

18.3.2 ArrayBuffer(...)

See24.1.2.

18.3.3 Boolean(...)

See19.3.1.

18.3.4 DataView(...)

See24.2.2.

18.3.5 Date(...)
See20.3.2.

18.3.6 Error(...)

See19.5.1.

18.3.7 EvalError(...)

See19.5.5.1.

18.3.8 Float32Array(...)

See22.2.4.

18.3.9 Float64Array(...)

See22.2.4.

18.3.10 Function(...)

See19.2.1.

18.3.11 Int8Array(...)

See22.2.4.

18.3.12 Int16Array(...)

See22.2.4.

18.3.13 Int32Array(...)

See22.2.4.

18.3.14 Map(...)

See23.1.1.

18.3.15 Number(...)

See20.1.1.

18.3.16 Object(...)

See19.1.1.

18.3.17 Proxy(...)

See26.2.1.

18.3.18 Promise(...)

See25.4.3.

18.3.19 RangeError(...)

See19.5.5.2.

18.3.20 ReferenceError(...)

See19.5.5.3.
18.3.21 RegExp(...)

See21.2.3.

18.3.22 Set(...)

See23.2.1.

18.3.23 String(...)

See21.1.1.

18.3.24 Symbol(...)

See19.4.1.

18.3.25 SyntaxError(...)

See19.5.5.4.

18.3.26 TypeError(...)

See19.5.5.5.

18.3.27 Uint8Array(...)

See22.2.4.

18.3.28 Uint8ClampedArray(...)

See22.2.4.

18.3.29 Uint16Array(...)

See22.2.4.

18.3.30 Uint32Array(...)

See22.2.4.

18.3.31 URIError(...)

See19.5.5.6.

18.3.32 WeakMap(...)

See23.3.1.

18.3.33 WeakSet(...)

See23.4.

18.4 OtherPropertiesoftheGlobalObject
18.4.1 JSON

See24.3.

18.4.2 Math
See20.2.

18.4.3 Relect

See26.1.

19 FundamentalObjects
19.1 ObjectObjects
19.1.1 TheObjectConstructor

TheObjectconstructoristhe%Object%intrinsicobjectandtheinitialvalueoftheObjectpropertyoftheglobalobject.
Whencalledasaconstructoritcreatesanewordinaryobject.WhenObjectiscalledasafunctionratherthanasa
constructor,itperformsatypeconversion.

TheObjectconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.

19.1.1.1 Object([value])

WhenObjectfunctioniscalledwithoptionalargumentvalue,thefollowingstepsaretaken:

1.IfNewTargetisneitherundeinednortheactivefunction,then
a.Return?OrdinaryCreateFromConstructor(NewTarget,"%ObjectPrototype%").
2.Ifvalueisnull,undeinedornotsupplied,returnObjectCreate(%ObjectPrototype%).
3.ReturnToObject(value).

ThelengthpropertyoftheObjectconstructorfunctionis1.

19.1.2 PropertiesoftheObjectConstructor

Thevalueofthe[[Prototype]]internalslotoftheObjectconstructoristheintrinsicobject%FunctionPrototype%.

Besidesthelengthproperty,theObjectconstructorhasthefollowingproperties:

19.1.2.1 Object.assign(target,...sources)

Theassignfunctionisusedtocopythevaluesofalloftheenumerableownpropertiesfromoneormoresourceobjectstoa
targetobject.Whentheassignfunctioniscalled,thefollowingstepsaretaken:

1.Lettobe?ToObject(target).
2.Ifonlyoneargumentwaspassed,returnto.
3.LetsourcesbetheListofargumentvaluesstartingwiththesecondargument.
4.ForeachelementnextSourceofsources,inascendingindexorder,
a.IfnextSourceisundeinedornull,letkeysbeanewemptyList.
b.Else,
i.LetfrombeToObject(nextSource).
ii.Letkeysbe?from.[[OwnPropertyKeys]]().
c.RepeatforeachelementnextKeyofkeysinListorder,
i.Letdescbe?from.[[GetOwnProperty]](nextKey).
ii.Ifdescisnotundeinedanddesc.[[Enumerable]]istrue,then
1.LetpropValuebe?Get(from,nextKey).
2.Perform?Set(to,nextKey,propValue,true).
5.Returnto.

Thelengthpropertyoftheassignmethodis2.
19.1.2.2 Object.create(O,Properties)

Thecreatefunctioncreatesanewobjectwithaspeciiedprototype.Whenthecreatefunctioniscalled,thefollowingsteps
aretaken:

1.IfType(O)isneitherObjectnorNull,throwaTypeErrorexception.
2.LetobjbeObjectCreate(O).
3.IfPropertiesisnotundeined,then
a.Return?ObjectDeineProperties(obj,Properties).
4.Returnobj.

19.1.2.3 Object.deineProperties(O,Properties)

ThedefinePropertiesfunctionisusedtoaddownpropertiesand/orupdatetheattributesofexistingownpropertiesof
anobject.WhenthedefinePropertiesfunctioniscalled,thefollowingstepsaretaken:

1.Return?ObjectDeineProperties(O,Properties).

19.1.2.3.1 RuntimeSemantics:ObjectDeineProperties(O,Properties)

TheabstractoperationObjectDeinePropertieswithargumentsOandPropertiesperformsthefollowingsteps:

1.IfType(O)isnotObject,throwaTypeErrorexception.
2.Letpropsbe?ToObject(Properties).
3.Letkeysbe?props.[[OwnPropertyKeys]]().
4.LetdescriptorsbeanewemptyList.
5.RepeatforeachelementnextKeyofkeysinListorder,
a.LetpropDescbe?props.[[GetOwnProperty]](nextKey).
b.IfpropDescisnotundeinedandpropDesc.[[Enumerable]]istrue,then
i.LetdescObjbe?Get(props,nextKey).
ii.Letdescbe?ToPropertyDescriptor(descObj).
iii.Appendthepair(atwoelementList)consistingofnextKeyanddesctotheendofdescriptors.
6.Foreachpairfromdescriptorsinlistorder,
a.LetPbetheirstelementofpair.
b.Letdescbethesecondelementofpair.
c.Perform?DeinePropertyOrThrow(O,P,desc).
7.ReturnO.

19.1.2.4 Object.deineProperty(O,P,Attributes)

ThedefinePropertyfunctionisusedtoaddanownpropertyand/orupdatetheattributesofanexistingownpropertyof
anobject.WhenthedefinePropertyfunctioniscalled,thefollowingstepsaretaken:

1.IfType(O)isnotObject,throwaTypeErrorexception.
2.Letkeybe?ToPropertyKey(P).
3.Letdescbe?ToPropertyDescriptor(Attributes).
4.Perform?DeinePropertyOrThrow(O,key,desc).
5.ReturnO.

19.1.2.5 Object.freeze(O)

Whenthefreezefunctioniscalled,thefollowingstepsaretaken:

1.IfType(O)isnotObject,returnO.
2.Letstatusbe?SetIntegrityLevel(O,"frozen").
3.Ifstatusisfalse,throwaTypeErrorexception.
4.ReturnO.
19.1.2.6 Object.getOwnPropertyDescriptor(O,P)

WhenthegetOwnPropertyDescriptorfunctioniscalled,thefollowingstepsaretaken:

1.Letobjbe?ToObject(O).
2.Letkeybe?ToPropertyKey(P).
3.Letdescbe?obj.[[GetOwnProperty]](key).
4.ReturnFromPropertyDescriptor(desc).

19.1.2.7 Object.getOwnPropertyNames(O)

WhenthegetOwnPropertyNamesfunctioniscalled,thefollowingstepsaretaken:

1.Return?GetOwnPropertyKeys(O,String).

19.1.2.8 Object.getOwnPropertySymbols(O)

WhenthegetOwnPropertySymbolsfunctioniscalledwithargumentO,thefollowingstepsaretaken:

1.Return?GetOwnPropertyKeys(O,Symbol).

19.1.2.8.1 RuntimeSemantics:GetOwnPropertyKeys(O,Type)

TheabstractoperationGetOwnPropertyKeysiscalledwithargumentsOandTypewhereOisanObjectandTypeisoneofthe
ECMAScriptspeciicationtypesStringorSymbol.Thefollowingstepsaretaken:

1.Letobjbe?ToObject(O).
2.Letkeysbe?obj.[[OwnPropertyKeys]]().
3.LetnameListbeanewemptyList.
4.RepeatforeachelementnextKeyofkeysinListorder,
a.IfType(nextKey)isType,then
i.AppendnextKeyasthelastelementofnameList.
5.ReturnCreateArrayFromList(nameList).

19.1.2.9 Object.getPrototypeOf(O)

WhenthegetPrototypeOffunctioniscalledwithargumentO,thefollowingstepsaretaken:

1.Letobjbe?ToObject(O).
2.Return?obj.[[GetPrototypeOf]]().

19.1.2.10 Object.is(value1,value2)

Whentheisfunctioniscalledwithargumentsvalue1andvalue2,thefollowingstepsaretaken:

1.ReturnSameValue(value1,value2).

19.1.2.11 Object.isExtensible(O)

WhentheisExtensiblefunctioniscalledwithargumentO,thefollowingstepsaretaken:

1.IfType(O)isnotObject,returnfalse.
2.Return?IsExtensible(O).

19.1.2.12 Object.isFrozen(O)

WhentheisFrozenfunctioniscalledwithargumentO,thefollowingstepsaretaken:

1.IfType(O)isnotObject,returntrue.
2.Return?TestIntegrityLevel(O,"frozen").
19.1.2.13 Object.isSealed(O)

WhentheisSealedfunctioniscalledwithargumentO,thefollowingstepsaretaken:

1.IfType(O)isnotObject,returntrue.
2.Return?TestIntegrityLevel(O,"sealed").

19.1.2.14 Object.keys(O)

WhenthekeysfunctioniscalledwithargumentO,thefollowingstepsaretaken:

1.Letobjbe?ToObject(O).
2.LetnameListbe?EnumerableOwnNames(obj).
3.ReturnCreateArrayFromList(nameList).

Ifanimplementationdeinesaspeciicorderofenumerationfortheforinstatement,thesameordermustbeusedforthe
elementsofthearrayreturnedinstep3.

19.1.2.15 Object.preventExtensions(O)

WhenthepreventExtensionsfunctioniscalled,thefollowingstepsaretaken:

1.IfType(O)isnotObject,returnO.
2.Letstatusbe?O.[[PreventExtensions]]().
3.Ifstatusisfalse,throwaTypeErrorexception.
4.ReturnO.

19.1.2.16 Object.prototype

TheinitialvalueofObject.prototypeistheintrinsicobject%ObjectPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.1.2.17 Object.seal(O)

Whenthesealfunctioniscalled,thefollowingstepsaretaken:

1.IfType(O)isnotObject,returnO.
2.Letstatusbe?SetIntegrityLevel(O,"sealed").
3.Ifstatusisfalse,throwaTypeErrorexception.
4.ReturnO.

19.1.2.18 Object.setPrototypeOf(O,proto)

WhenthesetPrototypeOffunctioniscalledwithargumentsOandproto,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(O).
2.IfType(proto)isneitherObjectnorNull,throwaTypeErrorexception.
3.IfType(O)isnotObject,returnO.
4.Letstatusbe?O.[[SetPrototypeOf]](proto).
5.Ifstatusisfalse,throwaTypeErrorexception.
6.ReturnO.

19.1.3 PropertiesoftheObjectPrototypeObject

TheObjectprototypeobjectistheintrinsicobject%ObjectPrototype%.TheObjectprototypeobjectisanimmutable
prototypeexoticobject.

Thevalueofthe[[Prototype]]internalslotoftheObjectprototypeobjectisnullandtheinitialvalueofthe[[Extensible]]
internalslotistrue.
19.1.3.1 Object.prototype.constructor

TheinitialvalueofObject.prototype.constructoristheintrinsicobject%Object%.

19.1.3.2 Object.prototype.hasOwnProperty(V)

WhenthehasOwnPropertymethodiscalledwithargumentV,thefollowingstepsaretaken:

1.LetPbe?ToPropertyKey(V).
2.LetObe?ToObject(thisvalue).
3.Return?HasOwnProperty(O,P).

NOTE Theorderingofsteps1and2ischosentoensurethatanyexceptionthatwouldhavebeenthrownbystep1in
previouseditionsofthisspeciicationwillcontinuetobethrownevenifthethisvalueisundeinedornull.

19.1.3.3 Object.prototype.isPrototypeOf(V)

WhentheisPrototypeOfmethodiscalledwithargumentV,thefollowingstepsaretaken:

1.IfType(V)isnotObject,returnfalse.
2.LetObe?ToObject(thisvalue).
3.Repeat
a.LetVbe?V.[[GetPrototypeOf]]().
b.IfVisnull,returnfalse.
c.IfSameValue(O,V)istrue,returntrue.

NOTE Theorderingofsteps1and2preservesthebehaviourspeciiedbypreviouseditionsofthisspeciicationfor
thecasewhereVisnotanobjectandthethisvalueisundeinedornull.

19.1.3.4 Object.prototype.propertyIsEnumerable(V)

WhenthepropertyIsEnumerablemethodiscalledwithargumentV,thefollowingstepsaretaken:

1.LetPbe?ToPropertyKey(V).
2.LetObe?ToObject(thisvalue).
3.Letdescbe?O.[[GetOwnProperty]](P).
4.Ifdescisundeined,returnfalse.
5.Returnthevalueofdesc.[[Enumerable]].

NOTE1 Thismethoddoesnotconsiderobjectsintheprototypechain.

NOTE2 Theorderingofsteps1and2ischosentoensurethatanyexceptionthatwouldhavebeenthrownbystep1in
previouseditionsofthisspeciicationwillcontinuetobethrownevenifthethisvalueisundeinedornull.

19.1.3.5 Object.prototype.toLocaleString([reserved1[,reserved2]])

WhenthetoLocaleStringmethodiscalled,thefollowingstepsaretaken:

1.LetObethethisvalue.
2.Return?Invoke(O,"toString").

Theoptionalparameterstothisfunctionarenotusedbutareintendedtocorrespondtotheparameterpatternusedby
ECMA402toLocalStringfunctions.ImplementationsthatdonotincludeECMA402supportmustnotusethose
parameterpositionsforotherpurposes.

NOTE1 ThisfunctionprovidesagenerictoLocaleStringimplementationforobjectsthathavenolocalespeciic
toStringbehaviour.Array,Number,Date,andTypedArraysprovidetheirownlocalesensitive
toLocaleStringmethods.

NOTE2 ECMA402intentionallydoesnotprovideanalternativetothisdefaultimplementation.
19.1.3.6 Object.prototype.toString()

WhenthetoStringmethodiscalled,thefollowingstepsaretaken:

1.Ifthethisvalueisundeined,return"[objectUndefined]".
2.Ifthethisvalueisnull,return"[objectNull]".
3.LetObeToObject(thisvalue).
4.LetisArraybe?IsArray(O).
5.IfisArrayistrue,letbuiltinTagbe"Array".
6.Else,ifOisanexoticStringobject,letbuiltinTagbe"String".
7.Else,ifOhasan[[ParameterMap]]internalslot,letbuiltinTagbe"Arguments".
8.Else,ifOhasa[[Call]]internalmethod,letbuiltinTagbe"Function".
9.Else,ifOhasan[[ErrorData]]internalslot,letbuiltinTagbe"Error".
10.Else,ifOhasa[[BooleanData]]internalslot,letbuiltinTagbe"Boolean".
11.Else,ifOhasa[[NumberData]]internalslot,letbuiltinTagbe"Number".
12.Else,ifOhasa[[DateValue]]internalslot,letbuiltinTagbe"Date".
13.Else,ifOhasa[[RegExpMatcher]]internalslot,letbuiltinTagbe"RegExp".
14.Else,letbuiltinTagbe"Object".
15.Lettagbe?Get(O,@@toStringTag).
16.IfType(tag)isnotString,lettagbebuiltinTag.
17.ReturntheStringthatistheresultofconcatenating"[object",tag,and"]".

Thisfunctionisthe%ObjProto_toString%intrinsicobject.

NOTE Historically,thisfunctionwasoccasionallyusedtoaccesstheStringvalueofthe[[Class]]internalslotthatwas
usedinpreviouseditionsofthisspeciicationasanominaltypetagforvariousbuiltinobjects.Theabove
deinitionoftoStringpreservescompatibilityforlegacycodethatusestoStringasatestforthosespeciic
kindsofbuiltinobjects.Itdoesnotprovideareliabletypetestingmechanismforotherkindsofbuiltinor
programdeinedobjects.Inaddition,programscanuse@@toStringTaginwaysthatwillinvalidatethe
reliabilityofsuchlegacytypetests.

19.1.3.7 Object.prototype.valueOf()

WhenthevalueOfmethodiscalled,thefollowingstepsaretaken:

1.Return?ToObject(thisvalue).

Thisfunctionisthe%ObjProto_valueOf%intrinsicobject.

19.1.4 PropertiesofObjectInstances

ObjectinstanceshavenospecialpropertiesbeyondthoseinheritedfromtheObjectprototypeobject.

19.2 FunctionObjects
19.2.1 TheFunctionConstructor

TheFunctionconstructoristhe%Function%intrinsicobjectandtheinitialvalueoftheFunctionpropertyoftheglobal
object.WhenFunctioniscalledasafunctionratherthanasaconstructor,itcreatesandinitializesanewFunctionobject.
ThusthefunctioncallFunction()isequivalenttotheobjectcreationexpressionnewFunction()withthesame
arguments.

TheFunctionconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedFunctionbehaviourmustincludeasupercalltothe
Functionconstructortocreateandinitializeasubclassinstanceswiththeinternalslotsnecessaryforbuiltinfunction
behaviour.AllECMAScriptsyntacticformsfordeiningfunctionobjectscreateinstancesofFunction.Thereisnosyntactic
meanstocreateinstancesofFunctionsubclassesexceptforthebuiltinGeneratorFunctionsubclass.

19.2.1.1 Function(p1,p2,,pn,body)

Thelastargumentspeciiesthebody(executablecode)ofafunction;anyprecedingargumentsspecifyformalparameters.

WhentheFunctionfunctioniscalledwithsomeargumentsp1,p2,,pn,body(wherenmightbe0,thatis,therearenop
arguments,andwherebodymightalsonotbeprovided),thefollowingstepsaretaken:

1.LetCbetheactivefunctionobject.
2.LetargsbetheargumentsListthatwaspassedtothisfunctionby[[Call]]or[[Construct]].
3.Return?CreateDynamicFunction(C,NewTarget,"normal",args).

NOTE Itispermissiblebutnotnecessarytohaveoneargumentforeachformalparametertobespeciied.For
example,allthreeofthefollowingexpressionsproducethesameresult:

newFunction("a","b","c","returna+b+c")
newFunction("a,b,c","returna+b+c")
newFunction("a,b","c","returna+b+c")

19.2.1.1.1 RuntimeSemantics:CreateDynamicFunction(constructor,newTarget,kind,args)

TheabstractoperationCreateDynamicFunctioniscalledwithargumentsconstructor,newTarget,kind,andargs.constructor
istheconstructorfunctionthatisperformingthisaction,newTargetistheconstructorthatnewwasinitiallyappliedto,kind
iseither"normal"or"generator",andargsisaListcontainingtheactualargumentvaluesthatwerepassedto
constructor.Thefollowingstepsaretaken:

1.IfnewTargetisundeined,letnewTargetbeconstructor.
2.Ifkindis"normal",then
a.LetgoalbethegrammarsymbolFunctionBody.
b.LetparameterGoalbethegrammarsymbolFormalParameters.
c.LetfallbackProtobe"%FunctionPrototype%".
3.Else,
a.LetgoalbethegrammarsymbolGeneratorBody.
b.LetparameterGoalbethegrammarsymbolFormalParameters[Yield] .
c.LetfallbackProtobe"%Generator%".
4.LetargCountbethenumberofelementsinargs.
5.LetPbetheemptyString.
6.IfargCount=0,letbodyTextbetheemptyString.
7.ElseifargCount=1,letbodyTextbeargs[0].
8.ElseargCount>1,
a.LetirstArgbeargs[0].
b.LetPbe?ToString(irstArg).
c.Letkbe1.
d.Repeat,whilek<argCount1
i.LetnextArgbeargs[k].
ii.LetnextArgStringbe?ToString(nextArg).
iii.LetPbetheresultofconcatenatingthepreviousvalueofP,theString","(acomma),andnextArgString.
iv.Increasekby1.
e.LetbodyTextbeargs[k].
9.LetbodyTextbe?ToString(bodyText).
10.LetparametersbetheresultofparsingP,interpretedasUTF16encodedUnicodetextasdescribedin6.1.4,using
parameterGoalasthegoalsymbol.ThrowaSyntaxErrorexceptioniftheparsefails.
11.LetbodybetheresultofparsingbodyText,interpretedasUTF16encodedUnicodetextasdescribedin6.1.4,usinggoal
asthegoalsymbol.ThrowaSyntaxErrorexceptioniftheparsefails.
12.IfbodyTextisstrictmodecode,thenletstrictbetrue,elseletstrictbefalse.
13.Ifanystaticsemanticserrorsaredetectedforparametersorbody,throwaSyntaxErrororaReferenceErrorexception,
dependingonthetypeoftheerror.Ifstrictistrue,theEarlyErrorrulesforStrictFormalParameters :
FormalParameters areapplied.Parsingandearlyerrordetectionmaybeinterweavedinanimplementation
dependentmanner.
14.IfContainsUseStrictofbodyistrueandIsSimpleParameterListofparametersisfalse,throwaSyntaxErrorexception.
15.IfanyelementoftheBoundNamesofparametersalsooccursintheLexicallyDeclaredNamesofbody,throwa
SyntaxErrorexception.
16.IfbodyContainsSuperCallistrue,throwaSyntaxErrorexception.
17.IfparametersContainsSuperCallistrue,throwaSyntaxErrorexception.
18.IfbodyContainsSuperPropertyistrue,throwaSyntaxErrorexception.
19.IfparametersContainsSuperPropertyistrue,throwaSyntaxErrorexception.
20.Ifkindis"generator",then
a.IfparametersContainsYieldExpressionistrue,throwaSyntaxErrorexception.
21.Ifstrictistrue,then
a.IfBoundNamesofparameterscontainsanyduplicateelements,throwaSyntaxErrorexception.
22.Letprotobe?GetPrototypeFromConstructor(newTarget,fallbackProto).
23.LetFbeFunctionAllocate(proto,strict,kind).
24.LetrealmFbethevalueofF's[[Realm]]internalslot.
25.LetscopeberealmF.[[GlobalEnv]].
26.PerformFunctionInitialize(F,Normal,parameters,body,scope).
27.Ifkindis"generator",then
a.LetprototypebeObjectCreate(%GeneratorPrototype%).
b.PerformDeinePropertyOrThrow(F,"prototype",PropertyDescriptor{[[Value]]:prototype,[[Writable]]:true,
[[Enumerable]]:false,[[Conigurable]]:false}).
28.Else,performMakeConstructor(F).
29.PerformSetFunctionName(F,"anonymous").
30.ReturnF.

NOTE AprototypepropertyisautomaticallycreatedforeveryfunctioncreatedusingCreateDynamicFunction,to
provideforthepossibilitythatthefunctionwillbeusedasaconstructor.

19.2.2 PropertiesoftheFunctionConstructor

TheFunctionconstructorisitselfabuiltinfunctionobject.Thevalueofthe[[Prototype]]internalslotoftheFunction
constructoristheintrinsicobject%FunctionPrototype%.

Thevalueofthe[[Extensible]]internalslotoftheFunctionconstructoristrue.

TheFunctionconstructorhasthefollowingproperties:

19.2.2.1 Function.length

Thisisadatapropertywithavalueof1.Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,
[[Conigurable]]:true}.

19.2.2.2 Function.prototype

ThevalueofFunction.prototypeis%FunctionPrototype%,theintrinsicFunctionprototypeobject.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.2.3 PropertiesoftheFunctionPrototypeObject

TheFunctionprototypeobjectistheintrinsicobject%FunctionPrototype%.TheFunctionprototypeobjectisitselfabuiltin
functionobject.Wheninvoked,itacceptsanyargumentsandreturnsundeined.Itdoesnothavea[[Construct]]internal
methodsoitisnotaconstructor.
NOTE TheFunctionprototypeobjectisspeciiedtobeafunctionobjecttoensurecompatibilitywithECMAScript
codethatwascreatedpriortotheECMAScript2015speciication.

Thevalueofthe[[Prototype]]internalslotoftheFunctionprototypeobjectistheintrinsicobject%ObjectPrototype%.The
initialvalueofthe[[Extensible]]internalslotoftheFunctionprototypeobjectistrue.

TheFunctionprototypeobjectdoesnothaveaprototypeproperty.

ThevalueofthelengthpropertyoftheFunctionprototypeobjectis0.

ThevalueofthenamepropertyoftheFunctionprototypeobjectistheemptyString.

19.2.3.1 Function.prototype.apply(thisArg,argArray)

WhentheapplymethodiscalledonanobjectfuncwithargumentsthisArgandargArray,thefollowingstepsaretaken:

1.IfIsCallable(func)isfalse,throwaTypeErrorexception.
2.IfargArrayisnullorundeined,then
a.PerformPrepareForTailCall().
b.Return?Call(func,thisArg).
3.LetargListbe?CreateListFromArrayLike(argArray).
4.PerformPrepareForTailCall().
5.Return?Call(func,thisArg,argList).

NOTE1 ThethisArgvalueispassedwithoutmodiicationasthethisvalue.ThisisachangefromEdition3,wherean
undeinedornullthisArgisreplacedwiththeglobalobjectandToObjectisappliedtoallothervaluesandthat
resultispassedasthethisvalue.EventhoughthethisArgispassedwithoutmodiication,nonstrictfunctions
stillperformthesetransformationsuponentrytothefunction.

NOTE2 IffuncisanarrowfunctionoraboundfunctionthenthethisArgwillbeignoredbythefunction[[Call]]instep
5.

19.2.3.2 Function.prototype.bind(thisArg,...args)

WhenthebindmethodiscalledwithargumentthisArgandzeroormoreargs,itperformsthefollowingsteps:

1.LetTargetbethethisvalue.
2.IfIsCallable(Target)isfalse,throwaTypeErrorexception.
3.Letargsbeanew(possiblyempty)ListconsistingofalloftheargumentvaluesprovidedafterthisArginorder.
4.LetFbe?BoundFunctionCreate(Target,thisArg,args).
5.LettargetHasLengthbe?HasOwnProperty(Target,"length").
6.IftargetHasLengthistrue,then
a.LettargetLenbe?Get(Target,"length").
b.IfType(targetLen)isnotNumber,letLbe0.
c.Else,
i.LettargetLenbeToInteger(targetLen).
ii.LetLbethelargerof0andtheresultoftargetLenminusthenumberofelementsofargs.
7.ElseletLbe0.
8.Perform!DeinePropertyOrThrow(F,"length",PropertyDescriptor{[[Value]]:L,[[Writable]]:false,[[Enumerable]]:
false,[[Conigurable]]:true}).
9.LettargetNamebe?Get(Target,"name").
10.IfType(targetName)isnotString,lettargetNamebetheemptystring.
11.PerformSetFunctionName(F,targetName,"bound").
12.ReturnF.

NOTE1 FunctionobjectscreatedusingFunction.prototype.bindareexoticobjects.Theyalsodonothavea
prototypeproperty.
NOTE2 IfTargetisanarrowfunctionoraboundfunctionthenthethisArgpassedtothismethodwillnotbeusedby
subsequentcallstoF.

19.2.3.3 Function.prototype.call(thisArg,...args)

Whenthecallmethodiscalledonanobjectfuncwithargument,thisArgandzeroormoreargs,thefollowingstepsare
taken:

1.IfIsCallable(func)isfalse,throwaTypeErrorexception.
2.LetargListbeanewemptyList.
3.Ifthismethodwascalledwithmorethanoneargument,theninlefttorightorder,startingwiththesecondargument,
appendeachargumentasthelastelementofargList.
4.PerformPrepareForTailCall().
5.Return?Call(func,thisArg,argList).

NOTE1 ThethisArgvalueispassedwithoutmodiicationasthethisvalue.ThisisachangefromEdition3,wherean
undeinedornullthisArgisreplacedwiththeglobalobjectandToObjectisappliedtoallothervaluesandthat
resultispassedasthethisvalue.EventhoughthethisArgispassedwithoutmodiication,nonstrictfunctions
stillperformthesetransformationsuponentrytothefunction.

NOTE2 IffuncisanarrowfunctionoraboundfunctionthenthethisArgwillbeignoredbythefunction[[Call]]instep
5.

19.2.3.4 Function.prototype.constructor

TheinitialvalueofFunction.prototype.constructoristheintrinsicobject%Function%.

19.2.3.5 Function.prototype.toString()

WhenthetoStringmethodiscalledonanobjectfunc,thefollowingstepsaretaken:

1.IffuncisaBoundFunctionexoticobject,then
a.ReturnanimplementationdependentStringsourcecoderepresentationoffunc.Therepresentationmustconform
totherulesbelow.Itisimplementationdependentwhethertherepresentationincludesboundfunction
informationorinformationaboutthetargetfunction.
2.IfType(func)isObjectandiseitherabuiltinfunctionobjectorhasan[[ECMAScriptCode]]internalslot,then
a.ReturnanimplementationdependentStringsourcecoderepresentationoffunc.Therepresentationmustconform
totherulesbelow.
3.ThrowaTypeErrorexception.

toStringRepresentationRequirements:

ThestringrepresentationmusthavethesyntaxofaFunctionDeclaration,FunctionExpression,GeneratorDeclaration,
GeneratorExpression,ClassDeclaration,ClassExpression,ArrowFunction,MethodDeinition,orGeneratorMethod
dependingupontheactualcharacteristicsoftheobject.
Theuseandplacementofwhitespace,lineterminators,andsemicolonswithintherepresentationStringis
implementationdependent.
IftheobjectwasdeinedusingECMAScriptcodeandthereturnedstringrepresentationisnotintheformofa
MethodDeinitionorGeneratorMethodthentherepresentationmustbesuchthatifthestringisevaluated,usingevalin
alexicalcontextthatisequivalenttothelexicalcontextusedtocreatetheoriginalobject,itwillresultinanew
functionallyequivalentobject.Inthatcasethereturnedsourcecodemustnotmentionfreelyanyvariablesthatwere
notmentionedfreelybytheoriginalfunction'ssourcecode,eveniftheseextranameswereoriginallyinscope.
Iftheimplementationcannotproduceasourcecodestringthatmeetsthesecriteriathenitmustreturnastringfor
whichevalwillthrowaSyntaxErrorexception.

19.2.3.6 Function.prototype[@@hasInstance](V)

Whenthe@@hasInstancemethodofanobjectFiscalledwithvalueV,thefollowingstepsaretaken:
1.LetFbethethisvalue.
2.Return?OrdinaryHasInstance(F,V).

Thevalueofthenamepropertyofthisfunctionis"[Symbol.hasInstance]".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

NOTE Thisisthedefaultimplementationof@@hasInstancethatmostfunctionsinherit.@@hasInstanceiscalledby
theinstanceofoperatortodeterminewhetheravalueisaninstanceofaspeciicconstructor.Anexpression
suchas

vinstanceofF

evaluatesas

F[@@hasInstance](v)

Aconstructorfunctioncancontrolwhichobjectsarerecognizedasitsinstancesbyinstanceofbyexposinga
different@@hasInstancemethodonthefunction.

Thispropertyisnonwritableandnonconigurabletopreventtamperingthatcouldbeusedtogloballyexposethetarget
functionofaboundfunction.

19.2.4 FunctionInstances

EveryfunctioninstanceisanECMAScriptfunctionobjectandhastheinternalslotslistedinTable27.Functioninstances
createdusingtheFunction.prototype.bindmethod(19.2.3.2)havetheinternalslotslistedinTable28.

TheFunctioninstanceshavethefollowingproperties:

19.2.4.1 length

Thevalueofthelengthpropertyisanintegerthatindicatesthetypicalnumberofargumentsexpectedbythefunction.
However,thelanguagepermitsthefunctiontobeinvokedwithsomeothernumberofarguments.Thebehaviourofa
functionwheninvokedonanumberofargumentsotherthanthenumberspeciiedbyitslengthpropertydependsonthe
function.Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

19.2.4.2 name

ThevalueofthenamepropertyisanStringthatisdescriptiveofthefunction.Thenamehasnosemanticsigniicancebutis
typicallyavariableorpropertynamethatisusedtorefertothefunctionatitspointofdeinitioninECMAScriptcode.This
propertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

Anonymousfunctionsobjectsthatdonothaveacontextualnameassociatedwiththembythisspeciicationdonothavea
nameownpropertybutinheritthenamepropertyof%FunctionPrototype%.

19.2.4.3 prototype

Functioninstancesthatcanbeusedasaconstructorhaveaprototypeproperty.Wheneversuchafunctioninstanceis
createdanotherordinaryobjectisalsocreatedandistheinitialvalueofthefunction'sprototypeproperty.Unless
otherwisespeciied,thevalueoftheprototypepropertyisusedtoinitializethe[[Prototype]]internalslotoftheobject
createdwhenthatfunctionisinvokedasaconstructor.

Thispropertyhastheattributes{[[Writable]]:true,[[Enumerable]]:false,[[Conigurable]]:false}.

NOTE FunctionobjectscreatedusingFunction.prototype.bind,orbyevaluatingaMethodDeinition(thatarenot
aGeneratorMethod)oranArrowFunctiongrammarproductiondonothaveaprototypeproperty.

19.3 BooleanObjects
19.3.1 TheBooleanConstructor

TheBooleanconstructoristhe%Boolean%intrinsicobjectandtheinitialvalueoftheBooleanpropertyoftheglobalobject.
WhencalledasaconstructoritcreatesandinitializesanewBooleanobject.WhenBooleaniscalledasafunctionrather
thanasaconstructor,itperformsatypeconversion.

TheBooleanconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedBooleanbehaviourmustincludeasupercalltothe
Booleanconstructortocreateandinitializethesubclassinstancewitha[[BooleanData]]internalslot.

19.3.1.1 Boolean(value)

WhenBooleaniscalledwithargumentvalue,thefollowingstepsaretaken:

1.LetbbeToBoolean(value).
2.IfNewTargetisundeined,returnb.
3.LetObe?OrdinaryCreateFromConstructor(NewTarget,"%BooleanPrototype%",[[BooleanData]]).
4.SetthevalueofO's[[BooleanData]]internalslottob.
5.ReturnO.

19.3.2 PropertiesoftheBooleanConstructor

Thevalueofthe[[Prototype]]internalslotoftheBooleanconstructoristheintrinsicobject%FunctionPrototype%.

TheBooleanconstructorhasthefollowingproperties:

19.3.2.1 Boolean.prototype

TheinitialvalueofBoolean.prototypeistheintrinsicobject%BooleanPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.3.3 PropertiesoftheBooleanPrototypeObject

TheBooleanprototypeobjectistheintrinsicobject%BooleanPrototype%.TheBooleanprototypeobjectisanordinary
object.TheBooleanprototypeisitselfaBooleanobject;ithasa[[BooleanData]]internalslotwiththevaluefalse.

Thevalueofthe[[Prototype]]internalslotoftheBooleanprototypeobjectistheintrinsicobject%ObjectPrototype%.

19.3.3.1 thisBooleanValue(value)

TheabstractoperationthisBooleanValue(value)performsthefollowingsteps:

1.IfType(value)isBoolean,returnvalue.
2.IfType(value)isObjectandvaluehasa[[BooleanData]]internalslot,then
a.Assert:value's[[BooleanData]]internalslotisaBooleanvalue.
b.Returnthevalueofvalue's[[BooleanData]]internalslot.
3.ThrowaTypeErrorexception.

19.3.3.2 Boolean.prototype.constructor

TheinitialvalueofBoolean.prototype.constructoristheintrinsicobject%Boolean%.

19.3.3.3 Boolean.prototype.toString()

Thefollowingstepsaretaken:

1.Letbbe?thisBooleanValue(thisvalue).
2.Ifbistrue,return"true";elsereturn"false".
19.3.3.4 Boolean.prototype.valueOf()

Thefollowingstepsaretaken:

1.Return?thisBooleanValue(thisvalue).

19.3.4 PropertiesofBooleanInstances

BooleaninstancesareordinaryobjectsthatinheritpropertiesfromtheBooleanprototypeobject.Booleaninstanceshavea
[[BooleanData]]internalslot.The[[BooleanData]]internalslotistheBooleanvaluerepresentedbythisBooleanobject.

19.4 SymbolObjects
19.4.1 TheSymbolConstructor

TheSymbolconstructoristhe%Symbol%intrinsicobjectandtheinitialvalueoftheSymbolpropertyoftheglobalobject.
WhenSymboliscalledasafunction,itreturnsanewSymbolvalue.

TheSymbolconstructorisnotintendedtobeusedwiththenewoperatorortobesubclassed.Itmaybeusedasthevalueof
anextendsclauseofaclassdeinitionbutasupercalltotheSymbolconstructorwillcauseanexception.

19.4.1.1 Symbol([description])

WhenSymboliscalledwithoptionalargumentdescription,thefollowingstepsaretaken:

1.IfNewTargetisnotundeined,throwaTypeErrorexception.
2.Ifdescriptionisundeined,letdescStringbeundeined.
3.Else,letdescStringbe?ToString(description).
4.ReturnanewuniqueSymbolvaluewhose[[Description]]valueisdescString.

19.4.2 PropertiesoftheSymbolConstructor

Thevalueofthe[[Prototype]]internalslotoftheSymbolconstructoristheintrinsicobject%FunctionPrototype%.

TheSymbolconstructorhasthefollowingproperties:

19.4.2.1 Symbol.for(key)

WhenSymbol.foriscalledwithargumentkeyitperformsthefollowingsteps:

1.LetstringKeybe?ToString(key).
2.ForeachelementeoftheGlobalSymbolRegistryList,
a.IfSameValue(e.[[Key]],stringKey)istrue,returne.[[Symbol]].
3.Assert:GlobalSymbolRegistrydoesnotcurrentlycontainanentryforstringKey.
4.LetnewSymbolbeanewuniqueSymbolvaluewhose[[Description]]valueisstringKey.
5.AppendtheRecord{[[Key]]:stringKey,[[Symbol]]:newSymbol}totheGlobalSymbolRegistryList.
6.ReturnnewSymbol.

TheGlobalSymbolRegistryisaListthatisgloballyavailable.Itissharedbyallrealms.Priortotheevaluationofany
ECMAScriptcodeitisinitializedasanewemptyList.ElementsoftheGlobalSymbolRegistryareRecordswiththestructure
deinedinTable45.

Table45:GlobalSymbolRegistryRecordFields
FieldName Value Usage

[[Key]] AString AstringkeyusedtogloballyidentifyaSymbol.

[[Symbol]] ASymbol Asymbolthatcanberetrievedfromanyrealm.


19.4.2.2 Symbol.hasInstance

TheinitialvalueofSymbol.hasInstanceisthewellknownsymbol@@hasInstance(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.3 Symbol.isConcatSpreadable

TheinitialvalueofSymbol.isConcatSpreadableisthewellknownsymbol@@isConcatSpreadable(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.4 Symbol.iterator

TheinitialvalueofSymbol.iteratoristhewellknownsymbol@@iterator(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.5 Symbol.keyFor(sym)

WhenSymbol.keyForiscalledwithargumentsymitperformsthefollowingsteps:

1.IfType(sym)isnotSymbol,throwaTypeErrorexception.
2.ForeachelementeoftheGlobalSymbolRegistryList(see19.4.2.1),
a.IfSameValue(e.[[Symbol]],sym)istrue,returne.[[Key]].
3.Assert:GlobalSymbolRegistrydoesnotcurrentlycontainanentryforsym.
4.Returnundeined.

19.4.2.6 Symbol.match

TheinitialvalueofSymbol.matchisthewellknownsymbol@@match(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.7 Symbol.prototype

TheinitialvalueofSymbol.prototypeistheintrinsicobject%SymbolPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.8 Symbol.replace

TheinitialvalueofSymbol.replaceisthewellknownsymbol@@replace(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.9 Symbol.search

TheinitialvalueofSymbol.searchisthewellknownsymbol@@search(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.10 Symbol.species

TheinitialvalueofSymbol.speciesisthewellknownsymbol@@species(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.11 Symbol.split

TheinitialvalueofSymbol.splitisthewellknownsymbol@@split(Table1).
Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.12 Symbol.toPrimitive

TheinitialvalueofSymbol.toPrimitiveisthewellknownsymbol@@toPrimitive(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.13 Symbol.toStringTag

TheinitialvalueofSymbol.toStringTagisthewellknownsymbol@@toStringTag(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.2.14 Symbol.unscopables

TheinitialvalueofSymbol.unscopablesisthewellknownsymbol@@unscopables(Table1).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.4.3 PropertiesoftheSymbolPrototypeObject

TheSymbolprototypeobjectistheintrinsicobject%SymbolPrototype%.TheSymbolprototypeobjectisanordinaryobject.
ItisnotaSymbolinstanceanddoesnothavea[[SymbolData]]internalslot.

Thevalueofthe[[Prototype]]internalslotoftheSymbolprototypeobjectistheintrinsicobject%ObjectPrototype%.

19.4.3.1 Symbol.prototype.constructor

TheinitialvalueofSymbol.prototype.constructoristheintrinsicobject%Symbol%.

19.4.3.2 Symbol.prototype.toString()

Thefollowingstepsaretaken:

1.Letsbethethisvalue.
2.IfType(s)isSymbol,letsymbes.
3.Else,
a.IfType(s)isnotObject,throwaTypeErrorexception.
b.Ifsdoesnothavea[[SymbolData]]internalslot,throwaTypeErrorexception.
c.Letsymbethevalueofs's[[SymbolData]]internalslot.
4.ReturnSymbolDescriptiveString(sym).

19.4.3.2.1 RuntimeSemantics:SymbolDescriptiveString(sym)

WhentheabstractoperationSymbolDescriptiveStringiscalledwithargumentsym,thefollowingstepsaretaken:

1.Assert:Type(sym)isSymbol.
2.Letdescbesym's[[Description]]value.
3.Ifdescisundeined,letdescbetheemptystring.
4.Assert:Type(desc)isString.
5.Returntheresultofconcatenatingthestrings"Symbol(",desc,and")".

19.4.3.3 Symbol.prototype.valueOf()

Thefollowingstepsaretaken:

1.Letsbethethisvalue.
2.IfType(s)isSymbol,returns.
3.IfType(s)isnotObject,throwaTypeErrorexception.
4.Ifsdoesnothavea[[SymbolData]]internalslot,throwaTypeErrorexception.
5.Returnthevalueofs's[[SymbolData]]internalslot.

19.4.3.4 Symbol.prototype[@@toPrimitive](hint)

ThisfunctioniscalledbyECMAScriptlanguageoperatorstoconvertaSymbolobjecttoaprimitivevalue.Theallowedvalues
forhintare"default","number",and"string".

Whenthe@@toPrimitivemethodiscalledwithargumenthint,thefollowingstepsaretaken:

1.Letsbethethisvalue.
2.IfType(s)isSymbol,returns.
3.IfType(s)isnotObject,throwaTypeErrorexception.
4.Ifsdoesnothavea[[SymbolData]]internalslot,throwaTypeErrorexception.
5.Returnthevalueofs's[[SymbolData]]internalslot.

Thevalueofthenamepropertyofthisfunctionis"[Symbol.toPrimitive]".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

19.4.3.5 Symbol.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"Symbol".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

19.4.4 PropertiesofSymbolInstances

SymbolinstancesareordinaryobjectsthatinheritpropertiesfromtheSymbolprototypeobject.Symbolinstanceshavea
[[SymbolData]]internalslot.The[[SymbolData]]internalslotistheSymbolvaluerepresentedbythisSymbolobject.

19.5 ErrorObjects
InstancesofErrorobjectsarethrownasexceptionswhenruntimeerrorsoccur.TheErrorobjectsmayalsoserveasbase
objectsforuserdeinedexceptionclasses.

19.5.1 TheErrorConstructor

TheErrorconstructoristhe%Error%intrinsicobjectandtheinitialvalueoftheErrorpropertyoftheglobalobject.When
Erroriscalledasafunctionratherthanasaconstructor,itcreatesandinitializesanewErrorobject.Thusthefunctioncall
Error()isequivalenttotheobjectcreationexpressionnewError()withthesamearguments.

TheErrorconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedErrorbehaviourmustincludeasupercalltotheError
constructortocreateandinitializesubclassinstanceswitha[[ErrorData]]internalslot.

19.5.1.1 Error(message)

WhentheErrorfunctioniscalledwithargumentmessage,thefollowingstepsaretaken:

1.IfNewTargetisundeined,letnewTargetbetheactivefunctionobject,elseletnewTargetbeNewTarget.
2.LetObe?OrdinaryCreateFromConstructor(newTarget,"%ErrorPrototype%",[[ErrorData]]).
3.Ifmessageisnotundeined,then
a.Letmsgbe?ToString(message).
b.LetmsgDescbethePropertyDescriptor{[[Value]]:msg,[[Writable]]:true,[[Enumerable]]:false,[[Conigurable]]:
true}.
c.Perform!DeinePropertyOrThrow(O,"message",msgDesc).
4.ReturnO.

19.5.2 PropertiesoftheErrorConstructor
Thevalueofthe[[Prototype]]internalslotoftheErrorconstructoristheintrinsicobject%FunctionPrototype%.

TheErrorconstructorhasthefollowingproperties:

19.5.2.1 Error.prototype

TheinitialvalueofError.prototypeistheintrinsicobject%ErrorPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.5.3 PropertiesoftheErrorPrototypeObject

TheErrorprototypeobjectistheintrinsicobject%ErrorPrototype%.TheErrorprototypeobjectisanordinaryobject.Itis
notanErrorinstanceanddoesnothavean[[ErrorData]]internalslot.

Thevalueofthe[[Prototype]]internalslotoftheErrorprototypeobjectistheintrinsicobject%ObjectPrototype%.

19.5.3.1 Error.prototype.constructor

TheinitialvalueofError.prototype.constructoristheintrinsicobject%Error%.

19.5.3.2 Error.prototype.message

TheinitialvalueofError.prototype.messageistheemptyString.

19.5.3.3 Error.prototype.name

TheinitialvalueofError.prototype.nameis"Error".

19.5.3.4 Error.prototype.toString()

Thefollowingstepsaretaken:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.Letnamebe?Get(O,"name").
4.Ifnameisundeined,letnamebe"Error";otherwiseletnamebe?ToString(name).
5.Letmsgbe?Get(O,"message").
6.Ifmsgisundeined,letmsgbetheemptyString;otherwiseletmsgbe?ToString(msg).
7.IfnameistheemptyString,returnmsg.
8.IfmsgistheemptyString,returnname.
9.Returntheresultofconcatenatingname,thecodeunit0x003A(COLON),thecodeunit0x0020(SPACE),andmsg.

19.5.4 PropertiesofErrorInstances

ErrorinstancesareordinaryobjectsthatinheritpropertiesfromtheErrorprototypeobjectandhavean[[ErrorData]]
internalslotwhosevalueisundeined.Theonlyspeciiedusesof[[ErrorData]]istoidentifyErrorandNativeErrorinstances
asErrorobjectswithinObject.prototype.toString.

19.5.5 NativeErrorTypesUsedinThisStandard

AnewinstanceofoneoftheNativeErrorobjectsbelowisthrownwhenaruntimeerrorisdetected.Alloftheseobjectsshare
thesamestructure,asdescribedin19.5.6.

19.5.5.1 EvalError

Thisexceptionisnotcurrentlyusedwithinthisspeciication.Thisobjectremainsforcompatibilitywithpreviouseditionsof
thisspeciication.

19.5.5.2 RangeError
Indicatesavaluethatisnotinthesetorrangeofallowablevalues.

19.5.5.3 ReferenceError

Indicatethataninvalidreferencevaluehasbeendetected.

19.5.5.4 SyntaxError

Indicatesthataparsingerrorhasoccurred.

19.5.5.5 TypeError

TypeErrorisusedtoindicateanunsuccessfuloperationwhennoneoftheotherNativeErrorobjectsareanappropriate
indicationofthefailurecause.

19.5.5.6 URIError

IndicatesthatoneoftheglobalURIhandlingfunctionswasusedinawaythatisincompatiblewithitsdeinition.

19.5.6 NativeErrorObjectStructure

WhenanECMAScriptimplementationdetectsaruntimeerror,itthrowsanewinstanceofoneoftheNativeErrorobjects
deinedin19.5.5.Eachoftheseobjectshasthestructuredescribedbelow,differingonlyinthenameusedastheconstructor
nameinsteadofNativeError,inthenamepropertyoftheprototypeobject,andintheimplementationdeinedmessage
propertyoftheprototypeobject.

Foreacherrorobject,referencestoNativeErrorinthedeinitionshouldbereplacedwiththeappropriateerrorobjectname
from19.5.5.

19.5.6.1 NativeErrorConstructors

WhenaNativeErrorconstructoriscalledasafunctionratherthanasaconstructor,itcreatesandinitializesanew
NativeErrorobject.Acalloftheobjectasafunctionisequivalenttocallingitasaconstructorwiththesamearguments.Thus
thefunctioncallNativeError()isequivalenttotheobjectcreationexpressionnewNativeError()withthesame
arguments.

EachNativeErrorconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedNativeErrorbehaviourmustincludeasupercalltothe
NativeErrorconstructortocreateandinitializesubclassinstanceswitha[[ErrorData]]internalslot.

19.5.6.1.1 NativeError(message)

WhenaNativeErrorfunctioniscalledwithargumentmessage,thefollowingstepsaretaken:

1.IfNewTargetisundeined,letnewTargetbetheactivefunctionobject,elseletnewTargetbeNewTarget.
2.LetObe?OrdinaryCreateFromConstructor(newTarget,"%NativeErrorPrototype%",[[ErrorData]]).
3.Ifmessageisnotundeined,then
a.Letmsgbe?ToString(message).
b.LetmsgDescbethePropertyDescriptor{[[Value]]:msg,[[Writable]]:true,[[Enumerable]]:false,[[Conigurable]]:
true}.
c.Perform!DeinePropertyOrThrow(O,"message",msgDesc).
4.ReturnO.

Theactualvalueofthestringpassedinstep2iseither"%EvalErrorPrototype%","%RangeErrorPrototype%",
"%ReferenceErrorPrototype%","%SyntaxErrorPrototype%","%TypeErrorPrototype%",or
"%URIErrorPrototype%"correspondingtowhichNativeErrorconstructorisbeingdeined.

19.5.6.2 PropertiesoftheNativeErrorConstructors

Thevalueofthe[[Prototype]]internalslotofaNativeErrorconstructoristheintrinsicobject%Error%.
EachNativeErrorconstructorhasanamepropertywhosevalueistheStringvalue`"NativeError"`.

EachNativeErrorconstructorhasthefollowingproperties:

19.5.6.2.1 NativeError.prototype

TheinitialvalueofNativeError.prototypeisaNativeErrorprototypeobject(19.5.6.3).EachNativeErrorconstructorhas
adistinctprototypeobject.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

19.5.6.3 PropertiesoftheNativeErrorPrototypeObjects

EachNativeErrorprototypeobjectisanordinaryobject.ItisnotanErrorinstanceanddoesnothavean[[ErrorData]]
internalslot.

Thevalueofthe[[Prototype]]internalslotofeachNativeErrorprototypeobjectistheintrinsicobject%ErrorPrototype%.

19.5.6.3.1 NativeError.prototype.constructor

TheinitialvalueoftheconstructorpropertyoftheprototypeforagivenNativeErrorconstructoristhecorresponding
intrinsicobject%NativeError%(19.5.6.1).

19.5.6.3.2 NativeError.prototype.message

TheinitialvalueofthemessagepropertyoftheprototypeforagivenNativeErrorconstructoristheemptyString.

19.5.6.3.3 NativeError.prototype.name

TheinitialvalueofthenamepropertyoftheprototypeforagivenNativeErrorconstructorisastringconsistingofthename
oftheconstructor(thenameusedinsteadofNativeError).

19.5.6.4 PropertiesofNativeErrorInstances

NativeErrorinstancesareordinaryobjectsthatinheritpropertiesfromtheirNativeErrorprototypeobjectandhavean
[[ErrorData]]internalslotwhosevalueisundeined.Theonlyspeciieduseof[[ErrorData]]isby
Object.prototype.toString(19.1.3.6)toidentifyErrororNativeErrorinstances.

20 NumbersandDates
20.1 NumberObjects
20.1.1 TheNumberConstructor

TheNumberconstructoristhe%Number%intrinsicobjectandtheinitialvalueoftheNumberpropertyoftheglobalobject.
Whencalledasaconstructor,itcreatesandinitializesanewNumberobject.WhenNumberiscalledasafunctionratherthan
asaconstructor,itperformsatypeconversion.

TheNumberconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedNumberbehaviourmustincludeasupercalltotheNumber
constructortocreateandinitializethesubclassinstancewitha[[NumberData]]internalslot.

20.1.1.1 Number(value)

WhenNumberiscalledwithargumentnumber,thefollowingstepsaretaken:

1.Ifnoargumentswerepassedtothisfunctioninvocation,letnbe+0.
2.Else,letnbe?ToNumber(value).
3.IfNewTargetisundeined,returnn.
4.LetObe?OrdinaryCreateFromConstructor(NewTarget,"%NumberPrototype%",[[NumberData]]).
5.SetthevalueofO's[[NumberData]]internalslotton.
6.ReturnO.

20.1.2 PropertiesoftheNumberConstructor

Thevalueofthe[[Prototype]]internalslotoftheNumberconstructoristheintrinsicobject%FunctionPrototype%.

TheNumberconstructorhasthefollowingproperties:

20.1.2.1 Number.EPSILON

ThevalueofNumber.EPSILONisthedifferencebetween1andthesmallestvaluegreaterthan1thatisrepresentableasa
Numbervalue,whichisapproximately2.2204460492503130808472633361816x1016.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.2.2 Number.isFinite(number)

WhentheNumber.isFiniteiscalledwithoneargumentnumber,thefollowingstepsaretaken:

1.IfType(number)isnotNumber,returnfalse.
2.IfnumberisNaN,+,or,returnfalse.
3.Otherwise,returntrue.

20.1.2.3 Number.isInteger(number)

WhentheNumber.isIntegeriscalledwithoneargumentnumber,thefollowingstepsaretaken:

1.IfType(number)isnotNumber,returnfalse.
2.IfnumberisNaN,+,or,returnfalse.
3.LetintegerbeToInteger(number).
4.Ifintegerisnotequaltonumber,returnfalse.
5.Otherwise,returntrue.

20.1.2.4 Number.isNaN(number)

WhentheNumber.isNaNiscalledwithoneargumentnumber,thefollowingstepsaretaken:

1.IfType(number)isnotNumber,returnfalse.
2.IfnumberisNaN,returntrue.
3.Otherwise,returnfalse.

NOTE ThisfunctiondiffersfromtheglobalisNaNfunction(18.2.3)inthatitdoesnotconvertitsargumenttoa
NumberbeforedeterminingwhetheritisNaN.

20.1.2.5 Number.isSafeInteger(number)

WhentheNumber.isSafeIntegeriscalledwithoneargumentnumber,thefollowingstepsaretaken:

1.IfType(number)isnotNumber,returnfalse.
2.IfnumberisNaN,+,or,returnfalse.
3.LetintegerbeToInteger(number).
4.Ifintegerisnotequaltonumber,returnfalse.
5.Ifabs(integer)2531,returntrue.
6.Otherwise,returnfalse.

20.1.2.6 Number.MAX_SAFE_INTEGER
NOTE ThevalueofNumber.MAX_SAFE_INTEGERisthelargestintegernsuchthatnandn+1arebothexactly
representableasaNumbervalue.

ThevalueofNumber.MAX_SAFE_INTEGERis9007199254740991(2531).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.2.7 Number.MAX_VALUE

ThevalueofNumber.MAX_VALUEisthelargestpositiveinitevalueoftheNumbertype,whichisapproximately
1.797693134862315710308.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.2.8 Number.MIN_SAFE_INTEGER

NOTE ThevalueofNumber.MIN_SAFE_INTEGERisthesmallestintegernsuchthatnandn1arebothexactly
representableasaNumbervalue.

ThevalueofNumber.MIN_SAFE_INTEGERis9007199254740991((2531)).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.2.9 Number.MIN_VALUE

ThevalueofNumber.MIN_VALUEisthesmallestpositivevalueoftheNumbertype,whichisapproximately510324.

IntheIEEE7542008doubleprecisionbinaryrepresentation,thesmallestpossiblevalueisadenormalizednumber.Ifan
implementationdoesnotsupportdenormalizedvalues,thevalueofNumber.MIN_VALUEmustbethesmallestnonzero
positivevaluethatcanactuallyberepresentedbytheimplementation.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.2.10 Number.NaN

ThevalueofNumber.NaNisNaN.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.2.11 Number.NEGATIVE_INFINITY

ThevalueofNumber.NEGATIVE_INFINITYis.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.2.12 Number.parseFloat(string)

ThevalueoftheNumber.parseFloatdatapropertyisthesamebuiltinfunctionobjectthatisthevalueoftheparseFloat
propertyoftheglobalobjectdeinedin18.2.4.

20.1.2.13 Number.parseInt(string,radix)

ThevalueoftheNumber.parseIntdatapropertyisthesamebuiltinfunctionobjectthatisthevalueoftheparseInt
propertyoftheglobalobjectdeinedin18.2.5.

20.1.2.14 Number.POSITIVE_INFINITY

ThevalueofNumber.POSITIVE_INFINITYis+.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.
20.1.2.15 Number.prototype

TheinitialvalueofNumber.prototypeistheintrinsicobject%NumberPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.1.3 PropertiesoftheNumberPrototypeObject

TheNumberprototypeobjectistheintrinsicobject%NumberPrototype%.TheNumberprototypeobjectisanordinary
object.TheNumberprototypeisitselfaNumberobject;ithasa[[NumberData]]internalslotwiththevalue+0.

Thevalueofthe[[Prototype]]internalslotoftheNumberprototypeobjectistheintrinsicobject%ObjectPrototype%.

Unlessexplicitlystatedotherwise,themethodsoftheNumberprototypeobjectdeinedbelowarenotgenericandthethis
valuepassedtothemmustbeeitheraNumbervalueoranobjectthathasa[[NumberData]]internalslotthathasbeen
initializedtoaNumbervalue.

TheabstractoperationthisNumberValue(value)performsthefollowingsteps:

1.IfType(value)isNumber,returnvalue.
2.IfType(value)isObjectandvaluehasa[[NumberData]]internalslot,then
a.Assert:value's[[NumberData]]internalslotisaNumbervalue.
b.Returnthevalueofvalue's[[NumberData]]internalslot.
3.ThrowaTypeErrorexception.

ThephrasethisNumbervaluewithinthespeciicationofamethodreferstotheresultreturnedbycallingtheabstract
operationthisNumberValuewiththethisvalueofthemethodinvocationpassedastheargument.

20.1.3.1 Number.prototype.constructor

TheinitialvalueofNumber.prototype.constructoristheintrinsicobject%Number%.

20.1.3.2 Number.prototype.toExponential(fractionDigits)

ReturnaStringcontainingthisNumbervaluerepresentedindecimalexponentialnotationwithonedigitbeforethe
signiicand'sdecimalpointandfractionDigitsdigitsafterthesigniicand'sdecimalpoint.IffractionDigitsisundeined,
includeasmanysigniicanddigitsasnecessarytouniquelyspecifytheNumber(justlikeinToStringexceptthatinthiscase
theNumberisalwaysoutputinexponentialnotation).Speciically,performthefollowingsteps:

1.Letxbe?thisNumberValue(thisvalue).
2.Letfbe?ToInteger(fractionDigits).
3.Assert:fis0,whenfractionDigitsisundeined.
4.IfxisNaN,returntheString"NaN".
5.LetsbetheemptyString.
6.Ifx<0,then
a.Letsbe"".
b.Letxbex.
7.Ifx=+,then
a.ReturntheconcatenationoftheStringssand"Infinity".
8.Iff<0orf>20,throwaRangeErrorexception.However,animplementationispermittedtoextendthebehaviourof
toExponentialforvaluesofflessthan0orgreaterthan20.InthiscasetoExponentialwouldnotnecessarilythrow
RangeErrorforsuchvalues.
9.Ifx=0,then
a.LetmbetheStringconsistingoff+1occurrencesofthecodeunit0x0030(DIGITZERO).
b.Letebe0.
10.Elsex0,
a.IffractionDigitsisnotundeined,then
i.Leteandnbeintegerssuchthat10fn<10f+1andforwhichtheexactmathematicalvalueofn10efxis
asclosetozeroaspossible.Iftherearetwosuchsetsofeandn,picktheeandnforwhichn10efislarger.
b.ElsefractionDigitsisundeined,
i.Lete,n,andfbeintegerssuchthatf0,10fn<10f+1,theNumbervalueforn10efisx,andfisassmallas
possible.Notethatthedecimalrepresentationofnhasf+1digits,nisnotdivisibleby10,andtheleast
signiicantdigitofnisnotnecessarilyuniquelydeterminedbythesecriteria.
c.LetmbetheStringconsistingofthedigitsofthedecimalrepresentationofn(inorder,withnoleadingzeroes).
11.Iff0,then
a.Letabetheirstelementofm,andletbbetheremainingfelementsofm.
b.LetmbetheconcatenationofthethreeStringsa,".",andb.
12.Ife=0,then
a.Letcbe"+".
b.Letdbe"0".
13.Else,
a.Ife>0,letcbe"+".
b.Elsee0,
i.Letcbe"".
ii.Letebee.
c.LetdbetheStringconsistingofthedigitsofthedecimalrepresentationofe(inorder,withnoleadingzeroes).
14.LetmbetheconcatenationofthefourStringsm,"e",c,andd.
15.ReturntheconcatenationoftheStringssandm.

IfthetoExponentialmethodiscalledwithmorethanoneargument,thenthebehaviourisundeined(seeclause17).

NOTE Forimplementationsthatprovidemoreaccurateconversionsthanrequiredbytherulesabove,itis
recommendedthatthefollowingalternativeversionofstep10.b.ibeusedasaguideline:

1.Lete,n,andfbeintegerssuchthatf0,10fn<10f+1,theNumbervalueforn10efisx,andfisas
smallaspossible.Iftherearemultiplepossibilitiesforn,choosethevalueofnforwhichn10efis
closestinvaluetox.Iftherearetwosuchpossiblevaluesofn,choosetheonethatiseven.

20.1.3.3 Number.prototype.toFixed(fractionDigits)

NOTE1 toFixedreturnsaStringcontainingthisNumbervaluerepresentedindecimalixedpointnotationwith
fractionDigitsdigitsafterthedecimalpoint.IffractionDigitsisundeined,0isassumed.

Thefollowingstepsareperformed:

1.Letxbe?thisNumberValue(thisvalue).
2.Letfbe?ToInteger(fractionDigits).(IffractionDigitsisundeined,thisstepproducesthevalue0.)
3.Iff<0orf>20,throwaRangeErrorexception.However,animplementationispermittedtoextendthebehaviourof
toFixedforvaluesofflessthan0orgreaterthan20.InthiscasetoFixedwouldnotnecessarilythrowRangeError
forsuchvalues.
4.IfxisNaN,returntheString"NaN".
5.LetsbetheemptyString.
6.Ifx<0,then
a.Letsbe"".
b.Letxbex.
7.Ifx1021,then
a.Letmbe!ToString(x).
8.Elsex<1021,
a.Letnbeanintegerforwhichtheexactmathematicalvalueofn10fxisasclosetozeroaspossible.Ifthereare
twosuchn,pickthelargern.
b.Ifn=0,letmbetheString"0".Otherwise,letmbetheStringconsistingofthedigitsofthedecimalrepresentation
ofn(inorder,withnoleadingzeroes).
c.Iff0,then
i.Letkbethenumberofelementsinm.
ii.Ifkf,then
1.LetzbetheStringconsistingoff+1koccurrencesofthecodeunit0x0030(DIGITZERO).
2.LetmbetheconcatenationofStringszandm.
3.Letkbef+1.
iii.Letabetheirstkfelementsofm,andletbbetheremainingfelementsofm.
iv.LetmbetheconcatenationofthethreeStringsa,".",andb.
9.ReturntheconcatenationoftheStringssandm.

IfthetoFixedmethodiscalledwithmorethanoneargument,thenthebehaviourisundeined(seeclause17).

NOTE2 TheoutputoftoFixedmaybemoreprecisethantoStringforsomevaluesbecausetoStringonlyprints
enoughsigniicantdigitstodistinguishthenumberfromadjacentnumbervalues.Forexample,

(1000000000000000128).toString()returns"1000000000000000100",while
(1000000000000000128).toFixed(0)returns"1000000000000000128".

20.1.3.4 Number.prototype.toLocaleString([reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthe
Number.prototype.toLocaleStringmethodasspeciiedintheECMA402speciication.IfanECMAScript
implementationdoesnotincludetheECMA402APIthefollowingspeciicationofthetoLocaleStringmethodisused.

ProducesaStringvaluethatrepresentsthisNumbervalueformattedaccordingtotheconventionsofthehostenvironment's
currentlocale.Thisfunctionisimplementationdependent,anditispermissible,butnotencouraged,forittoreturnthesame
thingastoString.

ThemeaningsoftheoptionalparameterstothismethodaredeinedintheECMA402speciication;implementationsthatdo
notincludeECMA402supportmustnotusethoseparameterpositionsforanythingelse.

20.1.3.5 Number.prototype.toPrecision(precision)

ReturnaStringcontainingthisNumbervaluerepresentedeitherindecimalexponentialnotationwithonedigitbeforethe
signiicand'sdecimalpointandprecision1digitsafterthesigniicand'sdecimalpointorindecimalixednotationwith
precisionsigniicantdigits.Ifprecisionisundeined,callToStringinstead.Speciically,performthefollowingsteps:

1.Letxbe?thisNumberValue(thisvalue).
2.Ifprecisionisundeined,return!ToString(x).
3.Letpbe?ToInteger(precision).
4.IfxisNaN,returntheString"NaN".
5.LetsbetheemptyString.
6.Ifx<0,then
a.Letsbecodeunit0x002D(HYPHENMINUS).
b.Letxbex.
7.Ifx=+,then
a.ReturntheStringthatistheconcatenationofsand"Infinity".
8.Ifp<1orp>21,throwaRangeErrorexception.However,animplementationispermittedtoextendthebehaviourof
toPrecisionforvaluesofplessthan1orgreaterthan21.InthiscasetoPrecisionwouldnotnecessarilythrow
RangeErrorforsuchvalues.
9.Ifx=0,then
a.LetmbetheStringconsistingofpoccurrencesofthecodeunit0x0030(DIGITZERO).
b.Letebe0.
10.Elsex0,
a.Leteandnbeintegerssuchthat10p1n<10pandforwhichtheexactmathematicalvalueofn10ep+1xisas
closetozeroaspossible.Iftherearetwosuchsetsofeandn,picktheeandnforwhichn10ep+1islarger.
b.LetmbetheStringconsistingofthedigitsofthedecimalrepresentationofn(inorder,withnoleadingzeroes).
c.Ife<6orep,then
i.Assert:e0.
ii.Letabetheirstelementofm,andletbbetheremainingp1elementsofm.
iii.Letmbetheconcatenationofa,".",andb.
iv.Ife>0,then
1.Letcbecodeunit0x002B(PLUSSIGN).
v.Elsee<0,
1.Letcbecodeunit0x002D(HYPHENMINUS).
2.Letebee.
vi.LetdbetheStringconsistingofthedigitsofthedecimalrepresentationofe(inorder,withnoleading
zeroes).
vii.Returntheconcatenationofs,m,codeunit0x0065(LATINSMALLLETTERE),c,andd.
11.Ife=p1,returntheconcatenationoftheStringssandm.
12.Ife0,then
a.Letmbetheconcatenationoftheirste+1elementsofm,thecodeunit0x002E(FULLSTOP),andtheremainingp
(e+1)elementsofm.
13.Elsee<0,
a.LetmbetheStringformedbytheconcatenationofcodeunit0x0030(DIGITZERO),codeunit0x002E(FULL
STOP),(e+1)occurrencesofcodeunit0x0030(DIGITZERO),andtheStringm.
14.ReturntheStringthatistheconcatenationofsandm.

IfthetoPrecisionmethodiscalledwithmorethanoneargument,thenthebehaviourisundeined(seeclause17).

20.1.3.6 Number.prototype.toString([radix])

NOTE Theoptionalradixshouldbeanintegervalueintheinclusiverange2to36.Ifradixnotpresentoris
undeinedtheNumber10isusedasthevalueofradix.

Thefollowingstepsareperformed:

1.Letxbe?thisNumberValue(thisvalue).
2.Ifradixisnotpresent,letradixNumberbe10.
3.Elseifradixisundeined,letradixNumberbe10.
4.ElseletradixNumberbe?ToInteger(radix).
5.IfradixNumber<2orradixNumber>36,throwaRangeErrorexception.
6.IfradixNumber=10,return!ToString(x).
7.ReturntheStringrepresentationofthisNumbervalueusingtheradixspeciiedbyradixNumber.Lettersazareused
fordigitswithvalues10through35.Theprecisealgorithmisimplementationdependent,howeverthealgorithm
shouldbeageneralizationofthatspeciiedin7.1.12.1.

ThetoStringfunctionisnotgeneric;itthrowsaTypeErrorexceptionifitsthisvalueisnotaNumberoraNumberobject.
Therefore,itcannotbetransferredtootherkindsofobjectsforuseasamethod.

ThelengthpropertyofthetoStringmethodis1.

20.1.3.7 Number.prototype.valueOf()

1.Return?thisNumberValue(thisvalue).

20.1.4 PropertiesofNumberInstances

NumberinstancesareordinaryobjectsthatinheritpropertiesfromtheNumberprototypeobject.Numberinstancesalso
havea[[NumberData]]internalslot.The[[NumberData]]internalslotistheNumbervaluerepresentedbythisNumber
object.

20.2 TheMathObject
TheMathobjectisthe%Math%intrinsicobjectandtheinitialvalueoftheMathpropertyoftheglobalobject.TheMath
objectisasingleordinaryobject.

Thevalueofthe[[Prototype]]internalslotoftheMathobjectistheintrinsicobject%ObjectPrototype%.

TheMathobjectisnotafunctionobject.Itdoesnothavea[[Construct]]internalmethod;itisnotpossibletousetheMath
objectasaconstructorwiththenewoperator.TheMathobjectalsodoesnothavea[[Call]]internalmethod;itisnotpossible
toinvoketheMathobjectasafunction.

NOTE Inthisspeciication,thephrasetheNumbervalueforxhasatechnicalmeaningdeinedin6.1.6.

20.2.1 ValuePropertiesoftheMathObject

20.2.1.1 Math.E

TheNumbervaluefore,thebaseofthenaturallogarithms,whichisapproximately2.7182818284590452354.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.2.1.2 Math.LN10

TheNumbervalueforthenaturallogarithmof10,whichisapproximately2.302585092994046.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.2.1.3 Math.LN2

TheNumbervalueforthenaturallogarithmof2,whichisapproximately0.6931471805599453.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.2.1.4 Math.LOG10E

TheNumbervalueforthebase10logarithmofe,thebaseofthenaturallogarithms;thisvalueisapproximately
0.4342944819032518.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

NOTE ThevalueofMath.LOG10EisapproximatelythereciprocalofthevalueofMath.LN10.

20.2.1.5 Math.LOG2E

TheNumbervalueforthebase2logarithmofe,thebaseofthenaturallogarithms;thisvalueisapproximately
1.4426950408889634.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

NOTE ThevalueofMath.LOG2EisapproximatelythereciprocalofthevalueofMath.LN2.

20.2.1.6 Math.PI

TheNumbervaluefor,theratioofthecircumferenceofacircletoitsdiameter,whichisapproximately
3.1415926535897932.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.2.1.7 Math.SQRT1_2

TheNumbervalueforthesquarerootof,whichisapproximately0.7071067811865476.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.
NOTE ThevalueofMath.SQRT1_2isapproximatelythereciprocalofthevalueofMath.SQRT2.

20.2.1.8 Math.SQRT2

TheNumbervalueforthesquarerootof2,whichisapproximately1.4142135623730951.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.2.1.9 Math[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"Math".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

20.2.2 FunctionPropertiesoftheMathObject

EachofthefollowingMathobjectfunctionsappliestheToNumberabstractoperationtoeachofitsarguments(inlefttoright
orderifthereismorethanone).IfToNumberreturnsanabruptcompletion,thatCompletionRecordisimmediately
returned.Otherwise,thefunctionperformsacomputationontheresultingNumbervalue(s).Thevaluereturnedbyeach
functionisaNumber.

Inthefunctiondescriptionsbelow,thesymbolsNaN,0,+0,and+refertotheNumbervaluesdescribedin6.1.6.

NOTE Thebehaviourofthefunctionsacos,acosh,asin,asinh,atan,atanh,atan2,cbrt,cos,cosh,exp,expm1,
hypot,log,log1p,log2,log10,pow,random,sin,sinh,sqrt,tan,andtanhisnotpreciselyspeciiedhere
excepttorequirespeciicresultsforcertainargumentvaluesthatrepresentboundarycasesofinterest.For
otherargumentvalues,thesefunctionsareintendedtocomputeapproximationstotheresultsoffamiliar
mathematicalfunctions,butsomelatitudeisallowedinthechoiceofapproximationalgorithms.Thegeneral
intentisthatanimplementershouldbeabletousethesamemathematicallibraryforECMAScriptonagiven
hardwareplatformthatisavailabletoCprogrammersonthatplatform.

Althoughthechoiceofalgorithmsislefttotheimplementation,itisrecommended(butnotspeciiedbythis
standard)thatimplementationsusetheapproximationalgorithmsforIEEE7542008arithmeticcontainedin
fdlibm,thefreelydistributablemathematicallibraryfromSunMicrosystems(http://www.netlib.org/fdlibm).

20.2.2.1 Math.abs(x)

Returnstheabsolutevalueofx;theresulthasthesamemagnitudeasxbuthaspositivesign.

IfxisNaN,theresultisNaN.
Ifxis0,theresultis+0.
Ifxis,theresultis+.

20.2.2.2 Math.acos(x)

Returnsanimplementationdependentapproximationtothearccosineofx.Theresultisexpressedinradiansandranges
from+0to+.

IfxisNaN,theresultisNaN.
Ifxisgreaterthan1,theresultisNaN.
Ifxislessthan1,theresultisNaN.
Ifxisexactly1,theresultis+0.

20.2.2.3 Math.acosh(x)

Returnsanimplementationdependentapproximationtotheinversehyperboliccosineofx.

IfxisNaN,theresultisNaN.
Ifxislessthan1,theresultisNaN.
Ifxis1,theresultis+0.
Ifxis+,theresultis+.

20.2.2.4 Math.asin(x)

Returnsanimplementationdependentapproximationtothearcsineofx.Theresultisexpressedinradiansandrangesfrom
/2to+/2.

IfxisNaN,theresultisNaN.
Ifxisgreaterthan1,theresultisNaN.
Ifxislessthan1,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.

20.2.2.5 Math.asinh(x)

Returnsanimplementationdependentapproximationtotheinversehyperbolicsineofx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.
Ifxis,theresultis.

20.2.2.6 Math.atan(x)

Returnsanimplementationdependentapproximationtothearctangentofx.Theresultisexpressedinradiansandranges
from/2to+/2.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultisanimplementationdependentapproximationto+/2.
Ifxis,theresultisanimplementationdependentapproximationto/2.

20.2.2.7 Math.atanh(x)

Returnsanimplementationdependentapproximationtotheinversehyperbolictangentofx.

IfxisNaN,theresultisNaN.
Ifxislessthan1,theresultisNaN.
Ifxisgreaterthan1,theresultisNaN.
Ifxis1,theresultis.
Ifxis+1,theresultis+.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.

20.2.2.8 Math.atan2(y,x)

Returnsanimplementationdependentapproximationtothearctangentofthequotienty/xoftheargumentsyandx,where
thesignsofyandxareusedtodeterminethequadrantoftheresult.Notethatitisintentionalandtraditionalforthetwo
argumentarctangentfunctionthattheargumentnamedybeirstandtheargumentnamedxbesecond.Theresultis
expressedinradiansandrangesfromto+.

IfeitherxoryisNaN,theresultisNaN.
Ify>0andxis+0,theresultisanimplementationdependentapproximationto+/2.
Ify>0andxis0,theresultisanimplementationdependentapproximationto+/2.
Ifyis+0andx>0,theresultis+0.
Ifyis+0andxis+0,theresultis+0.
Ifyis+0andxis0,theresultisanimplementationdependentapproximationto+.
Ifyis+0andx<0,theresultisanimplementationdependentapproximationto+.
Ifyis0andx>0,theresultis0.
Ifyis0andxis+0,theresultis0.
Ifyis0andxis0,theresultisanimplementationdependentapproximationto.
Ifyis0andx<0,theresultisanimplementationdependentapproximationto.
Ify<0andxis+0,theresultisanimplementationdependentapproximationto/2.
Ify<0andxis0,theresultisanimplementationdependentapproximationto/2.
Ify>0andyisiniteandxis+,theresultis+0.
Ify>0andyisiniteandxis,theresultisanimplementationdependentapproximationto+.
Ify<0andyisiniteandxis+,theresultis0.
Ify<0andyisiniteandxis,theresultisanimplementationdependentapproximationto.
Ifyis+andxisinite,theresultisanimplementationdependentapproximationto+/2.
Ifyisandxisinite,theresultisanimplementationdependentapproximationto/2.
Ifyis+andxis+,theresultisanimplementationdependentapproximationto+/4.
Ifyis+andxis,theresultisanimplementationdependentapproximationto+3/4.
Ifyisandxis+,theresultisanimplementationdependentapproximationto/4.
Ifyisandxis,theresultisanimplementationdependentapproximationto3/4.

20.2.2.9 Math.cbrt(x)

Returnsanimplementationdependentapproximationtothecuberootofx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.
Ifxis,theresultis.

20.2.2.10 Math.ceil(x)

Returnsthesmallest(closestto)Numbervaluethatisnotlessthanxandisequaltoamathematicalinteger.Ifxisalready
aninteger,theresultisx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.
Ifxis,theresultis.
Ifxislessthan0butgreaterthan1,theresultis0.

ThevalueofMath.ceil(x)isthesameasthevalueofMath.floor(x).

20.2.2.11 Math.clz32(x)

WhenMath.clz32iscalledwithoneargumentx,thefollowingstepsaretaken:

1.LetnbeToUint32(x).
2.Letpbethenumberofleadingzerobitsinthe32bitbinaryrepresentationofn.
3.Returnp.

NOTE Ifnis0,pwillbe32.Ifthemostsigniicantbitofthe32bitbinaryencodingofnis1,pwillbe0.

20.2.2.12 Math.cos(x)

Returnsanimplementationdependentapproximationtothecosineofx.Theargumentisexpressedinradians.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis1.
Ifxis0,theresultis1.
Ifxis+,theresultisNaN.
Ifxis,theresultisNaN.

20.2.2.13 Math.cosh(x)

Returnsanimplementationdependentapproximationtothehyperboliccosineofx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis1.
Ifxis0,theresultis1.
Ifxis+,theresultis+.
Ifxis,theresultis+.

NOTE Thevalueofcosh(x)isthesameas(exp(x)+exp(x))/2.

20.2.2.14 Math.exp(x)

Returnsanimplementationdependentapproximationtotheexponentialfunctionofx(eraisedtothepowerofx,whereeis
thebaseofthenaturallogarithms).

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis1.
Ifxis0,theresultis1.
Ifxis+,theresultis+.
Ifxis,theresultis+0.

20.2.2.15 Math.expm1(x)

Returnsanimplementationdependentapproximationtosubtracting1fromtheexponentialfunctionofx(eraisedtothe
powerofx,whereeisthebaseofthenaturallogarithms).Theresultiscomputedinawaythatisaccurateevenwhenthe
valueofxisclose0.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.
Ifxis,theresultis1.

20.2.2.16 Math.loor(x)

Returnsthegreatest(closestto+)Numbervaluethatisnotgreaterthanxandisequaltoamathematicalinteger.Ifxis
alreadyaninteger,theresultisx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.
Ifxis,theresultis.
Ifxisgreaterthan0butlessthan1,theresultis+0.

NOTE ThevalueofMath.floor(x)isthesameasthevalueofMath.ceil(x).

20.2.2.17 Math.fround(x)

WhenMath.froundiscalledwithargumentx,thefollowingstepsaretaken:

1.IfxisNaN,returnNaN.
2.Ifxisoneof+0,0,+,,returnx.
3.Letx32betheresultofconvertingxtoavalueinIEEE7542008binary32formatusingroundTiesToEven.
4.Letx64betheresultofconvertingx32toavalueinIEEE7542008binary64format.
5.ReturntheECMAScriptNumbervaluecorrespondingtox64.

20.2.2.18 Math.hypot(value1,value2,...values)

Math.hypotreturnsanimplementationdependentapproximationofthesquarerootofthesumofsquaresofitsarguments.

Ifnoargumentsarepassed,theresultis+0.
Ifanyargumentis+,theresultis+.
Ifanyargumentis,theresultis+.
Ifnoargumentis+or,andanyargumentisNaN,theresultisNaN.
Ifallargumentsareeither+0or0,theresultis+0.

NOTE Implementationsshouldtakecaretoavoidthelossofprecisionfromoverlowsandunderlowsthatareprone
tooccurinnaiveimplementationswhenthisfunctioniscalledwithtwoormorearguments.

20.2.2.19 Math.imul(x,y)

WhentheMath.imuliscalledwithargumentsxandy,thefollowingstepsaretaken:

1.LetabeToUint32(x).
2.LetbbeToUint32(y).
3.Letproductbe(ab)modulo232.
4.Ifproduct231,returnproduct232;otherwisereturnproduct.

20.2.2.20 Math.log(x)

Returnsanimplementationdependentapproximationtothenaturallogarithmofx.

IfxisNaN,theresultisNaN.
Ifxislessthan0,theresultisNaN.
Ifxis+0or0,theresultis.
Ifxis1,theresultis+0.
Ifxis+,theresultis+.

20.2.2.21 Math.log1p(x)

Returnsanimplementationdependentapproximationtothenaturallogarithmof1+x.Theresultiscomputedinawaythat
isaccurateevenwhenthevalueofxisclosetozero.

IfxisNaN,theresultisNaN.
Ifxislessthan1,theresultisNaN.
Ifxis1,theresultis.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.

20.2.2.22 Math.log10(x)

Returnsanimplementationdependentapproximationtothebase10logarithmofx.

IfxisNaN,theresultisNaN.
Ifxislessthan0,theresultisNaN.
Ifxis+0,theresultis.
Ifxis0,theresultis.
Ifxis1,theresultis+0.
Ifxis+,theresultis+.
20.2.2.23 Math.log2(x)

Returnsanimplementationdependentapproximationtothebase2logarithmofx.

IfxisNaN,theresultisNaN.
Ifxislessthan0,theresultisNaN.
Ifxis+0,theresultis.
Ifxis0,theresultis.
Ifxis1,theresultis+0.
Ifxis+,theresultis+.

20.2.2.24 Math.max(value1,value2,...values)

Givenzeroormorearguments,callsToNumberoneachoftheargumentsandreturnsthelargestoftheresultingvalues.

Ifnoargumentsaregiven,theresultis.
IfanyvalueisNaN,theresultisNaN.
ThecomparisonofvaluestodeterminethelargestvalueisdoneusingtheAbstractRelationalComparisonalgorithm
exceptthat+0isconsideredtobelargerthan0.

20.2.2.25 Math.min(value1,value2,...values)

Givenzeroormorearguments,callsToNumberoneachoftheargumentsandreturnsthesmallestoftheresultingvalues.

Ifnoargumentsaregiven,theresultis+.
IfanyvalueisNaN,theresultisNaN.
ThecomparisonofvaluestodeterminethesmallestvalueisdoneusingtheAbstractRelationalComparisonalgorithm
exceptthat+0isconsideredtobelargerthan0.

20.2.2.26 Math.pow(base,exponent)

1.ReturntheresultofApplyingthe**operatorwithbaseandexponentasspeciiedin12.7.3.4.

20.2.2.27 Math.random()

ReturnsaNumbervaluewithpositivesign,greaterthanorequalto0butlessthan1,chosenrandomlyorpseudorandomly
withapproximatelyuniformdistributionoverthatrange,usinganimplementationdependentalgorithmorstrategy.This
functiontakesnoarguments.

EachMath.randomfunctioncreatedfordistinctrealmsmustproduceadistinctsequenceofvaluesfromsuccessivecalls.

20.2.2.28 Math.round(x)

ReturnstheNumbervaluethatisclosesttoxandisequaltoamathematicalinteger.IftwointegerNumbervaluesareequally
closetox,thentheresultistheNumbervaluethatiscloserto+.Ifxisalreadyaninteger,theresultisx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.
Ifxis,theresultis.
Ifxisgreaterthan0butlessthan0.5,theresultis+0.
Ifxislessthan0butgreaterthanorequalto0.5,theresultis0.

NOTE1 Math.round(3.5)returns4,butMath.round(3.5)returns3.

NOTE2 ThevalueofMath.round(x)isnotalwaysthesameasthevalueofMath.floor(x+0.5).Whenxis0oris
lessthan0butgreaterthanorequalto0.5,Math.round(x)returns0,butMath.floor(x+0.5)returns+0.
Math.round(x)mayalsodifferfromthevalueofMath.floor(x+0.5)becauseofinternalroundingwhen
computingx+0.5.

20.2.2.29 Math.sign(x)

Returnsthesignofthex,indicatingwhetherxispositive,negativeorzero.

IfxisNaN,theresultisNaN.
Ifxis0,theresultis0.
Ifxis+0,theresultis+0.
Ifxisnegativeandnot0,theresultis1.
Ifxispositiveandnot+0,theresultis+1.

20.2.2.30 Math.sin(x)

Returnsanimplementationdependentapproximationtothesineofx.Theargumentisexpressedinradians.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+or,theresultisNaN.

20.2.2.31 Math.sinh(x)

Returnsanimplementationdependentapproximationtothehyperbolicsineofx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.
Ifxis,theresultis.

NOTE Thevalueofsinh(x)isthesameas(exp(x)exp(x))/2.

20.2.2.32 Math.sqrt(x)

Returnsanimplementationdependentapproximationtothesquarerootofx.

IfxisNaN,theresultisNaN.
Ifxislessthan0,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+.

20.2.2.33 Math.tan(x)

Returnsanimplementationdependentapproximationtothetangentofx.Theargumentisexpressedinradians.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+or,theresultisNaN.

20.2.2.34 Math.tanh(x)

Returnsanimplementationdependentapproximationtothehyperbolictangentofx.

IfxisNaN,theresultisNaN.
Ifxis+0,theresultis+0.
Ifxis0,theresultis0.
Ifxis+,theresultis+1.
Ifxis,theresultis1.

NOTE Thevalueoftanh(x)isthesameas(exp(x)exp(x))/(exp(x)+exp(x)).

20.2.2.35 Math.trunc(x)

Returnstheintegralpartofthenumberx,removinganyfractionaldigits.Ifxisalreadyaninteger,theresultisx.

IfxisNaN,theresultisNaN.
Ifxis0,theresultis0.
Ifxis+0,theresultis+0.
Ifxis+,theresultis+.
Ifxis,theresultis.
Ifxisgreaterthan0butlessthan1,theresultis+0.
Ifxislessthan0butgreaterthan1,theresultis0.

20.3 DateObjects
20.3.1 OverviewofDateObjectsandDeinitionsofAbstractOperations

Thefollowingfunctionsareabstractoperationsthatoperateontimevalues(deinedin20.3.1.1).Notethat,ineverycase,if
anyargumenttooneofthesefunctionsisNaN,theresultwillbeNaN.

20.3.1.1 TimeValuesandTimeRange

ADateobjectcontainsaNumberindicatingaparticularinstantintimetowithinamillisecond.SuchaNumberiscalleda
timevalue.AtimevaluemayalsobeNaN,indicatingthattheDateobjectdoesnotrepresentaspeciicinstantoftime.

TimeismeasuredinECMAScriptinmillisecondssince01January,1970UTC.Intimevaluesleapsecondsareignored.Itis
assumedthatthereareexactly86,400,000millisecondsperday.ECMAScriptNumbervaluescanrepresentallintegersfrom
9,007,199,254,740,992to9,007,199,254,740,992;thisrangesuficestomeasuretimestomillisecondprecisionforany
instantthatiswithinapproximately285,616years,eitherforwardorbackward,from01January,1970UTC.

TheactualrangeoftimessupportedbyECMAScriptDateobjectsisslightlysmaller:exactly100,000,000daysto
100,000,000daysmeasuredrelativetomidnightatthebeginningof01January,1970UTC.Thisgivesarangeof
8,640,000,000,000,000millisecondstoeithersideof01January,1970UTC.

Theexactmomentofmidnightatthebeginningof01January,1970UTCisrepresentedbythevalue+0.

20.3.1.2 DayNumberandTimewithinDay

Agiventimevaluetbelongstodaynumber

Day(t)=loor(t/msPerDay)

wherethenumberofmillisecondsperdayis

msPerDay=86400000

Theremainderiscalledthetimewithintheday:

TimeWithinDay(t)=tmodulomsPerDay

20.3.1.3 YearNumber

ECMAScriptusesanextrapolatedGregoriansystemtomapadaynumbertoayearnumberandtodeterminethemonthand
datewithinthatyear.Inthissystem,leapyearsarepreciselythosewhichare(divisibleby4)and((notdivisibleby100)or
(divisibleby400)).Thenumberofdaysinyearnumberyisthereforedeinedby
DaysInYear(y)
=365if(ymodulo4)0
=366if(ymodulo4)=0and(ymodulo100)0
=365if(ymodulo100)=0and(ymodulo400)0
=366if(ymodulo400)=0

Allnonleapyearshave365dayswiththeusualnumberofdayspermonthandleapyearshaveanextradayinFebruary.The
daynumberoftheirstdayofyearyisgivenby:

DayFromYear(y)=365(y1970)+loor((y1969)/4)loor((y1901)/100)+loor((y1601)/400)

Thetimevalueofthestartofayearis:

TimeFromYear(y)=msPerDayDayFromYear(y)

Atimevaluedeterminesayearby:

YearFromTime(t)=thelargestintegery(closesttopositiveininity)suchthatTimeFromYear(y)t

Theleapyearfunctionis1foratimewithinaleapyearandotherwiseiszero:

InLeapYear(t)
=0ifDaysInYear(YearFromTime(t))=365
=1ifDaysInYear(YearFromTime(t))=366

20.3.1.4 MonthNumber

Monthsareidentiiedbyanintegerintherange0to11,inclusive.ThemappingMonthFromTime(t)fromatimevaluettoa
monthnumberisdeinedby:

MonthFromTime(t)
=0if0DayWithinYear(t)<31
=1if31DayWithinYear(t)<59+InLeapYear(t)
=2if59+InLeapYear(t)DayWithinYear(t)<90+InLeapYear(t)
=3if90+InLeapYear(t)DayWithinYear(t)<120+InLeapYear(t)
=4if120+InLeapYear(t)DayWithinYear(t)<151+InLeapYear(t)
=5if151+InLeapYear(t)DayWithinYear(t)<181+InLeapYear(t)
=6if181+InLeapYear(t)DayWithinYear(t)<212+InLeapYear(t)
=7if212+InLeapYear(t)DayWithinYear(t)<243+InLeapYear(t)
=8if243+InLeapYear(t)DayWithinYear(t)<273+InLeapYear(t)
=9if273+InLeapYear(t)DayWithinYear(t)<304+InLeapYear(t)
=10if304+InLeapYear(t)DayWithinYear(t)<334+InLeapYear(t)
=11if334+InLeapYear(t)DayWithinYear(t)<365+InLeapYear(t)

where

DayWithinYear(t)=Day(t)DayFromYear(YearFromTime(t))

Amonthvalueof0speciiesJanuary;1speciiesFebruary;2speciiesMarch;3speciiesApril;4speciiesMay;5speciies
June;6speciiesJuly;7speciiesAugust;8speciiesSeptember;9speciiesOctober;10speciiesNovember;and11speciies
December.NotethatMonthFromTime(0)=0,correspondingtoThursday,01January,1970.

20.3.1.5 DateNumber

Adatenumberisidentiiedbyanintegerintherange1through31,inclusive.ThemappingDateFromTime(t)fromatime
valuettoadatenumberisdeinedby:

DateFromTime(t)
=DayWithinYear(t)+1ifMonthFromTime(t)=0
=DayWithinYear(t)30ifMonthFromTime(t)=1
=DayWithinYear(t)58InLeapYear(t)ifMonthFromTime(t)=2
=DayWithinYear(t)89InLeapYear(t)ifMonthFromTime(t)=3
=DayWithinYear(t)119InLeapYear(t)ifMonthFromTime(t)=4
=DayWithinYear(t)150InLeapYear(t)ifMonthFromTime(t)=5
=DayWithinYear(t)180InLeapYear(t)ifMonthFromTime(t)=6
=DayWithinYear(t)211InLeapYear(t)ifMonthFromTime(t)=7
=DayWithinYear(t)242InLeapYear(t)ifMonthFromTime(t)=8
=DayWithinYear(t)272InLeapYear(t)ifMonthFromTime(t)=9
=DayWithinYear(t)303InLeapYear(t)ifMonthFromTime(t)=10
=DayWithinYear(t)333InLeapYear(t)ifMonthFromTime(t)=11

20.3.1.6 WeekDay

Theweekdayforaparticulartimevaluetisdeinedas

WeekDay(t)=(Day(t)+4)modulo7

Aweekdayvalueof0speciiesSunday;1speciiesMonday;2speciiesTuesday;3speciiesWednesday;4speciiesThursday;
5speciiesFriday;and6speciiesSaturday.NotethatWeekDay(0)=4,correspondingtoThursday,01January,1970.

20.3.1.7 LocalTimeZoneAdjustment

AnimplementationofECMAScriptisexpectedtodeterminethelocaltimezoneadjustment.Thelocaltimezoneadjustment
isavalueLocalTZAmeasuredinmillisecondswhichwhenaddedtoUTCrepresentsthelocalstandardtime.Daylightsaving
timeisnotrelectedbyLocalTZA.

NOTE ItisrecommendedthatimplementationsusethetimezoneinformationoftheIANATimeZoneDatabase
http://www.iana.org/timezones/.

20.3.1.8 DaylightSavingTimeAdjustment

Animplementationdependentalgorithmusingbestavailableinformationontimezonestodeterminethelocaldaylight
savingtimeadjustmentDaylightSavingTA(t),measuredinmilliseconds.AnimplementationofECMAScriptisexpectedto
makeitsbestefforttodeterminethelocaldaylightsavingtimeadjustment.

NOTE ItisrecommendedthatimplementationsusethetimezoneinformationoftheIANATimeZoneDatabase
http://www.iana.org/timezones/.

20.3.1.9 LocalTime(t)

TheabstractoperationLocalTimewithargumenttconvertstfromUTCtolocaltimebyperformingthefollowingsteps:

1.Returnt+LocalTZA+DaylightSavingTA(t).

20.3.1.10 UTC(t)

TheabstractoperationUTCwithargumenttconvertstfromlocaltimetoUTCisdeinedbyperformingthefollowingsteps:

1.ReturntLocalTZADaylightSavingTA(tLocalTZA).

NOTE UTC(LocalTime(t))isnotnecessarilyalwaysequaltot.

20.3.1.11 Hours,Minutes,Second,andMilliseconds

Thefollowingabstractoperationsareusefulindecomposingtimevalues:

HourFromTime(t)=loor(t/msPerHour)moduloHoursPerDay
MinFromTime(t)=loor(t/msPerMinute)moduloMinutesPerHour
SecFromTime(t)=loor(t/msPerSecond)moduloSecondsPerMinute
msFromTime(t)=tmodulomsPerSecond
where

HoursPerDay=24
MinutesPerHour=60
SecondsPerMinute=60
msPerSecond=1000
msPerMinute=60000=msPerSecondSecondsPerMinute
msPerHour=3600000=msPerMinuteMinutesPerHour

20.3.1.12 MakeTime(hour,min,sec,ms)

TheabstractoperationMakeTimecalculatesanumberofmillisecondsfromitsfourarguments,whichmustbeECMAScript
Numbervalues.Thisoperatorfunctionsasfollows:

1.Ifhourisnotiniteorminisnotiniteorsecisnotiniteormsisnotinite,returnNaN.
2.LethbeToInteger(hour).
3.LetmbeToInteger(min).
4.LetsbeToInteger(sec).
5.LetmillibeToInteger(ms).
6.Lettbeh*msPerHour+m*msPerMinute+s*msPerSecond+milli,performingthearithmeticaccordingtoIEEE754
2008rules(thatis,asifusingtheECMAScriptoperators*and+).
7.Returnt.

20.3.1.13 MakeDay(year,month,date)

TheabstractoperationMakeDaycalculatesanumberofdaysfromitsthreearguments,whichmustbeECMAScriptNumber
values.Thisoperatorfunctionsasfollows:

1.Ifyearisnotiniteormonthisnotiniteordateisnotinite,returnNaN.
2.LetybeToInteger(year).
3.LetmbeToInteger(month).
4.LetdtbeToInteger(date).
5.Letymbey+loor(m/12).
6.Letmnbemmodulo12.
7.FindavaluetsuchthatYearFromTime(t)isymandMonthFromTime(t)ismnandDateFromTime(t)is1;butifthisis
notpossible(becausesomeargumentisoutofrange),returnNaN.
8.ReturnDay(t)+dt1.

20.3.1.14 MakeDate(day,time)

TheabstractoperationMakeDatecalculatesanumberofmillisecondsfromitstwoarguments,whichmustbeECMAScript
Numbervalues.Thisoperatorfunctionsasfollows:

1.Ifdayisnotiniteortimeisnotinite,returnNaN.
2.ReturndaymsPerDay+time.

20.3.1.15 TimeClip(time)

TheabstractoperationTimeClipcalculatesanumberofmillisecondsfromitsargument,whichmustbeanECMAScript
Numbervalue.Thisoperatorfunctionsasfollows:

1.Iftimeisnotinite,returnNaN.
2.Ifabs(time)>8.641015,returnNaN.
3.LetclippedTimebeToInteger(time).
4.IfclippedTimeis0,letclippedTimebe+0.
5.ReturnclippedTime.
NOTE Thepointofstep4isthatanimplementationispermittedachoiceofinternalrepresentationsoftimevalues,
forexampleasa64bitsignedintegerorasa64bitloatingpointvalue.Dependingontheimplementation,
thisinternalrepresentationmayormaynotdistinguish0and+0.

20.3.1.16 DateTimeStringFormat

ECMAScriptdeinesastringinterchangeformatfordatetimesbaseduponasimpliicationoftheISO8601ExtendedFormat.
Theformatisasfollows:YYYYMMDDTHH:mm:ss.sssZ

Wheretheieldsareasfollows:

YYYY isthedecimaldigitsoftheyear0000to9999intheGregoriancalendar.
""(hyphen)appearsliterallytwiceinthestring.
MM isthemonthoftheyearfrom01(January)to12(December).
DD isthedayofthemonthfrom01to31.
T "T"appearsliterallyinthestring,toindicatethebeginningofthetimeelement.
HH isthenumberofcompletehoursthathavepassedsincemidnightastwodecimaldigitsfrom00to24.
: ":"(colon)appearsliterallytwiceinthestring.
mm isthenumberofcompleteminutessincethestartofthehourastwodecimaldigitsfrom00to59.
ss isthenumberofcompletesecondssincethestartoftheminuteastwodecimaldigitsfrom00to59.
. "."(dot)appearsliterallyinthestring.
sss isthenumberofcompletemillisecondssincethestartofthesecondasthreedecimaldigits.
Z isthetimezoneoffsetspeciiedas"Z"(forUTC)oreither"+"or""followedbyatimeexpressionHH:mm

Thisformatincludesdateonlyforms:

YYYY
YYYYMM
YYYYMMDD

Italsoincludesdatetimeformsthatconsistofoneoftheabovedateonlyformsimmediatelyfollowedbyoneofthe
followingtimeformswithanoptionaltimezoneoffsetappended:

THH:mm
THH:mm:ss
THH:mm:ss.sss

Allnumbersmustbebase10.IftheMMorDDieldsareabsent"01"isusedasthevalue.IftheHH,mm,orssieldsareabsent
"00"isusedasthevalueandthevalueofanabsentsssieldis"000".Whenthetimezoneoffsetisabsent,dateonlyforms
areinterpretedasaUTCtimeanddatetimeformsareinterpretedasalocaltime.

Illegalvalues(outofboundsaswellassyntaxerrors)inaformatstringmeansthattheformatstringisnotavalidinstance
ofthisformat.

NOTE1 Aseverydaybothstartsandendswithmidnight,thetwonotations00:00and24:00areavailableto
distinguishthetwomidnightsthatcanbeassociatedwithonedate.Thismeansthatthefollowingtwo
notationsrefertoexactlythesamepointintime:19950204T24:00and19950205T00:00

NOTE2 ThereexistsnointernationalstandardthatspeciiesabbreviationsforciviltimezoneslikeCET,EST,etc.and
sometimesthesameabbreviationisevenusedfortwoverydifferenttimezones.Forthisreason,ISO8601and
thisformatspeciiesnumericrepresentationsofdateandtime.

20.3.1.16.1 ExtendedYears
ECMAScriptrequirestheabilitytospecify6digityears(extendedyears);approximately285,426years,eitherforwardor
backward,from01January,1970UTC.Torepresentyearsbefore0orafter9999,ISO8601permitstheexpansionoftheyear
representation,butonlybyprioragreementbetweenthesenderandthereceiver.InthesimpliiedECMAScriptformatsuch
anexpandedyearrepresentationshallhave2extrayeardigitsandisalwayspreixedwitha+orsign.Theyear0is
consideredpositiveandhencepreixedwitha+sign.

NOTE Examplesofextendedyears:

2834570321T15:00:59.008Z 283458B.C.

0000010101T00:00:00Z 2B.C.

+0000000101T00:00:00Z 1B.C.

+0000010101T00:00:00Z 1A.D.

+0019700101T00:00:00Z 1970A.D.

+0020091215T00:00:00Z 2009A.D.

+2873961012T08:59:00.992Z 287396A.D.

20.3.2 TheDateConstructor

TheDateconstructoristhe%Date%intrinsicobjectandtheinitialvalueoftheDatepropertyoftheglobalobject.When
calledasaconstructoritcreatesandinitializesanewDateobject.WhenDateiscalledasafunctionratherthanasa
constructor,itreturnsaStringrepresentingthecurrenttime(UTC).

TheDateconstructorisasinglefunctionwhosebehaviourisoverloadedbaseduponthenumberandtypesofitsarguments.

TheDateconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedDatebehaviourmustincludeasupercalltotheDateconstructor
tocreateandinitializethesubclassinstancewitha[[DateValue]]internalslot.

ThelengthpropertyoftheDateconstructorfunctionis7.

20.3.2.1 Date(year,month[,date[,hours[,minutes[,seconds[,ms]]]]])

ThisdescriptionappliesonlyiftheDateconstructoriscalledwithatleasttwoarguments.

WhentheDatefunctioniscalled,thefollowingstepsaretaken:

1.LetnumberOfArgsbethenumberofargumentspassedtothisfunctioncall.
2.Assert:numberOfArgs2.
3.IfNewTargetisnotundeined,then
a.Letybe?ToNumber(year).
b.Letmbe?ToNumber(month).
c.Ifdateissupplied,letdtbe?ToNumber(date);elseletdtbe1.
d.Ifhoursissupplied,lethbe?ToNumber(hours);elselethbe0.
e.Ifminutesissupplied,letminbe?ToNumber(minutes);elseletminbe0.
f.Ifsecondsissupplied,letsbe?ToNumber(seconds);elseletsbe0.
g.Ifmsissupplied,letmillibe?ToNumber(ms);elseletmillibe0.
h.IfyisnotNaNand0ToInteger(y)99,letyrbe1900+ToInteger(y);otherwise,letyrbey.
i.LetinalDatebeMakeDate(MakeDay(yr,m,dt),MakeTime(h,min,s,milli)).
j.LetObe?OrdinaryCreateFromConstructor(NewTarget,"%DatePrototype%",[[DateValue]]).
k.Setthe[[DateValue]]internalslotofOtoTimeClip(UTC(inalDate)).
l.ReturnO.
4.Else,
a.LetnowbetheNumberthatisthetimevalue(UTC)identifyingthecurrenttime.
b.ReturnToDateString(now).

20.3.2.2 Date(value)

ThisdescriptionappliesonlyiftheDateconstructoriscalledwithexactlyoneargument.

WhentheDatefunctioniscalled,thefollowingstepsaretaken:

1.LetnumberOfArgsbethenumberofargumentspassedtothisfunctioncall.
2.Assert:numberOfArgs=1.
3.IfNewTargetisnotundeined,then
a.IfType(value)isObjectandvaluehasa[[DateValue]]internalslot,then
i.LettvbethisTimeValue(value).
b.Else,
i.Letvbe?ToPrimitive(value).
ii.IfType(v)isString,then
1.Lettvbetheresultofparsingvasadate,inexactlythesamemannerasfortheparsemethod
(20.3.3.2).Iftheparseresultedinanabruptcompletion,tvistheCompletionRecord.
2.ReturnIfAbrupt(tv).
iii.Else,
1.Lettvbe?ToNumber(v).
c.LetObe?OrdinaryCreateFromConstructor(NewTarget,"%DatePrototype%",[[DateValue]]).
d.Setthe[[DateValue]]internalslotofOtoTimeClip(tv).
e.ReturnO.
4.Else,
a.LetnowbetheNumberthatisthetimevalue(UTC)identifyingthecurrenttime.
b.ReturnToDateString(now).

20.3.2.3 Date()

ThisdescriptionappliesonlyiftheDateconstructoriscalledwithnoarguments.

WhentheDatefunctioniscalled,thefollowingstepsaretaken:

1.LetnumberOfArgsbethenumberofargumentspassedtothisfunctioncall.
2.Assert:numberOfArgs=0.
3.IfNewTargetisnotundeined,then
a.LetObe?OrdinaryCreateFromConstructor(NewTarget,"%DatePrototype%",[[DateValue]]).
b.Setthe[[DateValue]]internalslotofOtothetimevalue(UTC)identifyingthecurrenttime.
c.ReturnO.
4.Else,
a.LetnowbetheNumberthatisthetimevalue(UTC)identifyingthecurrenttime.
b.ReturnToDateString(now).

20.3.3 PropertiesoftheDateConstructor

Thevalueofthe[[Prototype]]internalslotoftheDateconstructoristheintrinsicobject%FunctionPrototype%.

TheDateconstructorhasthefollowingproperties:
20.3.3.1 Date.now()

ThenowfunctionreturnsaNumbervaluethatisthetimevaluedesignatingtheUTCdateandtimeoftheoccurrenceofthe
calltonow.

20.3.3.2 Date.parse(string)

TheparsefunctionappliestheToStringoperatortoitsargument.IfToStringresultsinanabruptcompletiontheCompletion
Recordisimmediatelyreturned.Otherwise,parseinterpretstheresultingStringasadateandtime;itreturnsaNumber,the
UTCtimevaluecorrespondingtothedateandtime.TheStringmaybeinterpretedasalocaltime,aUTCtime,oratimein
someothertimezone,dependingonthecontentsoftheString.ThefunctionirstattemptstoparsetheformatoftheString
accordingtotherules(includingextendedyears)calledoutinDateTimeStringFormat(20.3.1.16).IftheStringdoesnot
conformtothatformatthefunctionmayfallbacktoanyimplementationspeciicheuristicsorimplementationspeciicdate
formats.UnrecognizableStringsordatescontainingillegalelementvaluesintheformatStringshallcauseDate.parseto
returnNaN.

IfxisanyDateobjectwhosemillisecondsamountiszerowithinaparticularimplementationofECMAScript,thenallofthe
followingexpressionsshouldproducethesamenumericvalueinthatimplementation,ifallthepropertiesreferencedhave
theirinitialvalues:

x.valueOf()
Date.parse(x.toString())
Date.parse(x.toUTCString())
Date.parse(x.toISOString())

However,theexpression

Date.parse(x.toLocaleString())

isnotrequiredtoproducethesameNumbervalueastheprecedingthreeexpressionsand,ingeneral,thevalueproducedby
Date.parseisimplementationdependentwhengivenanyStringvaluethatdoesnotconformtotheDateTimeString
Format(20.3.1.16)andthatcouldnotbeproducedinthatimplementationbythetoStringortoUTCStringmethod.

20.3.3.3 Date.prototype

TheinitialvalueofDate.prototypeistheintrinsicobject%DatePrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

20.3.3.4 Date.UTC(year,month[,date[,hours[,minutes[,seconds[,ms]]]]])

WhentheUTCfunctioniscalledwithfewerthantwoarguments,thebehaviourisimplementationdependent.WhentheUTC
functioniscalledwithtwotosevenarguments,itcomputesthedatefromyear,monthand(optionally)date,hours,minutes,
secondsandms.Thefollowingstepsaretaken:

1.Letybe?ToNumber(year).
2.Letmbe?ToNumber(month).
3.Ifdateissupplied,letdtbe?ToNumber(date);elseletdtbe1.
4.Ifhoursissupplied,lethbe?ToNumber(hours);elselethbe0.
5.Ifminutesissupplied,letminbe?ToNumber(minutes);elseletminbe0.
6.Ifsecondsissupplied,letsbe?ToNumber(seconds);elseletsbe0.
7.Ifmsissupplied,letmillibe?ToNumber(ms);elseletmillibe0.
8.IfyisnotNaNand0ToInteger(y)99,letyrbe1900+ToInteger(y);otherwise,letyrbey.
9.ReturnTimeClip(MakeDate(MakeDay(yr,m,dt),MakeTime(h,min,s,milli))).

ThelengthpropertyoftheUTCfunctionis7.
NOTE TheUTCfunctiondiffersfromtheDateconstructorintwoways:itreturnsatimevalueasaNumber,rather
thancreatingaDateobject,anditinterpretstheargumentsinUTCratherthanaslocaltime.

20.3.4 PropertiesoftheDatePrototypeObject

TheDateprototypeobjectistheintrinsicobject%DatePrototype%.TheDateprototypeobjectisitselfanordinaryobject.Itis
notaDateinstanceanddoesnothavea[[DateValue]]internalslot.

Thevalueofthe[[Prototype]]internalslotoftheDateprototypeobjectistheintrinsicobject%ObjectPrototype%.

Unlessexplicitlydeinedotherwise,themethodsoftheDateprototypeobjectdeinedbelowarenotgenericandthethis
valuepassedtothemmustbeanobjectthathasa[[DateValue]]internalslotthathasbeeninitializedtoatimevalue.

TheabstractoperationthisTimeValue(value)performsthefollowingsteps:

1.IfType(value)isObjectandvaluehasa[[DateValue]]internalslot,then
a.Returnthevalueofvalue's[[DateValue]]internalslot.
2.ThrowaTypeErrorexception.

InfollowingdescriptionsoffunctionsthatarepropertiesoftheDateprototypeobject,thephrasethisDateobjectrefersto
theobjectthatisthethisvaluefortheinvocationofthefunction.IftheTypeofthethisvalueisnotObject,aTypeError
exceptionisthrown.Thephrasethistimevaluewithinthespeciicationofamethodreferstotheresultreturnedbycalling
theabstractoperationthisTimeValuewiththethisvalueofthemethodinvocationpassedastheargument.

20.3.4.1 Date.prototype.constructor

TheinitialvalueofDate.prototype.constructoristheintrinsicobject%Date%.

20.3.4.2 Date.prototype.getDate()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnDateFromTime(LocalTime(t)).

20.3.4.3 Date.prototype.getDay()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnWeekDay(LocalTime(t)).

20.3.4.4 Date.prototype.getFullYear()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnYearFromTime(LocalTime(t)).

20.3.4.5 Date.prototype.getHours()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnHourFromTime(LocalTime(t)).
20.3.4.6 Date.prototype.getMilliseconds()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnmsFromTime(LocalTime(t)).

20.3.4.7 Date.prototype.getMinutes()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnMinFromTime(LocalTime(t)).

20.3.4.8 Date.prototype.getMonth()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnMonthFromTime(LocalTime(t)).

20.3.4.9 Date.prototype.getSeconds()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnSecFromTime(LocalTime(t)).

20.3.4.10 Date.prototype.getTime()

Thefollowingstepsareperformed:

1.Return?thisTimeValue(thisvalue).

20.3.4.11 Date.prototype.getTimezoneOffset()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.Return(tLocalTime(t))/msPerMinute.

20.3.4.12 Date.prototype.getUTCDate()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnDateFromTime(t).

20.3.4.13 Date.prototype.getUTCDay()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnWeekDay(t).
20.3.4.14 Date.prototype.getUTCFullYear()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnYearFromTime(t).

20.3.4.15 Date.prototype.getUTCHours()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnHourFromTime(t).

20.3.4.16 Date.prototype.getUTCMilliseconds()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnmsFromTime(t).

20.3.4.17 Date.prototype.getUTCMinutes()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnMinFromTime(t).

20.3.4.18 Date.prototype.getUTCMonth()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnMonthFromTime(t).

20.3.4.19 Date.prototype.getUTCSeconds()

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnSecFromTime(t).

20.3.4.20 Date.prototype.setDate(date)

Thefollowingstepsareperformed:

1.LettbeLocalTime(?thisTimeValue(thisvalue)).
2.Letdtbe?ToNumber(date).
3.LetnewDatebeMakeDate(MakeDay(YearFromTime(t),MonthFromTime(t),dt),TimeWithinDay(t)).
4.LetubeTimeClip(UTC(newDate)).
5.Setthe[[DateValue]]internalslotofthisDateobjecttou.
6.Returnu.

20.3.4.21 Date.prototype.setFullYear(year[,month[,date]])
Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,lettbe+0;otherwise,lettbeLocalTime(t).
3.Letybe?ToNumber(year).
4.Ifmonthisnotspeciied,letmbeMonthFromTime(t);otherwise,letmbe?ToNumber(month).
5.Ifdateisnotspeciied,letdtbeDateFromTime(t);otherwise,letdtbe?ToNumber(date).
6.LetnewDatebeMakeDate(MakeDay(y,m,dt),TimeWithinDay(t)).
7.LetubeTimeClip(UTC(newDate)).
8.Setthe[[DateValue]]internalslotofthisDateobjecttou.
9.Returnu.

ThelengthpropertyofthesetFullYearmethodis3.

NOTE Ifmonthisnotspeciied,thismethodbehavesasifmonthwerespeciiedwiththevaluegetMonth().Ifdateis
notspeciied,itbehavesasifdatewerespeciiedwiththevaluegetDate().

20.3.4.22 Date.prototype.setHours(hour[,min[,sec[,ms]]])

Thefollowingstepsareperformed:

1.LettbeLocalTime(?thisTimeValue(thisvalue)).
2.Lethbe?ToNumber(hour).
3.Ifminisnotspeciied,letmbeMinFromTime(t);otherwise,letmbe?ToNumber(min).
4.Ifsecisnotspeciied,letsbeSecFromTime(t);otherwise,letsbe?ToNumber(sec).
5.Ifmsisnotspeciied,letmillibemsFromTime(t);otherwise,letmillibe?ToNumber(ms).
6.LetdatebeMakeDate(Day(t),MakeTime(h,m,s,milli)).
7.LetubeTimeClip(UTC(date)).
8.Setthe[[DateValue]]internalslotofthisDateobjecttou.
9.Returnu.

ThelengthpropertyofthesetHoursmethodis4.

NOTE Ifminisnotspeciied,thismethodbehavesasifminwerespeciiedwiththevaluegetMinutes().Ifsecisnot
speciied,itbehavesasifsecwerespeciiedwiththevaluegetSeconds().Ifmsisnotspeciied,itbehavesasif
mswerespeciiedwiththevaluegetMilliseconds().

20.3.4.23 Date.prototype.setMilliseconds(ms)

Thefollowingstepsareperformed:

1.LettbeLocalTime(?thisTimeValue(thisvalue)).
2.Letmsbe?ToNumber(ms).
3.LettimebeMakeTime(HourFromTime(t),MinFromTime(t),SecFromTime(t),ms).
4.LetubeTimeClip(UTC(MakeDate(Day(t),time))).
5.Setthe[[DateValue]]internalslotofthisDateobjecttou.
6.Returnu.

20.3.4.24 Date.prototype.setMinutes(min[,sec[,ms]])

Thefollowingstepsareperformed:

1.LettbeLocalTime(?thisTimeValue(thisvalue)).
2.Letmbe?ToNumber(min).
3.Ifsecisnotspeciied,letsbeSecFromTime(t);otherwise,letsbe?ToNumber(sec).
4.Ifmsisnotspeciied,letmillibemsFromTime(t);otherwise,letmillibe?ToNumber(ms).
5.LetdatebeMakeDate(Day(t),MakeTime(HourFromTime(t),m,s,milli)).
6.LetubeTimeClip(UTC(date)).
7.Setthe[[DateValue]]internalslotofthisDateobjecttou.
8.Returnu.

ThelengthpropertyofthesetMinutesmethodis3.

NOTE Ifsecisnotspeciied,thismethodbehavesasifsecwerespeciiedwiththevaluegetSeconds().Ifmsisnot
speciied,thisbehavesasifmswerespeciiedwiththevaluegetMilliseconds().

20.3.4.25 Date.prototype.setMonth(month[,date])

Thefollowingstepsareperformed:

1.LettbeLocalTime(?thisTimeValue(thisvalue)).
2.Letmbe?ToNumber(month).
3.Ifdateisnotspeciied,letdtbeDateFromTime(t);otherwise,letdtbe?ToNumber(date).
4.LetnewDatebeMakeDate(MakeDay(YearFromTime(t),m,dt),TimeWithinDay(t)).
5.LetubeTimeClip(UTC(newDate)).
6.Setthe[[DateValue]]internalslotofthisDateobjecttou.
7.Returnu.

ThelengthpropertyofthesetMonthmethodis2.

NOTE Ifdateisnotspeciied,thismethodbehavesasifdatewerespeciiedwiththevaluegetDate().

20.3.4.26 Date.prototype.setSeconds(sec[,ms])

Thefollowingstepsareperformed:

1.LettbeLocalTime(?thisTimeValue(thisvalue)).
2.Letsbe?ToNumber(sec).
3.Ifmsisnotspeciied,letmillibemsFromTime(t);otherwise,letmillibe?ToNumber(ms).
4.LetdatebeMakeDate(Day(t),MakeTime(HourFromTime(t),MinFromTime(t),s,milli)).
5.LetubeTimeClip(UTC(date)).
6.Setthe[[DateValue]]internalslotofthisDateobjecttou.
7.Returnu.

ThelengthpropertyofthesetSecondsmethodis2.

NOTE Ifmsisnotspeciied,thismethodbehavesasifmswerespeciiedwiththevaluegetMilliseconds().

20.3.4.27 Date.prototype.setTime(time)

Thefollowingstepsareperformed:

1.Perform?thisTimeValue(thisvalue).
2.Lettbe?ToNumber(time).
3.LetvbeTimeClip(t).
4.Setthe[[DateValue]]internalslotofthisDateobjecttov.
5.Returnv.

20.3.4.28 Date.prototype.setUTCDate(date)

1.Lettbe?thisTimeValue(thisvalue).
2.Letdtbe?ToNumber(date).
3.LetnewDatebeMakeDate(MakeDay(YearFromTime(t),MonthFromTime(t),dt),TimeWithinDay(t)).
4.LetvbeTimeClip(newDate).
5.Setthe[[DateValue]]internalslotofthisDateobjecttov.
6.Returnv.
20.3.4.29 Date.prototype.setUTCFullYear(year[,month[,date]])

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,lettbe+0.
3.Letybe?ToNumber(year).
4.Ifmonthisnotspeciied,letmbeMonthFromTime(t);otherwise,letmbe?ToNumber(month).
5.Ifdateisnotspeciied,letdtbeDateFromTime(t);otherwise,letdtbe?ToNumber(date).
6.LetnewDatebeMakeDate(MakeDay(y,m,dt),TimeWithinDay(t)).
7.LetvbeTimeClip(newDate).
8.Setthe[[DateValue]]internalslotofthisDateobjecttov.
9.Returnv.

ThelengthpropertyofthesetUTCFullYearmethodis3.

NOTE Ifmonthisnotspeciied,thismethodbehavesasifmonthwerespeciiedwiththevaluegetUTCMonth().If
dateisnotspeciied,itbehavesasifdatewerespeciiedwiththevaluegetUTCDate().

20.3.4.30 Date.prototype.setUTCHours(hour[,min[,sec[,ms]]])

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.Lethbe?ToNumber(hour).
3.Ifminisnotspeciied,letmbeMinFromTime(t);otherwise,letmbe?ToNumber(min).
4.Ifsecisnotspeciied,letsbeSecFromTime(t);otherwise,letsbe?ToNumber(sec).
5.Ifmsisnotspeciied,letmillibemsFromTime(t);otherwise,letmillibe?ToNumber(ms).
6.LetnewDatebeMakeDate(Day(t),MakeTime(h,m,s,milli)).
7.LetvbeTimeClip(newDate).
8.Setthe[[DateValue]]internalslotofthisDateobjecttov.
9.Returnv.

ThelengthpropertyofthesetUTCHoursmethodis4.

NOTE Ifminisnotspeciied,thismethodbehavesasifminwerespeciiedwiththevaluegetUTCMinutes().Ifsecis
notspeciied,itbehavesasifsecwerespeciiedwiththevaluegetUTCSeconds().Ifmsisnotspeciied,it
behavesasifmswerespeciiedwiththevaluegetUTCMilliseconds().

20.3.4.31 Date.prototype.setUTCMilliseconds(ms)

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.Letmillibe?ToNumber(ms).
3.LettimebeMakeTime(HourFromTime(t),MinFromTime(t),SecFromTime(t),milli).
4.LetvbeTimeClip(MakeDate(Day(t),time)).
5.Setthe[[DateValue]]internalslotofthisDateobjecttov.
6.Returnv.

20.3.4.32 Date.prototype.setUTCMinutes(min[,sec[,ms]])

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.Letmbe?ToNumber(min).
3.Ifsecisnotspeciied,letsbeSecFromTime(t).
4.Else,
a.Letsbe?ToNumber(sec).
5.Ifmsisnotspeciied,letmillibemsFromTime(t).
6.Else,
a.Letmillibe?ToNumber(ms).
7.LetdatebeMakeDate(Day(t),MakeTime(HourFromTime(t),m,s,milli)).
8.LetvbeTimeClip(date).
9.Setthe[[DateValue]]internalslotofthisDateobjecttov.
10.Returnv.

ThelengthpropertyofthesetUTCMinutesmethodis3.

NOTE Ifsecisnotspeciied,thismethodbehavesasifsecwerespeciiedwiththevaluegetUTCSeconds().Ifmsis
notspeciied,itfunctionbehavesasifmswerespeciiedwiththevaluereturnbygetUTCMilliseconds().

20.3.4.33 Date.prototype.setUTCMonth(month[,date])

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.Letmbe?ToNumber(month).
3.Ifdateisnotspeciied,letdtbeDateFromTime(t).
4.Else,
a.Letdtbe?ToNumber(date).
5.LetnewDatebeMakeDate(MakeDay(YearFromTime(t),m,dt),TimeWithinDay(t)).
6.LetvbeTimeClip(newDate).
7.Setthe[[DateValue]]internalslotofthisDateobjecttov.
8.Returnv.

ThelengthpropertyofthesetUTCMonthmethodis2.

NOTE Ifdateisnotspeciied,thismethodbehavesasifdatewerespeciiedwiththevaluegetUTCDate().

20.3.4.34 Date.prototype.setUTCSeconds(sec[,ms])

Thefollowingstepsareperformed:

1.Lettbe?thisTimeValue(thisvalue).
2.Letsbe?ToNumber(sec).
3.Ifmsisnotspeciied,letmillibemsFromTime(t).
4.Else,
a.Letmillibe?ToNumber(ms).
5.LetdatebeMakeDate(Day(t),MakeTime(HourFromTime(t),MinFromTime(t),s,milli)).
6.LetvbeTimeClip(date).
7.Setthe[[DateValue]]internalslotofthisDateobjecttov.
8.Returnv.

ThelengthpropertyofthesetUTCSecondsmethodis2.

NOTE Ifmsisnotspeciied,thismethodbehavesasifmswerespeciiedwiththevaluegetUTCMilliseconds().

20.3.4.35 Date.prototype.toDateString()

ThisfunctionreturnsaStringvalue.ThecontentsoftheStringareimplementationdependent,butareintendedtorepresent
thedateportionoftheDateinthecurrenttimezoneinaconvenient,humanreadableform.

20.3.4.36 Date.prototype.toISOString()

ThisfunctionreturnsaStringvaluerepresentingtheinstanceintimecorrespondingtothistimevalue.Theformatofthe
StringistheDateTimestringformatdeinedin20.3.1.16.AllieldsarepresentintheString.ThetimezoneisalwaysUTC,
denotedbythesufixZ.IfthistimevalueisnotainiteNumberoriftheyearisnotavaluethatcanberepresentedinthat
format(ifnecessaryusingextendedyearformat),aRangeErrorexceptionisthrown.

20.3.4.37 Date.prototype.toJSON(key)

ThisfunctionprovidesaStringrepresentationofaDateobjectforusebyJSON.stringify(24.3.2).

WhenthetoJSONmethodiscalledwithargumentkey,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Lettvbe?ToPrimitive(O,hintNumber).
3.IfType(tv)isNumberandtvisnotinite,returnnull.
4.Return?Invoke(O,"toISOString").

NOTE1 Theargumentisignored.

NOTE2 ThetoJSONfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaDateobject.Therefore,
itcanbetransferredtootherkindsofobjectsforuseasamethod.However,itdoesrequirethatanysuchobject
haveatoISOStringmethod.

20.3.4.38 Date.prototype.toLocaleDateString([reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthe
Date.prototype.toLocaleDateStringmethodasspeciiedintheECMA402speciication.IfanECMAScript
implementationdoesnotincludetheECMA402APIthefollowingspeciicationofthetoLocaleDateStringmethodis
used.

ThisfunctionreturnsaStringvalue.ThecontentsoftheStringareimplementationdependent,butareintendedtorepresent
thedateportionoftheDateinthecurrenttimezoneinaconvenient,humanreadableformthatcorrespondstothe
conventionsofthehostenvironment'scurrentlocale.

ThemeaningoftheoptionalparameterstothismethodaredeinedintheECMA402speciication;implementationsthatdo
notincludeECMA402supportmustnotusethoseparameterpositionsforanythingelse.

20.3.4.39 Date.prototype.toLocaleString([reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthe
Date.prototype.toLocaleStringmethodasspeciiedintheECMA402speciication.IfanECMAScriptimplementation
doesnotincludetheECMA402APIthefollowingspeciicationofthetoLocaleStringmethodisused.

ThisfunctionreturnsaStringvalue.ThecontentsoftheStringareimplementationdependent,butareintendedtorepresent
theDateinthecurrenttimezoneinaconvenient,humanreadableformthatcorrespondstotheconventionsofthehost
environment'scurrentlocale.

ThemeaningoftheoptionalparameterstothismethodaredeinedintheECMA402speciication;implementationsthatdo
notincludeECMA402supportmustnotusethoseparameterpositionsforanythingelse.

20.3.4.40 Date.prototype.toLocaleTimeString([reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthe
Date.prototype.toLocaleTimeStringmethodasspeciiedintheECMA402speciication.IfanECMAScript
implementationdoesnotincludetheECMA402APIthefollowingspeciicationofthetoLocaleTimeStringmethodis
used.

ThisfunctionreturnsaStringvalue.ThecontentsoftheStringareimplementationdependent,butareintendedtorepresent
thetimeportionoftheDateinthecurrenttimezoneinaconvenient,humanreadableformthatcorrespondstothe
conventionsofthehostenvironment'scurrentlocale.
ThemeaningoftheoptionalparameterstothismethodaredeinedintheECMA402speciication;implementationsthatdo
notincludeECMA402supportmustnotusethoseparameterpositionsforanythingelse.

20.3.4.41 Date.prototype.toString()

Thefollowingstepsareperformed:

1.LetObethisDateobject.
2.IfOdoesnothavea[[DateValue]]internalslot,then
a.LettvbeNaN.
3.Else,
a.LettvbethisTimeValue(O).
4.ReturnToDateString(tv).

NOTE1 ForanyDateobjectdwhosemillisecondsamountiszero,theresultofDate.parse(d.toString())isequal
tod.valueOf().See20.3.3.2.

NOTE2 ThetoStringfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaDateobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

20.3.4.41.1 RuntimeSemantics:ToDateString(tv)

Thefollowingstepsareperformed:

1.Assert:Type(tv)isNumber.
2.IftvisNaN,return"InvalidDate".
3.ReturnanimplementationdependentStringvaluethatrepresentstvasadateandtimeinthecurrenttimezoneusinga
convenient,humanreadableform.

20.3.4.42 Date.prototype.toTimeString()

ThisfunctionreturnsaStringvalue.ThecontentsoftheStringareimplementationdependent,butareintendedtorepresent
thetimeportionoftheDateinthecurrenttimezoneinaconvenient,humanreadableform.

20.3.4.43 Date.prototype.toUTCString()

ThisfunctionreturnsaStringvalue.ThecontentsoftheStringareimplementationdependent,butareintendedtorepresent
thistimevalueinaconvenient,humanreadableforminUTC.

NOTE TheintentistoproduceaStringrepresentationofadatethatismorereadablethantheformatspeciiedin
20.3.1.16.Itisnotessentialthatthechosenformatbeunambiguousoreasilymachineparsable.Ifan
implementationdoesnothaveapreferredhumanreadableformatitisrecommendedtousetheformat
deinedin20.3.1.16butwithaspaceratherthana"T"usedtoseparatethedateandtimeelements.

20.3.4.44 Date.prototype.valueOf()

Thefollowingstepsareperformed:

1.Return?thisTimeValue(thisvalue).

20.3.4.45 Date.prototype[@@toPrimitive](hint)

ThisfunctioniscalledbyECMAScriptlanguageoperatorstoconvertaDateobjecttoaprimitivevalue.Theallowedvaluesfor
hintare"default","number",and"string".Dateobjects,areuniqueamongbuiltinECMAScriptobjectinthattheytreat
"default"asbeingequivalentto"string",AllotherbuiltinECMAScriptobjectstreat"default"asbeingequivalentto
"number".

Whenthe@@toPrimitivemethodiscalledwithargumenthint,thefollowingstepsaretaken:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfhintistheStringvalue"string"ortheStringvalue"default",then
a.LettryFirstbe"string".
4.ElseifhintistheStringvalue"number",then
a.LettryFirstbe"number".
5.Else,throwaTypeErrorexception.
6.Return?OrdinaryToPrimitive(O,tryFirst).

Thevalueofthenamepropertyofthisfunctionis"[Symbol.toPrimitive]".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

20.3.5 PropertiesofDateInstances

DateinstancesareordinaryobjectsthatinheritpropertiesfromtheDateprototypeobject.Dateinstancesalsohavea
[[DateValue]]internalslot.The[[DateValue]]internalslotisthetimevaluerepresentedbythisDateobject.

21 TextProcessing
21.1 StringObjects
21.1.1 TheStringConstructor

TheStringconstructoristhe%String%intrinsicobjectandtheinitialvalueoftheStringpropertyoftheglobalobject.
WhencalledasaconstructoritcreatesandinitializesanewStringobject.WhenStringiscalledasafunctionratherthanas
aconstructor,itperformsatypeconversion.

TheStringconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedStringbehaviourmustincludeasupercalltotheString
constructortocreateandinitializethesubclassinstancewitha[[StringData]]internalslot.

21.1.1.1 String(value)

WhenStringiscalledwithargumentvalue,thefollowingstepsaretaken:

1.Ifnoargumentswerepassedtothisfunctioninvocation,letsbe"".
2.Else,
a.IfNewTargetisundeinedandType(value)isSymbol,returnSymbolDescriptiveString(value).
b.Letsbe?ToString(value).
3.IfNewTargetisundeined,returns.
4.Return?StringCreate(s,?GetPrototypeFromConstructor(NewTarget,"%StringPrototype%")).

21.1.2 PropertiesoftheStringConstructor

Thevalueofthe[[Prototype]]internalslotoftheStringconstructoristheintrinsicobject%FunctionPrototype%.

TheStringconstructorhasthefollowingproperties:

21.1.2.1 String.fromCharCode(...codeUnits)

TheString.fromCharCodefunctionmaybecalledwithanynumberofargumentswhichformtherestparameter
codeUnits.Thefollowingstepsaretaken:

1.LetcodeUnitsbeaListcontainingtheargumentspassedtothisfunction.
2.LetlengthbethenumberofelementsincodeUnits.
3.LetelementsbeanewemptyList.
4.LetnextIndexbe0.
5.RepeatwhilenextIndex<length
a.LetnextbecodeUnits[nextIndex].
b.LetnextCUbe?ToUint16(next).
c.AppendnextCUtotheendofelements.
d.LetnextIndexbenextIndex+1.
6.ReturntheStringvaluewhoseelementsare,inorder,theelementsintheListelements.Iflengthis0,theemptystringis
returned.

ThelengthpropertyofthefromCharCodefunctionis1.

21.1.2.2 String.fromCodePoint(...codePoints)

TheString.fromCodePointfunctionmaybecalledwithanynumberofargumentswhichformtherestparameter
codePoints.Thefollowingstepsaretaken:

1.LetcodePointsbeaListcontainingtheargumentspassedtothisfunction.
2.LetlengthbethenumberofelementsincodePoints.
3.LetelementsbeanewemptyList.
4.LetnextIndexbe0.
5.RepeatwhilenextIndex<length
a.LetnextbecodePoints[nextIndex].
b.LetnextCPbe?ToNumber(next).
c.IfSameValue(nextCP,ToInteger(nextCP))isfalse,throwaRangeErrorexception.
d.IfnextCP<0ornextCP>0x10FFFF,throwaRangeErrorexception.
e.AppendtheelementsoftheUTF16EncodingofnextCPtotheendofelements.
f.LetnextIndexbenextIndex+1.
6.ReturntheStringvaluewhoseelementsare,inorder,theelementsintheListelements.Iflengthis0,theemptystringis
returned.

ThelengthpropertyofthefromCodePointfunctionis1.

21.1.2.3 String.prototype

TheinitialvalueofString.prototypeistheintrinsicobject%StringPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

21.1.2.4 String.raw(template,...substitutions)

TheString.rawfunctionmaybecalledwithavariablenumberofarguments.Theirstargumentistemplateandthe
remainderoftheargumentsformtheListsubstitutions.Thefollowingstepsaretaken:

1.LetsubstitutionsbeaListconsistingofalloftheargumentspassedtothisfunction,startingwiththesecondargument.
Iffewerthantwoargumentswerepassed,theListisempty.
2.LetnumberOfSubstitutionsbethenumberofelementsinsubstitutions.
3.Letcookedbe?ToObject(template).
4.Letrawbe?ToObject(?Get(cooked,"raw")).
5.LetliteralSegmentsbe?ToLength(?Get(raw,"length")).
6.IfliteralSegments0,returntheemptystring.
7.LetstringElementsbeanewemptyList.
8.LetnextIndexbe0.
9.Repeat
a.LetnextKeybe!ToString(nextIndex).
b.LetnextSegbe?ToString(?Get(raw,nextKey)).
c.AppendinorderthecodeunitelementsofnextSegtotheendofstringElements.
d.IfnextIndex+1=literalSegments,then
i.ReturntheStringvaluewhosecodeunitsare,inorder,theelementsintheListstringElements.If
stringElementshasnoelements,theemptystringisreturned.
e.IfnextIndex<numberOfSubstitutions,letnextbesubstitutions[nextIndex].
f.Else,letnextbetheemptyString.
g.LetnextSubbe?ToString(next).
h.AppendinorderthecodeunitelementsofnextSubtotheendofstringElements.
i.LetnextIndexbenextIndex+1.

NOTE String.rawisintendedforuseasatagfunctionofaTaggedTemplate(12.3.7).Whencalledassuch,theirst
argumentwillbeawellformedtemplateobjectandtherestparameterwillcontainthesubstitutionvalues.

21.1.3 PropertiesoftheStringPrototypeObject

TheStringprototypeobjectistheintrinsicobject%StringPrototype%.TheStringprototypeobjectisanordinaryobject.The
StringprototypeisitselfaStringobject;ithasa[[StringData]]internalslotwiththevalue"".

Thevalueofthe[[Prototype]]internalslotoftheStringprototypeobjectistheintrinsicobject%ObjectPrototype%.

Unlessexplicitlystatedotherwise,themethodsoftheStringprototypeobjectdeinedbelowarenotgenericandthethis
valuepassedtothemmustbeeitheraStringvalueoranobjectthathasa[[StringData]]internalslotthathasbeeninitialized
toaStringvalue.

TheabstractoperationthisStringValue(value)performsthefollowingsteps:

1.IfType(value)isString,returnvalue.
2.IfType(value)isObjectandvaluehasa[[StringData]]internalslot,then
a.Assert:value's[[StringData]]internalslotisaStringvalue.
b.Returnthevalueofvalue's[[StringData]]internalslot.
3.ThrowaTypeErrorexception.

ThephrasethisStringvaluewithinthespeciicationofamethodreferstotheresultreturnedbycallingtheabstract
operationthisStringValuewiththethisvalueofthemethodinvocationpassedastheargument.

21.1.3.1 String.prototype.charAt(pos)

NOTE1 ReturnsasingleelementStringcontainingthecodeunitatindexposintheStringvalueresultingfrom
convertingthisobjecttoaString.Ifthereisnoelementatthatindex,theresultistheemptyString.Theresult
isaStringvalue,notaStringobject.

IfposisavalueofNumbertypethatisaninteger,thentheresultofx.charAt(pos)isequaltotheresultof
x.substring(pos,pos+1).

WhenthecharAtmethodiscalledwithoneargumentpos,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.Letpositionbe?ToInteger(pos).
4.LetsizebethenumberofelementsinS.
5.Ifposition<0orpositionsize,returntheemptyString.
6.ReturnaStringoflength1,containingonecodeunitfromS,namelythecodeunitatindexposition.

NOTE2 ThecharAtfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.2 String.prototype.charCodeAt(pos)

NOTE1 ReturnsaNumber(anonnegativeintegerlessthan216)thatisthecodeunitvalueofthestringelementat
indexposintheStringresultingfromconvertingthisobjecttoaString.Ifthereisnoelementatthatindex,the
resultisNaN.
WhenthecharCodeAtmethodiscalledwithoneargumentpos,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.Letpositionbe?ToInteger(pos).
4.LetsizebethenumberofelementsinS.
5.Ifposition<0orpositionsize,returnNaN.
6.ReturnavalueofNumbertype,whosevalueisthecodeunitvalueoftheelementatindexpositionintheStringS.

NOTE2 ThecharCodeAtfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.3 String.prototype.codePointAt(pos)

NOTE1 ReturnsanonnegativeintegerNumberlessthan1114112(0x110000)thatisthecodepointvalueoftheUTF
16encodedcodepoint(6.1.4)startingatthestringelementatindexposintheStringresultingfromconverting
thisobjecttoaString.Ifthereisnoelementatthatindex,theresultisundeined.IfavalidUTF16surrogate
pairdoesnotbeginatpos,theresultisthecodeunitatpos.

WhenthecodePointAtmethodiscalledwithoneargumentpos,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.Letpositionbe?ToInteger(pos).
4.LetsizebethenumberofelementsinS.
5.Ifposition<0orpositionsize,returnundeined.
6.LetirstbethecodeunitvalueoftheelementatindexpositionintheStringS.
7.Ifirst<0xD800orirst>0xDBFForposition+1=size,returnirst.
8.Letsecondbethecodeunitvalueoftheelementatindexposition+1intheStringS.
9.Ifsecond<0xDC00orsecond>0xDFFF,returnirst.
10.ReturnUTF16Decode(irst,second).

NOTE2 ThecodePointAtfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.4 String.prototype.concat(...args)

NOTE1 WhentheconcatmethodiscalleditreturnsaStringconsistingofthecodeunitsofthethisobject(converted
toaString)followedbythecodeunitsofeachoftheargumentsconvertedtoaString.TheresultisaString
value,notaStringobject.

Whentheconcatmethodiscalledwithzeroormorearguments,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetargsbeaListwhoseelementsaretheargumentspassedtothisfunction.
4.LetRbeS.
5.Repeat,whileargsisnotempty
a.Removetheirstelementfromargsandletnextbethevalueofthatelement.
b.LetnextStringbe?ToString(next).
c.LetRbetheStringvalueconsistingofthecodeunitsofthepreviousvalueofRfollowedbythecodeunitsof
nextString.
6.ReturnR.

Thelengthpropertyoftheconcatmethodis1.

NOTE2 Theconcatfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.
21.1.3.5 String.prototype.constructor

TheinitialvalueofString.prototype.constructoristheintrinsicobject%String%.

21.1.3.6 String.prototype.endsWith(searchString[,endPosition])

Thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetisRegExpbe?IsRegExp(searchString).
4.IfisRegExpistrue,throwaTypeErrorexception.
5.LetsearchStrbe?ToString(searchString).
6.LetlenbethenumberofelementsinS.
7.IfendPositionisundeined,letposbelen,elseletposbe?ToInteger(endPosition).
8.Letendbemin(max(pos,0),len).
9.LetsearchLengthbethenumberofelementsinsearchStr.
10.LetstartbeendsearchLength.
11.Ifstartislessthan0,returnfalse.
12.IfthesequenceofelementsofSstartingatstartoflengthsearchLengthisthesameasthefullelementsequenceof
searchStr,returntrue.
13.Otherwise,returnfalse.

NOTE1 ReturnstrueifthesequenceofelementsofsearchStringconvertedtoaStringisthesameasthecorresponding
elementsofthisobject(convertedtoaString)startingatendPositionlength(this).Otherwisereturnsfalse.

NOTE2 ThrowinganexceptioniftheirstargumentisaRegExpisspeciiedinordertoallowfutureeditionstodeine
extensionsthatallowsuchargumentvalues.

NOTE3 TheendsWithfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.7 String.prototype.includes(searchString[,position])

Theincludesmethodtakestwoarguments,searchStringandposition,andperformsthefollowingsteps:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetisRegExpbe?IsRegExp(searchString).
4.IfisRegExpistrue,throwaTypeErrorexception.
5.LetsearchStrbe?ToString(searchString).
6.Letposbe?ToInteger(position).(Ifpositionisundeined,thisstepproducesthevalue0.)
7.LetlenbethenumberofelementsinS.
8.Letstartbemin(max(pos,0),len).
9.LetsearchLenbethenumberofelementsinsearchStr.
10.Ifthereexistsanyintegerknotsmallerthanstartsuchthatk+searchLenisnotgreaterthanlen,andforallnonnegative
integersjlessthansearchLen,thecodeunitatindexk+jofSisthesameasthecodeunitatindexjofsearchStr,return
true;butifthereisnosuchintegerk,returnfalse.

NOTE1 IfsearchStringappearsasasubstringoftheresultofconvertingthisobjecttoaString,atoneormoreindices
thataregreaterthanorequaltoposition,returntrue;otherwise,returnsfalse.Ifpositionisundeined,0is
assumed,soastosearchalloftheString.

NOTE2 ThrowinganexceptioniftheirstargumentisaRegExpisspeciiedinordertoallowfutureeditionstodeine
extensionsthatallowsuchargumentvalues.

NOTE3 Theincludesfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.
21.1.3.8 String.prototype.indexOf(searchString[,position])

NOTE1 IfsearchStringappearsasasubstringoftheresultofconvertingthisobjecttoaString,atoneormoreindices
thataregreaterthanorequaltoposition,thenthesmallestsuchindexisreturned;otherwise,1isreturned.If
positionisundeined,0isassumed,soastosearchalloftheString.

TheindexOfmethodtakestwoarguments,searchStringandposition,andperformsthefollowingsteps:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetsearchStrbe?ToString(searchString).
4.Letposbe?ToInteger(position).(Ifpositionisundeined,thisstepproducesthevalue0.)
5.LetlenbethenumberofelementsinS.
6.Letstartbemin(max(pos,0),len).
7.LetsearchLenbethenumberofelementsinsearchStr.
8.Returnthesmallestpossibleintegerknotsmallerthanstartsuchthatk+searchLenisnotgreaterthanlen,andforall
nonnegativeintegersjlessthansearchLen,thecodeunitatindexk+jofSisthesameasthecodeunitatindexjof
searchStr;butifthereisnosuchintegerk,returnthevalue1.

NOTE2 TheindexOffunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.9 String.prototype.lastIndexOf(searchString[,position])

NOTE1 IfsearchStringappearsasasubstringoftheresultofconvertingthisobjecttoaStringatoneormoreindices
thataresmallerthanorequaltoposition,thenthegreatestsuchindexisreturned;otherwise,1isreturned.If
positionisundeined,thelengthoftheStringvalueisassumed,soastosearchalloftheString.

ThelastIndexOfmethodtakestwoarguments,searchStringandposition,andperformsthefollowingsteps:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetsearchStrbe?ToString(searchString).
4.LetnumPosbe?ToNumber(position).(Ifpositionisundeined,thisstepproducesthevalueNaN.)
5.IfnumPosisNaN,letposbe+;otherwise,letposbeToInteger(numPos).
6.LetlenbethenumberofelementsinS.
7.Letstartbemin(max(pos,0),len).
8.LetsearchLenbethenumberofelementsinsearchStr.
9.Returnthelargestpossiblenonnegativeintegerknotlargerthanstartsuchthatk+searchLenisnotgreaterthanlen,and
forallnonnegativeintegersjlessthansearchLen,thecodeunitatindexk+jofSisthesameasthecodeunitatindexjof
searchStr;butifthereisnosuchintegerk,returnthevalue1.

NOTE2 ThelastIndexOffunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.10 String.prototype.localeCompare(that[,reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthelocaleCompare
methodasspeciiedintheECMA402speciication.IfanECMAScriptimplementationdoesnotincludetheECMA402APIthe
followingspeciicationofthelocaleComparemethodisused.

WhenthelocaleComparemethodiscalledwithargumentthat,itreturnsaNumberotherthanNaNthatrepresentsthe
resultofalocalesensitiveStringcomparisonofthethisvalue(convertedtoaString)withthat(convertedtoaString).The
twoStringsareSandThat.ThetwoStringsarecomparedinanimplementationdeinedfashion.Theresultisintendedto
orderStringvaluesinthesortorderspeciiedbyahostdefaultlocale,andwillbenegative,zero,orpositive,dependingon
whetherScomesbeforeThatinthesortorder,theStringsareequal,orScomesafterThatinthesortorder,respectively.

Beforeperformingthecomparisons,thefollowingstepsareperformedtopreparetheStrings:
1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetThatbe?ToString(that).

ThemeaningoftheoptionalsecondandthirdparameterstothismethodaredeinedintheECMA402speciication;
implementationsthatdonotincludeECMA402supportmustnotassignanyotherinterpretationtothoseparameter
positions.

ThelocaleComparemethod,ifconsideredasafunctionoftwoargumentsthisandthat,isaconsistentcomparisonfunction
(asdeinedin22.1.3.25)onthesetofallStrings.

Theactualreturnvaluesareimplementationdeinedtopermitimplementerstoencodeadditionalinformationinthevalue,
butthefunctionisrequiredtodeineatotalorderingonallStrings.ThisfunctionmusttreatStringsthatarecanonically
equivalentaccordingtotheUnicodestandardasidenticalandmustreturn0whencomparingStringsthatareconsidered
canonicallyequivalent.

NOTE1 ThelocaleComparemethoditselfisnotdirectlysuitableasanargumenttoArray.prototype.sort
becausethelatterrequiresafunctionoftwoarguments.

NOTE2 Thisfunctionisintendedtorelyonwhateverlanguagesensitivecomparisonfunctionalityisavailabletothe
ECMAScriptenvironmentfromthehostenvironment,andtocompareaccordingtotherulesofthehost
environment'scurrentlocale.However,regardlessofthehostprovidedcomparisoncapabilities,thisfunction
musttreatStringsthatarecanonicallyequivalentaccordingtotheUnicodestandardasidentical.Itis
recommendedthatthisfunctionshouldnothonourUnicodecompatibilityequivalencesordecompositions.For
adeinitionanddiscussionofcanonicalequivalenceseetheUnicodeStandard,chapters2and3,aswellas
UnicodeStandardAnnex#15,UnicodeNormalizationForms(http://www.unicode.org/reports/tr15/)and
UnicodeTechnicalNote#5,CanonicalEquivalenceinApplications(http://www.unicode.org/notes/tn5/).Also
seeUnicodeTechnicalStandard#10,UnicodeCollationAlgorithm(http://www.unicode.org/reports/tr10/).

NOTE3 ThelocaleComparefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.11 String.prototype.match(regexp)

Whenthematchmethodiscalledwithargumentregexp,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.Ifregexpisneitherundeinednornull,then
a.Letmatcherbe?GetMethod(regexp,@@match).
b.Ifmatcherisnotundeined,then
i.Return?Call(matcher,regexp,O).
3.LetSbe?ToString(O).
4.Letrxbe?RegExpCreate(regexp,undeined).
5.Return?Invoke(rx,@@match,S).

NOTE Thematchfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.Therefore,
itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.12 String.prototype.normalize([form])

Whenthenormalizemethodiscalledwithoneargumentform,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.Ifformisnotprovidedorformisundeined,letformbe"NFC".
4.Letfbe?ToString(form).
5.Iffisnotoneof"NFC","NFD","NFKC",or"NFKD",throwaRangeErrorexception.
6.LetnsbetheStringvaluethatistheresultofnormalizingSintothenormalizationformnamedbyfasspeciiedin
http://www.unicode.org/reports/tr15/tr1529.html.
7.Returnns.

NOTE Thenormalizefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.13 String.prototype.repeat(count)

Thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.Letnbe?ToInteger(count).
4.Ifn<0,throwaRangeErrorexception.
5.Ifnis+,throwaRangeErrorexception.
6.LetTbeaStringvaluethatismadefromncopiesofSappendedtogether.Ifnis0,TistheemptyString.
7.ReturnT.

NOTE1 ThismethodcreatesaStringconsistingofthecodeunitsofthethisobject(convertedtoString)repeated
counttimes.

NOTE2 Therepeatfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.14 String.prototype.replace(searchValue,replaceValue)

WhenthereplacemethodiscalledwithargumentssearchValueandreplaceValue,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.IfsearchValueisneitherundeinednornull,then
a.Letreplacerbe?GetMethod(searchValue,@@replace).
b.Ifreplacerisnotundeined,then
i.Return?Call(replacer,searchValue,O,replaceValue).
3.Letstringbe?ToString(O).
4.LetsearchStringbe?ToString(searchValue).
5.LetfunctionalReplacebeIsCallable(replaceValue).
6.IffunctionalReplaceisfalse,then
a.LetreplaceValuebe?ToString(replaceValue).
7.SearchstringfortheirstoccurrenceofsearchStringandletposbetheindexwithinstringoftheirstcodeunitofthe
matchedsubstringandletmatchedbesearchString.IfnooccurrencesofsearchStringwerefound,returnstring.
8.IffunctionalReplaceistrue,then
a.LetreplValuebe?Call(replaceValue,undeined,matched,pos,string).
b.LetreplStrbe?ToString(replValue).
9.Else,
a.LetcapturesbeanewemptyList.
b.LetreplStrbeGetSubstitution(matched,string,pos,captures,replaceValue).
10.LettailPosbepos+thenumberofcodeunitsinmatched.
11.LetnewStringbetheStringformedbyconcatenatingtheirstposcodeunitsofstring,replStr,andthetrailingsubstring
ofstringstartingatindextailPos.Ifposis0,theirstelementoftheconcatenationwillbetheemptyString.
12.ReturnnewString.

NOTE Thereplacefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.14.1 RuntimeSemantics:GetSubstitution(matched,str,position,captures,replacement)

TheabstractoperationGetSubstitutionperformsthefollowingsteps:
1.Assert:Type(matched)isString.
2.LetmatchLengthbethenumberofcodeunitsinmatched.
3.Assert:Type(str)isString.
4.LetstringLengthbethenumberofcodeunitsinstr.
5.Assert:positionisanonnegativeinteger.
6.Assert:positionstringLength.
7.Assert:capturesisapossiblyemptyListofStrings.
8.Assert:Type(replacement)isString.
9.LettailPosbeposition+matchLength.
10.Letmbethenumberofelementsincaptures.
11.LetresultbeaStringvaluederivedfromreplacementbycopyingcodeunitelementsfromreplacementtoresultwhile
performingreplacementsasspeciiedinTable46.These$replacementsaredonelefttoright,and,oncesucha
replacementisperformed,thenewreplacementtextisnotsubjecttofurtherreplacements.
12.Returnresult.

Table46:ReplacementTextSymbolSubstitutions
Code UnicodeCharacters Replacementtext
units

0x0024, $$ $
0x0024

0x0024, $& matched


0x0026

0x0024, $` Ifpositionis0,thereplacementistheemptyString.Otherwisethereplacementisthe
0x0060 substringofstrthatstartsatindex0andwhoselastcodeunitisatindexposition1.

0x0024, $' IftailPosstringLength,thereplacementistheemptyString.Otherwisethe


0x0027 replacementisthesubstringofstrthatstartsatindextailPosandcontinuestothe
endofstr.

0x0024, $nwhere Thenthelementofcaptures,wherenisasingledigitintherange1to9.Ifnmand


N nisoneof thenthelementofcapturesisundeined,usetheemptyStringinstead.Ifn>m,the
Where 123456789 resultisimplementationdeined.
0x0031 and$nisnotfollowedby
N adecimaldigit
0x0039

0x0024, $nnwhere Thennthelementofcaptures,wherennisatwodigitdecimalnumberintherange


N,N nisoneof 01to99.Ifnnmandthennthelementofcapturesisundeined,usetheempty
Where 0123456789 Stringinstead.Ifnnis00ornn>m,theresultisimplementationdeined.
0x0030
N
0x0039

0x0024 $inanycontextthatdoes $
notmatchanyofthe
above.

21.1.3.15 String.prototype.search(regexp)

Whenthesearchmethodiscalledwithargumentregexp,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.Ifregexpisneitherundeinednornull,then
a.Letsearcherbe?GetMethod(regexp,@@search).
b.Ifsearcherisnotundeined,then
i.Return?Call(searcher,regexp,O).
3.Letstringbe?ToString(O).
4.Letrxbe?RegExpCreate(regexp,undeined).
5.Return?Invoke(rx,@@search,string).

NOTE Thesearchfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.16 String.prototype.slice(start,end)

Theslicemethodtakestwoarguments,startandend,andreturnsasubstringoftheresultofconvertingthisobjecttoa
String,startingfromindexstartandrunningto,butnotincluding,indexend(orthroughtheendoftheStringifendis
undeined).Ifstartisnegative,itistreatedassourceLength+startwheresourceLengthisthelengthoftheString.Ifendis
negative,itistreatedassourceLength+endwheresourceLengthisthelengthoftheString.TheresultisaStringvalue,nota
Stringobject.Thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetlenbethenumberofelementsinS.
4.LetintStartbe?ToInteger(start).
5.Ifendisundeined,letintEndbelen;elseletintEndbe?ToInteger(end).
6.IfintStart<0,letfrombemax(len+intStart,0);otherwiseletfrombemin(intStart,len).
7.IfintEnd<0,lettobemax(len+intEnd,0);otherwiselettobemin(intEnd,len).
8.Letspanbemax(tofrom,0).
9.ReturnaStringvaluecontainingspanconsecutiveelementsfromSbeginningwiththeelementatindexfrom.

NOTE Theslicefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.17 String.prototype.split(separator,limit)

ReturnsanArrayobjectintowhichsubstringsoftheresultofconvertingthisobjecttoaStringhavebeenstored.The
substringsaredeterminedbysearchingfromlefttorightforoccurrencesofseparator;theseoccurrencesarenotpartofany
substringinthereturnedarray,butservetodivideuptheStringvalue.ThevalueofseparatormaybeaStringofanylength
oritmaybeanobject,suchasanRegExp,thathasa@@splitmethod.

Whenthesplitmethodiscalled,thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.Ifseparatorisneitherundeinednornull,then
a.Letsplitterbe?GetMethod(separator,@@split).
b.Ifsplitterisnotundeined,then
i.Return?Call(splitter,separator,O,limit).
3.LetSbe?ToString(O).
4.LetAbeArrayCreate(0).
5.LetlengthAbe0.
6.Iflimitisundeined,letlimbe2321;elseletlimbe?ToUint32(limit).
7.LetsbethenumberofelementsinS.
8.Letpbe0.
9.LetRbe?ToString(separator).
10.Iflim=0,returnA.
11.Ifseparatorisundeined,then
a.Perform!CreateDataProperty(A,"0",S).
b.ReturnA.
12.Ifs=0,then
a.LetzbeSplitMatch(S,0,R).
b.Ifzisnotfalse,returnA.
c.Perform!CreateDataProperty(A,"0",S).
d.ReturnA.
13.Letqbep.
14.Repeat,whileqs
a.LetebeSplitMatch(S,q,R).
b.Ifeisfalse,letqbeq+1.
c.Elseeisanintegerindexs,
i.Ife=p,letqbeq+1.
ii.Elseep,
1.LetTbeaStringvalueequaltothesubstringofSconsistingofthecodeunitsatindicesp(inclusive)
throughq(exclusive).
2.Perform!CreateDataProperty(A,!ToString(lengthA),T).
3.IncrementlengthAby1.
4.IflengthA=lim,returnA.
5.Letpbee.
6.Letqbep.
15.LetTbeaStringvalueequaltothesubstringofSconsistingofthecodeunitsatindicesp(inclusive)throughs
(exclusive).
16.Perform!CreateDataProperty(A,!ToString(lengthA),T).
17.ReturnA.

NOTE1 ThevalueofseparatormaybeanemptyString.Inthiscase,separatordoesnotmatchtheemptysubstringat
thebeginningorendoftheinputString,nordoesitmatchtheemptysubstringattheendoftheprevious
separatormatch.IfseparatoristheemptyString,theStringissplitupintoindividualcodeunitelements;the
lengthoftheresultarrayequalsthelengthoftheString,andeachsubstringcontainsonecodeunit.

Ifthethisobjectis(orconvertsto)theemptyString,theresultdependsonwhetherseparatorcanmatchthe
emptyString.Ifitcan,theresultarraycontainsnoelements.Otherwise,theresultarraycontainsoneelement,
whichistheemptyString.

Ifseparatorisundeined,thentheresultarraycontainsjustoneString,whichisthethisvalue(convertedtoa
String).Iflimitisnotundeined,thentheoutputarrayistruncatedsothatitcontainsnomorethanlimit
elements.

NOTE2 Thesplitfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.Therefore,
itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.17.1 RuntimeSemantics:SplitMatch(S,q,R)

TheabstractoperationSplitMatchtakesthreeparameters,aStringS,anintegerq,andaStringR,andperformsthefollowing
stepsinordertoreturneitherfalseortheendindexofamatch:

1.Assert:Type(R)isString.
2.LetrbethenumberofcodeunitsinR.
3.LetsbethenumberofcodeunitsinS.
4.Ifq+r>s,returnfalse.
5.Ifthereexistsanintegeribetween0(inclusive)andr(exclusive)suchthatthecodeunitatindexq+iofSisdifferent
fromthecodeunitatindexiofR,returnfalse.
6.Returnq+r.

21.1.3.18 String.prototype.startsWith(searchString[,position])

Thefollowingstepsaretaken:
1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetisRegExpbe?IsRegExp(searchString).
4.IfisRegExpistrue,throwaTypeErrorexception.
5.LetsearchStrbe?ToString(searchString).
6.Letposbe?ToInteger(position).(Ifpositionisundeined,thisstepproducesthevalue0.)
7.LetlenbethenumberofelementsinS.
8.Letstartbemin(max(pos,0),len).
9.LetsearchLengthbethenumberofelementsinsearchStr.
10.IfsearchLength+startisgreaterthanlen,returnfalse.
11.IfthesequenceofelementsofSstartingatstartoflengthsearchLengthisthesameasthefullelementsequenceof
searchStr,returntrue.
12.Otherwise,returnfalse.

NOTE1 ThismethodreturnstrueifthesequenceofelementsofsearchStringconvertedtoaStringisthesameasthe
correspondingelementsofthisobject(convertedtoaString)startingatindexposition.Otherwisereturns
false.

NOTE2 ThrowinganexceptioniftheirstargumentisaRegExpisspeciiedinordertoallowfutureeditionstodeine
extensionsthatallowsuchargumentvalues.

NOTE3 ThestartsWithfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.19 String.prototype.substring(start,end)

Thesubstringmethodtakestwoarguments,startandend,andreturnsasubstringoftheresultofconvertingthisobjectto
aString,startingfromindexstartandrunningto,butnotincluding,indexendoftheString(orthroughtheendoftheStringif
endisundeined).TheresultisaStringvalue,notaStringobject.

IfeitherargumentisNaNornegative,itisreplacedwithzero;ifeitherargumentislargerthanthelengthoftheString,itis
replacedwiththelengthoftheString.

Ifstartislargerthanend,theyareswapped.

Thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetlenbethenumberofelementsinS.
4.LetintStartbe?ToInteger(start).
5.Ifendisundeined,letintEndbelen;elseletintEndbe?ToInteger(end).
6.LetinalStartbemin(max(intStart,0),len).
7.LetinalEndbemin(max(intEnd,0),len).
8.Letfrombemin(inalStart,inalEnd).
9.Lettobemax(inalStart,inalEnd).
10.ReturnaStringwhoselengthistofrom,containingcodeunitsfromS,namelythecodeunitswithindicesfromthrough
to1,inascendingorder.

NOTE Thesubstringfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.20 String.prototype.toLocaleLowerCase([reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthe
toLocaleLowerCasemethodasspeciiedintheECMA402speciication.IfanECMAScriptimplementationdoesnotinclude
theECMA402APIthefollowingspeciicationofthetoLocaleLowerCasemethodisused.
ThisfunctioninterpretsaStringvalueasasequenceofUTF16encodedcodepoints,asdescribedin6.1.4.

ThisfunctionworksexactlythesameastoLowerCaseexceptthatitsresultisintendedtoyieldthecorrectresultforthehost
environment'scurrentlocale,ratherthanalocaleindependentresult.Therewillonlybeadifferenceinthefewcases(such
asTurkish)wheretherulesforthatlanguageconlictwiththeregularUnicodecasemappings.

ThemeaningoftheoptionalparameterstothismethodaredeinedintheECMA402speciication;implementationsthatdo
notincludeECMA402supportmustnotusethoseparameterpositionsforanythingelse.

NOTE ThetoLocaleLowerCasefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaString
object.Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.21 String.prototype.toLocaleUpperCase([reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthe
toLocaleUpperCasemethodasspeciiedintheECMA402speciication.IfanECMAScriptimplementationdoesnotinclude
theECMA402APIthefollowingspeciicationofthetoLocaleUpperCasemethodisused.

ThisfunctioninterpretsaStringvalueasasequenceofUTF16encodedcodepoints,asdescribedin6.1.4.

ThisfunctionworksexactlythesameastoUpperCaseexceptthatitsresultisintendedtoyieldthecorrectresultforthehost
environment'scurrentlocale,ratherthanalocaleindependentresult.Therewillonlybeadifferenceinthefewcases(such
asTurkish)wheretherulesforthatlanguageconlictwiththeregularUnicodecasemappings.

ThemeaningoftheoptionalparameterstothismethodaredeinedintheECMA402speciication;implementationsthatdo
notincludeECMA402supportmustnotusethoseparameterpositionsforanythingelse.

NOTE ThetoLocaleUpperCasefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaString
object.Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.22 String.prototype.toLowerCase()

ThisfunctioninterpretsaStringvalueasasequenceofUTF16encodedcodepoints,asdescribedin6.1.4.Thefollowing
stepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetcpListbeaListcontaininginorderthecodepointsasdeinedin6.1.4ofS,startingattheirstelementofS.
4.ForeachcodepointcincpList,iftheUnicodeCharacterDatabaseprovidesalanguageinsensitivelowercaseequivalent
ofc,thenreplacecincpListwiththatequivalentcodepoint(s).
5.LetcuListbeanewemptyList.
6.ForeachcodepointcincpList,inorder,appendtocuListtheelementsoftheUTF16Encodingofc.
7.LetLbeaStringwhoseelementsare,inorder,theelementsofcuList.
8.ReturnL.

TheresultmustbederivedaccordingtothelocaleinsensitivecasemappingsintheUnicodeCharacterDatabase(this
explicitlyincludesnotonlytheUnicodeData.txtile,butalsoalllocaleinsensitivemappingsintheSpecialCasings.txtilethat
accompaniesit).

NOTE1 Thecasemappingofsomecodepointsmayproducemultiplecodepoints.InthiscasetheresultStringmaynot
bethesamelengthasthesourceString.BecausebothtoUpperCaseandtoLowerCasehavecontextsensitive
behaviour,thefunctionsarenotsymmetrical.Inotherwords,s.toUpperCase().toLowerCase()isnot
necessarilyequaltos.toLowerCase().

NOTE2 ThetoLowerCasefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.23 String.prototype.toString()
WhenthetoStringmethodiscalled,thefollowingstepsaretaken:

1.Return?thisStringValue(thisvalue).

NOTE ForaStringobject,thetoStringmethodhappenstoreturnthesamethingasthevalueOfmethod.

21.1.3.24 String.prototype.toUpperCase()

ThisfunctioninterpretsaStringvalueasasequenceofUTF16encodedcodepoints,asdescribedin6.1.4.

ThisfunctionbehavesinexactlythesamewayasString.prototype.toLowerCase,exceptthatcodepointsaremappedto
theiruppercaseequivalentsasspeciiedintheUnicodeCharacterDatabase.

NOTE ThetoUpperCasefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.25 String.prototype.trim()

ThisfunctioninterpretsaStringvalueasasequenceofUTF16encodedcodepoints,asdescribedin6.1.4.

Thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetTbeaStringvaluethatisacopyofSwithbothleadingandtrailingwhitespaceremoved.Thedeinitionofwhite
spaceistheunionofWhiteSpaceandLineTerminator.WhendeterminingwhetheraUnicodecodepointisinUnicode
generalcategoryZs,codeunitsequencesareinterpretedasUTF16encodedcodepointsequencesasspeciiedin
6.1.4.
4.ReturnT.

NOTE Thetrimfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.Therefore,it
canbetransferredtootherkindsofobjectsforuseasamethod.

21.1.3.26 String.prototype.valueOf()

WhenthevalueOfmethodiscalled,thefollowingstepsaretaken:

1.Return?thisStringValue(thisvalue).

21.1.3.27 String.prototype[@@iterator]()

Whenthe@@iteratormethodiscalleditreturnsanIteratorobject(25.1.1.2)thatiteratesoverthecodepointsofaString
value,returningeachcodepointasaStringvalue.Thefollowingstepsaretaken:

1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.ReturnCreateStringIterator(S).

Thevalueofthenamepropertyofthisfunctionis"[Symbol.iterator]".

21.1.4 PropertiesofStringInstances

StringinstancesareStringexoticobjectsandhavetheinternalmethodsspeciiedforsuchobjects.Stringinstancesinherit
propertiesfromtheStringprototypeobject.Stringinstancesalsohavea[[StringData]]internalslot.

Stringinstanceshavealengthproperty,andasetofenumerablepropertieswithintegerindexednames.

21.1.4.1 length

ThenumberofelementsintheStringvaluerepresentedbythisStringobject.
OnceaStringobjectisinitialized,thispropertyisunchanging.Ithastheattributes{[[Writable]]:false,[[Enumerable]]:
false,[[Conigurable]]:false}.

21.1.5 StringIteratorObjects

AnStringIteratorisanobject,thatrepresentsaspeciiciterationoversomespeciicStringinstanceobject.Thereisnota
namedconstructorforStringIteratorobjects.Instead,StringiteratorobjectsarecreatedbycallingcertainmethodsofString
instanceobjects.

21.1.5.1 CreateStringIteratorAbstractOperation

SeveralmethodsofStringobjectsreturnIteratorobjects.TheabstractoperationCreateStringIteratorwithargumentstringis
usedtocreatesuchiteratorobjects.Itperformsthefollowingsteps:

1.Assert:Type(string)isString.
2.LetiteratorbeObjectCreate(%StringIteratorPrototype%,[[IteratedString]],[[StringIteratorNextIndex]]).
3.Setiterator's[[IteratedString]]internalslottostring.
4.Setiterator's[[StringIteratorNextIndex]]internalslotto0.
5.Returniterator.

21.1.5.2 The%StringIteratorPrototype%Object

AllStringIteratorObjectsinheritpropertiesfromthe%StringIteratorPrototype%intrinsicobject.The
%StringIteratorPrototype%objectisanordinaryobjectandits[[Prototype]]internalslotisthe%IteratorPrototype%
intrinsicobject.Inaddition,%StringIteratorPrototype%hasthefollowingproperties:

21.1.5.2.1 %StringIteratorPrototype%.next()

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavealloftheinternalslotsofanStringIteratorInstance(21.1.5.3),throwaTypeErrorexception.
4.Letsbethevalueofthe[[IteratedString]]internalslotofO.
5.Ifsisundeined,returnCreateIterResultObject(undeined,true).
6.Letpositionbethevalueofthe[[StringIteratorNextIndex]]internalslotofO.
7.Letlenbethenumberofelementsins.
8.Ifpositionlen,then
a.Setthevalueofthe[[IteratedString]]internalslotofOtoundeined.
b.ReturnCreateIterResultObject(undeined,true).
9.Letirstbethecodeunitvalueatindexpositionins.
10.Ifirst<0xD800orirst>0xDBFForposition+1=len,letresultStringbethestringconsistingofthesinglecodeunitirst.
11.Else,
a.Letsecondbethecodeunitvalueatindexposition+1intheStringS.
b.Ifsecond<0xDC00orsecond>0xDFFF,letresultStringbethestringconsistingofthesinglecodeunitirst.
c.Else,letresultStringbethestringconsistingofthecodeunitirstfollowedbythecodeunitsecond.
12.LetresultSizebethenumberofcodeunitsinresultString.
13.Setthevalueofthe[[StringIteratorNextIndex]]internalslotofOtoposition+resultSize.
14.ReturnCreateIterResultObject(resultString,false).

21.1.5.2.2 %StringIteratorPrototype%[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"StringIterator".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

21.1.5.3 PropertiesofStringIteratorInstances

StringIteratorinstancesareordinaryobjectsthatinheritpropertiesfromthe%StringIteratorPrototype%intrinsicobject.
StringIteratorinstancesareinitiallycreatedwiththeinternalslotslistedinTable47.
Table47:InternalSlotsofStringIteratorInstances
InternalSlot Description

[[IteratedString]] TheStringvaluewhoseelementsarebeingiterated.

[[StringIteratorNextIndex]] Theintegerindexofthenextstringindextobeexaminedbythisiteration.

21.2 RegExp(RegularExpression)Objects
ARegExpobjectcontainsaregularexpressionandtheassociatedlags.

NOTE TheformandfunctionalityofregularexpressionsismodelledaftertheregularexpressionfacilityinthePerl5
programminglanguage.

21.2.1 Patterns

TheRegExpconstructorappliesthefollowinggrammartotheinputpatternString.Anerroroccursifthegrammarcannot
interprettheStringasanexpansionofPattern.

Syntax

Pattern[U] ::
Disjunction[?U]

Disjunction[U] ::
Alternative[?U]
Alternative[?U] | Disjunction[?U]

Alternative[U] ::
[empty]
Alternative[?U] Term[?U]

Term[U] ::
Assertion[?U]
Atom[?U]
Atom[?U] Quantiier

Assertion[U] ::
^
$
\ b
\ B
( ? = Disjunction[?U] )
( ? ! Disjunction[?U] )

Quantiier ::
QuantiierPreix
QuantiierPreix ?

QuantiierPreix ::
*
+
?
{ DecimalDigits }
{ DecimalDigits , }
{ DecimalDigits , DecimalDigits }

Atom[U] ::
PatternCharacter
.
\ AtomEscape[?U]
CharacterClass[?U]
( Disjunction[?U] )
( ? : Disjunction[?U] )

SyntaxCharacter :: oneof
^ $ \ . * + ? ( ) [ ] { } |

PatternCharacter ::
SourceCharacter butnotSyntaxCharacter

AtomEscape[U] ::
DecimalEscape
CharacterEscape[?U]
CharacterClassEscape

CharacterEscape[U] ::
ControlEscape
c ControlLetter
HexEscapeSequence
RegExpUnicodeEscapeSequence[?U]
IdentityEscape[?U]

ControlEscape :: oneof
f n r t v

ControlLetter :: oneof
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

RegExpUnicodeEscapeSequence[U] ::
[+U] u LeadSurrogate \u TrailSurrogate
[+U] u LeadSurrogate
[+U] u TrailSurrogate
[+U] u NonSurrogate
[~U] u Hex4Digits
[+U] u{ HexDigits }

Each\uTrailSurrogateforwhichthechoiceofassociateduLeadSurrogateisambiguousshallbeassociatedwiththenearest
possibleuLeadSurrogatethatwouldotherwisehavenocorresponding\uTrailSurrogate.

LeadSurrogate ::
Hex4Digits butonlyiftheSVofHex4Digits isintheinclusiverange0xD800to0xDBFF

TrailSurrogate ::
Hex4Digits butonlyiftheSVofHex4Digits isintheinclusiverange0xDC00to0xDFFF

NonSurrogate ::
Hex4Digits butonlyiftheSVofHex4Digits isnotintheinclusiverange0xD800to0xDFFF
IdentityEscape[U] ::
[+U] SyntaxCharacter
[+U] /
[~U] SourceCharacter butnotUnicodeIDContinue

DecimalEscape ::
DecimalIntegerLiteral [lookaheadDecimalDigit]

CharacterClassEscape :: oneof
d D s S w W

CharacterClass[U] ::
[ [lookahead{^}] ClassRanges[?U] ]
[ ^ ClassRanges[?U] ]

ClassRanges[U] ::
[empty]
NonemptyClassRanges[?U]

NonemptyClassRanges[U] ::
ClassAtom[?U]
ClassAtom[?U] NonemptyClassRangesNoDash[?U]
ClassAtom[?U] ClassAtom[?U] ClassRanges[?U]

NonemptyClassRangesNoDash[U] ::
ClassAtom[?U]
ClassAtomNoDash[?U] NonemptyClassRangesNoDash[?U]
ClassAtomNoDash[?U] ClassAtom[?U] ClassRanges[?U]

ClassAtom[U] ::

ClassAtomNoDash[?U]

ClassAtomNoDash[U] ::
SourceCharacter butnotoneof\ or] or
\ ClassEscape[?U]

ClassEscape[U] ::
DecimalEscape
b
[+U]
CharacterEscape[?U]
CharacterClassEscape

21.2.1.1 StaticSemantics:EarlyErrors

RegExpUnicodeEscapeSequence :: u{ HexDigits }

ItisaSyntaxErroriftheMVofHexDigits>1114111.

21.2.2 PatternSemantics

Aregularexpressionpatternisconvertedintoaninternalprocedureusingtheprocessdescribedbelow.Animplementation
isencouragedtousemoreeficientalgorithmsthantheoneslistedbelow,aslongastheresultsarethesame.Theinternal
procedureisusedasthevalueofaRegExpobject's[[RegExpMatcher]]internalslot.
APatterniseitheraBMPpatternoraUnicodepatterndependinguponwhetherornotitsassociatedlagscontaina"u".A
BMPpatternmatchesagainstaStringinterpretedasconsistingofasequenceof16bitvaluesthatareUnicodecodepointsin
therangeoftheBasicMultilingualPlane.AUnicodepatternmatchesagainstaStringinterpretedasconsistingofUnicode
codepointsencodedusingUTF16.InthecontextofdescribingthebehaviourofaBMPpatterncharactermeansasingle
16bitUnicodeBMPcodepoint.InthecontextofdescribingthebehaviourofaUnicodepatterncharactermeansaUTF16
encodedcodepoint(6.1.4).Ineithercontext,charactervaluemeansthenumericvalueofthecorrespondingnonencoded
codepoint.

ThesyntaxandsemanticsofPatternisdeinedasifthesourcecodeforthePatternwasaListofSourceCharactervalues
whereeachSourceCharactercorrespondstoaUnicodecodepoint.IfaBMPpatterncontainsanonBMPSourceCharacterthe
entirepatternisencodedusingUTF16andtheindividualcodeunitsofthatencodingareusedastheelementsoftheList.

NOTE Forexample,considerapatternexpressedinsourcetextasthesinglenonBMPcharacterU+1D11E(MUSICAL
SYMBOLGCLEF).InterpretedasaUnicodepattern,itwouldbeasingleelement(character)Listconsistingof
thesinglecodepoint0x1D11E.However,interpretedasaBMPpattern,itisirstUTF16encodedtoproducea
twoelementListconsistingofthecodeunits0xD834and0xDD1E.

PatternsarepassedtotheRegExpconstructorasECMAScriptStringvaluesinwhichnonBMPcharactersare
UTF16encoded.Forexample,thesinglecharacterMUSICALSYMBOLGCLEFpattern,expressedasaString
value,isaStringoflength2whoseelementswerethecodeunits0xD834and0xDD1E.Sonofurther
translationofthestringwouldbenecessarytoprocessitasaBMPpatternconsistingoftwopattern
characters.However,toprocessitasaUnicodepatternUTF16DecodemustbeusedinproducingaList
consistingofasinglepatterncharacter,thecodepointU+1D11E.

AnimplementationmaynotactuallyperformsuchtranslationstoorfromUTF16,butthesemanticsofthis
speciicationrequiresthattheresultofpatternmatchingbeasifsuchtranslationswereperformed.

21.2.2.1 Notation

Thedescriptionsbelowusethefollowingvariables:

InputisaListconsistingofallofthecharacters,inorder,oftheStringbeingmatchedbytheregularexpressionpattern.
Eachcharacteriseitheracodeunitoracodepoint,dependinguponthekindofpatterninvolved.ThenotationInput[n]
meansthenthcharacterofInput,wherencanrangebetween0(inclusive)andInputLength(exclusive).
InputLengthisthenumberofcharactersinInput.
NcapturingParensisthetotalnumberofleftcapturingparentheses(i.e.thetotalnumberoftimestheAtom :: (
Disjunction ) productionisexpanded)inthepattern.Aleftcapturingparenthesisisany(patterncharacterthatis
matchedbythe(terminaloftheAtom :: ( Disjunction ) production.
IgnoreCaseistrueiftheRegExpobject's[[OriginalFlags]]internalslotcontains"i"andotherwiseisfalse.
MultilineistrueiftheRegExpobject's[[OriginalFlags]]internalslotcontains"m"andotherwiseisfalse.
UnicodeistrueiftheRegExpobject's[[OriginalFlags]]internalslotcontains"u"andotherwiseisfalse.

Furthermore,thedescriptionsbelowusethefollowinginternaldatastructures:

ACharSetisamathematicalsetofcharacters,eithercodeunitsorcodepointsdependingupthestateoftheUnicode
lag.AllcharactersmeanseitherallcodeunitvaluesorallcodepointvaluesalsodependinguponthestateifUnicode.
AStateisanorderedpair(endIndex,captures)whereendIndexisanintegerandcapturesisaListofNcapturingParens
values.Statesareusedtorepresentpartialmatchstatesintheregularexpressionmatchingalgorithms.TheendIndexis
oneplustheindexofthelastinputcharactermatchedsofarbythepattern,whilecapturesholdstheresultsofcapturing
parentheses.ThenthelementofcapturesiseitheraListthatrepresentsthevalueobtainedbythenthsetofcapturing
parenthesesorundeinedifthenthsetofcapturingparentheseshasn'tbeenreachedyet.Duetobacktracking,many
Statesmaybeinuseatanytimeduringthematchingprocess.
AMatchResultiseitheraStateorthespecialtokenfailurethatindicatesthatthematchfailed.
AContinuationprocedureisaninternalclosure(i.e.aninternalprocedurewithsomeargumentsalreadyboundto
values)thattakesoneStateargumentandreturnsaMatchResultresult.Ifaninternalclosurereferencesvariables
whichareboundinthefunctionthatcreatestheclosure,theclosureusesthevaluesthatthesevariableshadatthetime
theclosurewascreated.TheContinuationattemptstomatchtheremainingportion(speciiedbytheclosure'salready
boundarguments)ofthepatternagainstInput,startingattheintermediatestategivenbyitsStateargument.Ifthe
matchsucceeds,theContinuationreturnstheinalStatethatitreached;ifthematchfails,theContinuationreturns
failure.
AMatcherprocedureisaninternalclosurethattakestwoargumentsaStateandaContinuationandreturnsa
MatchResultresult.AMatcherattemptstomatchamiddlesubpattern(speciiedbytheclosure'salreadybound
arguments)ofthepatternagainstInput,startingattheintermediatestategivenbyitsStateargument.TheContinuation
argumentshouldbeaclosurethatmatchestherestofthepattern.Aftermatchingthesubpatternofapatterntoobtaina
newState,theMatcherthencallsContinuationonthatnewStatetotestiftherestofthepatterncanmatchaswell.Ifit
can,theMatcherreturnstheStatereturnedbyContinuation;ifnot,theMatchermaytrydifferentchoicesatitschoice
points,repeatedlycallingContinuationuntiliteithersucceedsorallpossibilitieshavebeenexhausted.
AnAssertionTesterprocedureisaninternalclosurethattakesaStateargumentandreturnsaBooleanresult.The
assertiontestertestsaspeciiccondition(speciiedbytheclosure'salreadyboundarguments)againstthecurrentplace
inInputandreturnstrueiftheconditionmatchedorfalseifnot.
AnEscapeValueiseitheracharacteroraninteger.AnEscapeValueisusedtodenotetheinterpretationofa
DecimalEscapeescapesequence:acharacterchmeansthattheescapesequenceisinterpretedasthecharacterch,while
anintegernmeansthattheescapesequenceisinterpretedasabackreferencetothenthsetofcapturingparentheses.

21.2.2.2 Pattern

TheproductionPattern :: Disjunction evaluatesasfollows:

1.EvaluateDisjunctiontoobtainaMatcherm.
2.Returnaninternalclosurethattakestwoarguments,aStringstrandanintegerindex,andperformsthefollowingsteps:
a.Assert:indexthenumberofelementsinstr.
b.IfUnicodeistrue,letInputbeaListconsistingofthesequenceofcodepointsofstrinterpretedasaUTF16
encoded(6.1.4)Unicodestring.Otherwise,letInputbeaListconsistingofthesequenceofcodeunitsthatarethe
elementsofstr.Inputwillbeusedthroughoutthealgorithmsin21.2.2.EachelementofInputisconsideredtobea
character.
c.LetInputLengthbethenumberofcharacterscontainedinInput.Thisvariablewillbeusedthroughoutthe
algorithmsin21.2.2.
d.LetlistIndexbetheindexintoInputofthecharacterthatwasobtainedfromelementindexofstr.
e.LetcbeaContinuationthatalwaysreturnsitsStateargumentasasuccessfulMatchResult.
f.LetcapbeaListofNcapturingParensundeinedvalues,indexed1throughNcapturingParens.
g.LetxbetheState(listIndex,cap).
h.Callm(x,c)andreturnitsresult.

NOTE APatternevaluates(compiles)toaninternalprocedurevalue.RegExpBuiltinExeccanthenapplythis
proceduretoaStringandanoffsetwithintheStringtodeterminewhetherthepatternwouldmatchstartingat
exactlythatoffsetwithintheString,and,ifitdoesmatch,whatthevaluesofthecapturingparentheseswould
be.Thealgorithmsin21.2.2aredesignedsothatcompilingapatternmaythrowaSyntaxErrorexception;on
theotherhand,oncethepatternissuccessfullycompiled,applyingtheresultinginternalproceduretoinda
matchinaStringcannotthrowanexception(exceptforanyhostdeinedexceptionsthatcanoccuranywhere
suchasoutofmemory).

21.2.2.3 Disjunction

TheproductionDisjunction :: Alternative evaluatesbyevaluatingAlternativetoobtainaMatcherandreturningthat


Matcher.

TheproductionDisjunction :: Alternative | Disjunction evaluatesasfollows:

1.EvaluateAlternativetoobtainaMatcherm1.
2.EvaluateDisjunctiontoobtainaMatcherm2.
3.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
stepswhenevaluated:
a.Callm1(x,c)andletrbeitsresult.
b.Ifrisnotfailure,returnr.
c.Callm2(x,c)andreturnitsresult.

NOTE The|regularexpressionoperatorseparatestwoalternatives.Thepatternirsttriestomatchtheleft
Alternative(followedbythesequeloftheregularexpression);ifitfails,ittriestomatchtherightDisjunction
(followedbythesequeloftheregularexpression).IftheleftAlternative,therightDisjunction,andthesequelall
havechoicepoints,allchoicesinthesequelaretriedbeforemovingontothenextchoiceintheleftAlternative.
IfchoicesintheleftAlternativeareexhausted,therightDisjunctionistriedinsteadoftheleftAlternative.Any
capturingparenthesesinsideaportionofthepatternskippedby|produceundeinedvaluesinsteadof
Strings.Thus,forexample,

/a|ab/.exec("abc")

returnstheresult"a"andnot"ab".Moreover,

/((a)|(ab))((c)|(bc))/.exec("abc")

returnsthearray

["abc","a","a",undefined,"bc",undefined,"bc"]

andnot

["abc","ab",undefined,"ab","c","c",undefined]

21.2.2.4 Alternative

TheproductionAlternative :: [empty] evaluatesbyreturningaMatcherthattakestwoarguments,aStatexanda


Continuationc,andreturnstheresultofcallingc(x).

TheproductionAlternative :: Alternative Term evaluatesasfollows:

1.EvaluateAlternativetoobtainaMatcherm1.
2.EvaluateTermtoobtainaMatcherm2.
3.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
stepswhenevaluated:
a.CreateaContinuationdthattakesaStateargumentyandreturnstheresultofcallingm2(y,c).
b.Callm1(x,d)andreturnitsresult.

NOTE ConsecutiveTermstrytosimultaneouslymatchconsecutiveportionsofInput.IftheleftAlternative,theright
Term,andthesequeloftheregularexpressionallhavechoicepoints,allchoicesinthesequelaretriedbefore
movingontothenextchoiceintherightTerm,andallchoicesintherightTermaretriedbeforemovingonto
thenextchoiceintheleftAlternative.

21.2.2.5 Term

TheproductionTerm :: Assertion evaluatesbyreturninganinternalMatcherclosurethattakestwoarguments,aStatex


andaContinuationc,andperformsthefollowingstepswhenevaluated:

1.EvaluateAssertiontoobtainanAssertionTestert.
2.Callt(x)andletrbetheresultingBooleanvalue.
3.Ifrisfalse,returnfailure.
4.Callc(x)andreturnitsresult.

TheproductionTerm :: Atom evaluatesasfollows:

1.ReturntheMatcherthatistheresultofevaluatingAtom.

TheproductionTerm :: Atom Quantiier evaluatesasfollows:


1.EvaluateAtomtoobtainaMatcherm.
2.EvaluateQuantiiertoobtainthethreeresults:anintegermin,aninteger(or)max,andBooleangreedy.
3.Ifmaxisiniteandlessthanmin,throwaSyntaxErrorexception.
4.LetparenIndexbethenumberofleftcapturingparenthesesintheentireregularexpressionthatoccurtotheleftofthis
productionexpansion'sTerm.ThisisthetotalnumberoftimestheAtom :: ( Disjunction ) productionisexpanded
priortothisproduction'sTermplusthetotalnumberofAtom :: ( Disjunction ) productionsenclosingthisTerm.
5.LetparenCountbethenumberofleftcapturingparenthesesintheexpansionofthisproduction'sAtom.Thisisthetotal
numberofAtom :: ( Disjunction ) productionsenclosedbythisproduction'sAtom.
6.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
stepswhenevaluated:
a.CallRepeatMatcher(m,min,max,greedy,x,c,parenIndex,parenCount)andreturnitsresult.

21.2.2.5.1 RuntimeSemantics:RepeatMatcherAbstractOperation

TheabstractoperationRepeatMatchertakeseightparameters,aMatcherm,anintegermin,aninteger(or)max,aBoolean
greedy,aStatex,aContinuationc,anintegerparenIndex,andanintegerparenCount,andperformsthefollowingsteps:

1.Ifmaxiszero,returnc(x).
2.CreateaninternalContinuationclosuredthattakesoneStateargumentyandperformsthefollowingstepswhen
evaluated:
a.Ifminiszeroandy'sendIndexisequaltox'sendIndex,returnfailure.
b.Ifminiszero,letmin2bezero;otherwiseletmin2bemin1.
c.Ifmaxis,letmax2be;otherwiseletmax2bemax1.
d.CallRepeatMatcher(m,min2,max2,greedy,y,c,parenIndex,parenCount)andreturnitsresult.
3.Letcapbeafreshcopyofx'scapturesList.
4.ForeveryintegerkthatsatisiesparenIndex<kandkparenIndex+parenCount,setcap[k]toundeined.
5.Letebex'sendIndex.
6.LetxrbetheState(e,cap).
7.Ifminisnotzero,returnm(xr,d).
8.Ifgreedyisfalse,then
a.Callc(x)andletzbeitsresult.
b.Ifzisnotfailure,returnz.
c.Callm(xr,d)andreturnitsresult.
9.Callm(xr,d)andletzbeitsresult.
10.Ifzisnotfailure,returnz.
11.Callc(x)andreturnitsresult.

NOTE1 AnAtomfollowedbyaQuantiierisrepeatedthenumberoftimesspeciiedbytheQuantiier.AQuantiiercan
benongreedy,inwhichcasetheAtompatternisrepeatedasfewtimesaspossiblewhilestillmatchingthe
sequel,oritcanbegreedy,inwhichcasetheAtompatternisrepeatedasmanytimesaspossiblewhilestill
matchingthesequel.TheAtompatternisrepeatedratherthantheinputcharactersequencethatitmatches,so
differentrepetitionsoftheAtomcanmatchdifferentinputsubstrings.

NOTE2 IftheAtomandthesequeloftheregularexpressionallhavechoicepoints,theAtomisirstmatchedasmany
(orasfew,ifnongreedy)timesaspossible.Allchoicesinthesequelaretriedbeforemovingontothenext
choiceinthelastrepetitionofAtom.Allchoicesinthelast(nth)repetitionofAtomaretriedbeforemovingon
tothenextchoiceinthenexttolast(n1)strepetitionofAtom;atwhichpointitmayturnoutthatmoreor
fewerrepetitionsofAtomarenowpossible;theseareexhausted(again,startingwitheitherasfeworasmany
aspossible)beforemovingontothenextchoiceinthe(n1)strepetitionofAtomandsoon.

Compare

/a[az]{2,4}/.exec("abcdefghi")

whichreturns"abcde"with
/a[az]{2,4}?/.exec("abcdefghi")

whichreturns"abc".

Consideralso

/(aa|aabaac|ba|b|c)*/.exec("aabaac")

which,bythechoicepointorderingabove,returnsthearray

["aaba","ba"]

andnotanyof:

["aabaac","aabaac"]
["aabaac","c"]

Theaboveorderingofchoicepointscanbeusedtowritearegularexpressionthatcalculatesthegreatest
commondivisoroftwonumbers(representedinunarynotation).Thefollowingexamplecalculatesthegcdof
10and15:

"aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\1*,\1+$/,"$1")

whichreturnsthegcdinunarynotation"aaaaa".

NOTE3 Step4oftheRepeatMatcherclearsAtom'scaptureseachtimeAtomisrepeated.Wecanseeitsbehaviourinthe
regularexpression

/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")

whichreturnsthearray

["zaacbbbcac","z","ac","a",undefined,"c"]

andnot

["zaacbbbcac","z","ac","a","bbb","c"]

becauseeachiterationoftheoutermost*clearsallcapturedStringscontainedinthequantiiedAtom,whichin
thiscaseincludescaptureStringsnumbered2,3,4,and5.

NOTE4 Step1oftheRepeatMatcher'sdclosurestatesthat,oncetheminimumnumberofrepetitionshasbeen
satisied,anymoreexpansionsofAtomthatmatchtheemptycharactersequencearenotconsideredfor
furtherrepetitions.Thispreventstheregularexpressionenginefromfallingintoanininitelooponpatterns
suchas:

/(a*)*/.exec("b")

ortheslightlymorecomplicated:

/(a*)b\1+/.exec("baaaac")

whichreturnsthearray

["b",""]

21.2.2.6 Assertion

TheproductionAssertion :: ^ evaluatesbyreturninganinternalAssertionTesterclosurethattakesaStateargumentxand
performsthefollowingstepswhenevaluated:

1.Letebex'sendIndex.
2.Ifeiszero,returntrue.
3.IfMultilineisfalse,returnfalse.
4.IfthecharacterInput[e1]isoneofLineTerminator,returntrue.
5.Returnfalse.

NOTE Evenwhentheylagisusedwithapattern,^alwaysmatchesonlyatthebeginningofInput,or(ifMultilineis
true)atthebeginningofaline.

TheproductionAssertion :: $ evaluatesbyreturninganinternalAssertionTesterclosurethattakesaStateargumentxand
performsthefollowingstepswhenevaluated:

1.Letebex'sendIndex.
2.IfeisequaltoInputLength,returntrue.
3.IfMultilineisfalse,returnfalse.
4.IfthecharacterInput[e]isoneofLineTerminator,returntrue.
5.Returnfalse.

TheproductionAssertion :: \ b evaluatesbyreturninganinternalAssertionTesterclosurethattakesaStateargumentx
andperformsthefollowingstepswhenevaluated:

1.Letebex'sendIndex.
2.CallIsWordChar(e1)andletabetheBooleanresult.
3.CallIsWordChar(e)andletbbetheBooleanresult.
4.Ifaistrueandbisfalse,returntrue.
5.Ifaisfalseandbistrue,returntrue.
6.Returnfalse.

TheproductionAssertion :: \ B evaluatesbyreturninganinternalAssertionTesterclosurethattakesaStateargumentx
andperformsthefollowingstepswhenevaluated:

1.Letebex'sendIndex.
2.CallIsWordChar(e1)andletabetheBooleanresult.
3.CallIsWordChar(e)andletbbetheBooleanresult.
4.Ifaistrueandbisfalse,returnfalse.
5.Ifaisfalseandbistrue,returnfalse.
6.Returntrue.

TheproductionAssertion :: ( ? = Disjunction ) evaluatesasfollows:

1.EvaluateDisjunctiontoobtainaMatcherm.
2.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
steps:
a.LetdbeaContinuationthatalwaysreturnsitsStateargumentasasuccessfulMatchResult.
b.Callm(x,d)andletrbeitsresult.
c.Ifrisfailure,returnfailure.
d.Letyber'sState.
e.Letcapbey'scapturesList.
f.Letxebex'sendIndex.
g.LetzbetheState(xe,cap).
h.Callc(z)andreturnitsresult.

TheproductionAssertion :: ( ? ! Disjunction ) evaluatesasfollows:

1.EvaluateDisjunctiontoobtainaMatcherm.
2.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
steps:
a.LetdbeaContinuationthatalwaysreturnsitsStateargumentasasuccessfulMatchResult.
b.Callm(x,d)andletrbeitsresult.
c.Ifrisnotfailure,returnfailure.
d.Callc(x)andreturnitsresult.

21.2.2.6.1 RuntimeSemantics:IsWordCharAbstractOperation

TheabstractoperationIsWordChartakesanintegerparametereandperformsthefollowingsteps:

1.Ifeis1oreisInputLength,returnfalse.
2.LetcbethecharacterInput[e].
3.Ifcisoneofthesixtythreecharactersbelow,returntrue.

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 _

4.Returnfalse.

21.2.2.7 Quantiier

TheproductionQuantiier :: QuantiierPreix evaluatesasfollows:

1.EvaluateQuantiierPreixtoobtainthetworesults:anintegerminandaninteger(or)max.
2.Returnthethreeresultsmin,max,andtrue.

TheproductionQuantiier :: QuantiierPreix ? evaluatesasfollows:

1.EvaluateQuantiierPreixtoobtainthetworesults:anintegerminandaninteger(or)max.
2.Returnthethreeresultsmin,max,andfalse.

TheproductionQuantiierPreix :: * evaluatesasfollows:

1.Returnthetworesults0and.

TheproductionQuantiierPreix :: + evaluatesasfollows:

1.Returnthetworesults1and.

TheproductionQuantiierPreix :: ? evaluatesasfollows:

1.Returnthetworesults0and1.

TheproductionQuantiierPreix :: { DecimalDigits } evaluatesasfollows:

1.LetibetheMVofDecimalDigits(see11.8.3).
2.Returnthetworesultsiandi.

TheproductionQuantiierPreix :: { DecimalDigits , } evaluatesasfollows:

1.LetibetheMVofDecimalDigits.
2.Returnthetworesultsiand.

TheproductionQuantiierPreix :: { DecimalDigits , DecimalDigits } evaluatesasfollows:

1.LetibetheMVoftheirstDecimalDigits.
2.LetjbetheMVofthesecondDecimalDigits.
3.Returnthetworesultsiandj.

21.2.2.8 Atom
TheproductionAtom :: PatternCharacter evaluatesasfollows:

1.LetchbethecharactermatchedbyPatternCharacter.
2.LetAbeaoneelementCharSetcontainingthecharacterch.
3.CallCharacterSetMatcher(A,false)andreturnitsMatcherresult.

TheproductionAtom :: . evaluatesasfollows:

1.LetAbethesetofallcharactersexceptLineTerminator.
2.CallCharacterSetMatcher(A,false)andreturnitsMatcherresult.

TheproductionAtom :: \ AtomEscape evaluatesasfollows:

1.ReturntheMatcherthatistheresultofevaluatingAtomEscape.

TheproductionAtom :: CharacterClass evaluatesasfollows:

1.EvaluateCharacterClasstoobtainaCharSetAandaBooleaninvert.
2.CallCharacterSetMatcher(A,invert)andreturnitsMatcherresult.

TheproductionAtom :: ( Disjunction ) evaluatesasfollows:

1.EvaluateDisjunctiontoobtainaMatcherm.
2.LetparenIndexbethenumberofleftcapturingparenthesesintheentireregularexpressionthatoccurtotheleftofthis
productionexpansion'sinitialleftparenthesis.ThisisthetotalnumberoftimestheAtom :: ( Disjunction )
productionisexpandedpriortothisproduction'sAtomplusthetotalnumberofAtom :: ( Disjunction ) productions
enclosingthisAtom.
3.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
steps:
a.CreateaninternalContinuationclosuredthattakesoneStateargumentyandperformsthefollowingsteps:
i.Letcapbeafreshcopyofy'scapturesList.
ii.Letxebex'sendIndex.
iii.Letyebey'sendIndex.
iv.LetsbeafreshListwhosecharactersarethecharactersofInputatindicesxe(inclusive)throughye
(exclusive).
v.Setcap[parenIndex+1]tos.
vi.LetzbetheState(ye,cap).
vii.Callc(z)andreturnitsresult.
b.Callm(x,d)andreturnitsresult.

TheproductionAtom :: ( ? : Disjunction ) evaluatesasfollows:

1.ReturntheMatcherthatistheresultofevaluatingDisjunction.

21.2.2.8.1 RuntimeSemantics:CharacterSetMatcherAbstractOperation

TheabstractoperationCharacterSetMatchertakestwoarguments,aCharSetAandaBooleanlaginvert,andperformsthe
followingsteps:

1.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
stepswhenevaluated:
a.Letebex'sendIndex.
b.IfeisInputLength,returnfailure.
c.LetchbethecharacterInput[e].
d.LetccbeCanonicalize(ch).
e.Ifinvertisfalse,then
i.IftheredoesnotexistamemberaofsetAsuchthatCanonicalize(a)iscc,returnfailure.
f.Elseinvertistrue,
i.IfthereexistsamemberaofsetAsuchthatCanonicalize(a)iscc,returnfailure.
g.Letcapbex'scapturesList.
h.LetybetheState(e+1,cap).
i.Callc(y)andreturnitsresult.

21.2.2.8.2 RuntimeSemantics:Canonicalize(ch)

TheabstractoperationCanonicalizetakesacharacterparameterchandperformsthefollowingsteps:

1.IfIgnoreCaseisfalse,returnch.
2.IfUnicodeistrue,then
a.IftheileCaseFolding.txtoftheUnicodeCharacterDatabaseprovidesasimpleorcommoncasefoldingmapping
forch,returntheresultofapplyingthatmappingtoch.
b.Else,returnch.
3.Else,
a.Assert:chisaUTF16codeunit.
b.LetsbetheECMAScriptStringvalueconsistingofthesinglecodeunitch.
c.LetubethesameresultproducedasifbyperformingthealgorithmforString.prototype.toUpperCaseusing
sasthethisvalue.
d.Assert:uisaStringvalue.
e.Ifudoesnotconsistofasinglecodeunit,returnch.
f.Letcubeu'ssinglecodeunitelement.
g.Ifch'scodeunitvalue128andcu'scodeunitvalue<128,returnch.
h.Returncu.

NOTE1 Parenthesesoftheform(Disjunction)servebothtogroupthecomponentsoftheDisjunctionpatterntogether
andtosavetheresultofthematch.Theresultcanbeusedeitherinabackreference(\followedbyanonzero
decimalnumber),referencedinareplaceString,orreturnedaspartofanarrayfromtheregularexpression
matchinginternalprocedure.Toinhibitthecapturingbehaviourofparentheses,usetheform(?:Disjunction)
instead.

NOTE2 Theform(?=Disjunction)speciiesazerowidthpositivelookahead.Inorderforittosucceed,thepattern
insideDisjunctionmustmatchatthecurrentposition,butthecurrentpositionisnotadvancedbeforematching
thesequel.IfDisjunctioncanmatchatthecurrentpositioninseveralways,onlytheirstoneistried.Unlike
otherregularexpressionoperators,thereisnobacktrackingintoa(?=form(thisunusualbehaviouris
inheritedfromPerl).ThisonlymatterswhentheDisjunctioncontainscapturingparenthesesandthesequelof
thepatterncontainsbackreferencestothosecaptures.

Forexample,

/(?=(a+))/.exec("baaabac")

matchestheemptyStringimmediatelyaftertheirstbandthereforereturnsthearray:

["","aaa"]

Toillustratethelackofbacktrackingintothelookahead,consider:

/(?=(a+))a*b\1/.exec("baaabac")

Thisexpressionreturns

["aba","a"]

andnot:

["aaaba","a"]
NOTE3 Theform(?!Disjunction)speciiesazerowidthnegativelookahead.Inorderforittosucceed,thepattern
insideDisjunctionmustfailtomatchatthecurrentposition.Thecurrentpositionisnotadvancedbefore
matchingthesequel.Disjunctioncancontaincapturingparentheses,butbackreferencestothemonlymake
sensefromwithinDisjunctionitself.Backreferencestothesecapturingparenthesesfromelsewhereinthe
patternalwaysreturnundeinedbecausethenegativelookaheadmustfailforthepatterntosucceed.For
example,

/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")

looksforananotimmediatelyfollowedbysomepositivenumbernofa's,ab,anotherna's(speciiedbythe
irst\2)andac.Thesecond\2isoutsidethenegativelookahead,soitmatchesagainstundeinedand
thereforealwayssucceeds.Thewholeexpressionreturnsthearray:

["baaabaac","ba",undefined,"abaac"]

NOTE4 IncaseinsigniicantmatcheswhenUnicodeistrue,allcharactersareimplicitlycasefoldedusingthesimple
mappingprovidedbytheUnicodestandardimmediatelybeforetheyarecompared.Thesimplemapping
alwaysmapstoasinglecodepoint,soitdoesnotmap,forexample,""(U+00DF)to"SS".Itmayhowever
mapacodepointoutsidetheBasicLatinrangetoacharacterwithin,forexample,""(U+017F)to"s".Such
charactersarenotmappedifUnicodeisfalse.ThispreventsUnicodecodepointssuchasU+017FandU+212A
frommatchingregularexpressionssuchas/[az]/i,buttheywillmatch/[az]/ui.

21.2.2.9 AtomEscape

TheproductionAtomEscape :: DecimalEscape evaluatesasfollows:

1.EvaluateDecimalEscapetoobtainanEscapeValueE.
2.IfEisacharacter,then
a.LetchbeE'scharacter.
b.LetAbeaoneelementCharSetcontainingthecharacterch.
c.CallCharacterSetMatcher(A,false)andreturnitsMatcherresult.
3.Assert:Emustbeaninteger.
4.Letnbethatinteger.
5.Ifn=0orn>NcapturingParens,throwaSyntaxErrorexception.
6.ReturnaninternalMatcherclosurethattakestwoarguments,aStatexandaContinuationc,andperformsthefollowing
steps:
a.Letcapbex'scapturesList.
b.Letsbecap[n].
c.Ifsisundeined,returnc(x).
d.Letebex'sendIndex.
e.Letlenbes'slength.
f.Letfbee+len.
g.Iff>InputLength,returnfailure.
h.Ifthereexistsanintegeribetween0(inclusive)andlen(exclusive)suchthatCanonicalize(s[i])isnotthesame
charactervalueasCanonicalize(Input[e+i]),returnfailure.
i.LetybetheState(f,cap).
j.Callc(y)andreturnitsresult.

TheproductionAtomEscape :: CharacterEscape evaluatesasfollows:

1.EvaluateCharacterEscapetoobtainacharacterch.
2.LetAbeaoneelementCharSetcontainingthecharacterch.
3.CallCharacterSetMatcher(A,false)andreturnitsMatcherresult.

TheproductionAtomEscape :: CharacterClassEscape evaluatesasfollows:

1.EvaluateCharacterClassEscapetoobtainaCharSetA.
2.CallCharacterSetMatcher(A,false)andreturnitsMatcherresult.

NOTE Anescapesequenceoftheform\followedbyanonzerodecimalnumbernmatchestheresultofthenthsetof
capturingparentheses(see0).Itisanerroriftheregularexpressionhasfewerthanncapturingparentheses.If
theregularexpressionhasnormorecapturingparenthesesbutthenthoneisundeinedbecauseithasnot
capturedanything,thenthebackreferencealwayssucceeds.

21.2.2.10 CharacterEscape

TheproductionCharacterEscape :: ControlEscape evaluatesbyreturningthecharacteraccordingtoTable48.

Table48:ControlEscapeCharacterValues
ControlEscape CharacterValue CodePoint UnicodeName Symbol

t 9 U+0009 CHARACTERTABULATION <HT>

n 10 U+000A LINEFEED(LF) <LF>

v 11 U+000B LINETABULATION <VT>

f 12 U+000C FORMFEED(FF) <FF>

r 13 U+000D CARRIAGERETURN(CR) <CR>

TheproductionCharacterEscape :: c ControlLetter evaluatesasfollows:

1.LetchbethecharactermatchedbyControlLetter.
2.Letibech'scharactervalue.
3.Letjbetheremainderofdividingiby32.
4.Returnthecharacterwhosecharactervalueisj.

TheproductionCharacterEscape :: HexEscapeSequence evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheSVofHexEscapeSequence.

TheproductionCharacterEscape :: RegExpUnicodeEscapeSequence evaluatesasfollows:

1.ReturntheresultofevaluatingRegExpUnicodeEscapeSequence.

TheproductionCharacterEscape :: IdentityEscape evaluatesasfollows:

1.ReturnthecharactermatchedbyIdentityEscape.

TheproductionRegExpUnicodeEscapeSequence :: u LeadSurrogate \u TrailSurrogate evaluatesasfollows:

1.LetleadbetheresultofevaluatingLeadSurrogate.
2.LettrailbetheresultofevaluatingTrailSurrogate.
3.LetcpbeUTF16Decode(lead,trail).
4.Returnthecharacterwhosecharactervalueiscp.

TheproductionRegExpUnicodeEscapeSequence :: u LeadSurrogate evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheresultofevaluatingLeadSurrogate.

TheproductionRegExpUnicodeEscapeSequence :: u TrailSurrogate evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheresultofevaluatingTrailSurrogate.

TheproductionRegExpUnicodeEscapeSequence :: u NonSurrogate evaluatesasfollows:


1.ReturnthecharacterwhosecodeistheresultofevaluatingNonSurrogate.

TheproductionRegExpUnicodeEscapeSequence :: u Hex4Digits evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheSVofHex4Digits.

TheproductionRegExpUnicodeEscapeSequence :: u{ HexDigits } evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheMVofHexDigits.

TheproductionLeadSurrogate :: Hex4Digits evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheSVofHex4Digits.

TheproductionTrailSurrogate :: Hex4Digits evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheSVofHex4Digits.

TheproductionNonSurrogate :: Hex4Digits evaluatesasfollows:

1.ReturnthecharacterwhosecodeistheSVofHex4Digits.

21.2.2.11 DecimalEscape

TheproductionDecimalEscape :: DecimalIntegerLiteral evaluatesasfollows:

1.LetibetheMVofDecimalIntegerLiteral.
2.Ifiiszero,returntheEscapeValueconsistingofthecharacterU+0000(NULL).
3.ReturntheEscapeValueconsistingoftheintegeri.

ThedeinitionoftheMVofDecimalIntegerLiteralisin11.8.3.

NOTE If\isfollowedbyadecimalnumbernwhoseirstdigitisnot0,thentheescapesequenceisconsideredtobea
backreference.Itisanerrorifnisgreaterthanthetotalnumberofleftcapturingparenthesesintheentire
regularexpression.\0representsthe<NUL>characterandcannotbefollowedbyadecimaldigit.

21.2.2.12 CharacterClassEscape

TheproductionCharacterClassEscape :: d evaluatesbyreturningthetenelementsetofcharacterscontainingthe
characters0through9inclusive.

TheproductionCharacterClassEscape :: D evaluatesbyreturningthesetofallcharactersnotincludedinthesetreturned
byCharacterClassEscape :: d .

TheproductionCharacterClassEscape :: s evaluatesbyreturningthesetofcharacterscontainingthecharactersthatareon
therighthandsideoftheWhiteSpaceorLineTerminatorproductions.

TheproductionCharacterClassEscape :: S evaluatesbyreturningthesetofallcharactersnotincludedinthesetreturned
byCharacterClassEscape :: s .

TheproductionCharacterClassEscape :: w evaluatesbyreturningthesetofcharacterscontainingthesixtythree
characters:

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 _

TheproductionCharacterClassEscape :: W evaluatesbyreturningthesetofallcharactersnotincludedinthesetreturned
byCharacterClassEscape :: w .
21.2.2.13 CharacterClass

TheproductionCharacterClass :: [ ClassRanges ] evaluatesbyevaluatingClassRangestoobtainaCharSetandreturning


thatCharSetandtheBooleanfalse.

TheproductionCharacterClass :: [ ^ ClassRanges ] evaluatesbyevaluatingClassRangestoobtainaCharSetandreturning


thatCharSetandtheBooleantrue.

21.2.2.14 ClassRanges

TheproductionClassRanges :: [empty] evaluatesbyreturningtheemptyCharSet.

TheproductionClassRanges :: NonemptyClassRanges evaluatesbyevaluatingNonemptyClassRangestoobtainaCharSetand


returningthatCharSet.

21.2.2.15 NonemptyClassRanges

TheproductionNonemptyClassRanges :: ClassAtom evaluatesasfollows:

1.ReturntheCharSetthatistheresultofevaluatingClassAtom.

TheproductionNonemptyClassRanges :: ClassAtom NonemptyClassRangesNoDash evaluatesasfollows:

1.EvaluateClassAtomtoobtainaCharSetA.
2.EvaluateNonemptyClassRangesNoDashtoobtainaCharSetB.
3.ReturntheunionofCharSetsAandB.

TheproductionNonemptyClassRanges :: ClassAtom ClassAtom ClassRanges evaluatesasfollows:

1.EvaluatetheirstClassAtomtoobtainaCharSetA.
2.EvaluatethesecondClassAtomtoobtainaCharSetB.
3.EvaluateClassRangestoobtainaCharSetC.
4.CallCharacterRange(A,B)andletDbetheresultingCharSet.
5.ReturntheunionofCharSetsDandC.

21.2.2.15.1 RuntimeSemantics:CharacterRangeAbstractOperation

TheabstractoperationCharacterRangetakestwoCharSetparametersAandBandperformsthefollowingsteps:

1.IfAdoesnotcontainexactlyonecharacterorBdoesnotcontainexactlyonecharacter,throwaSyntaxErrorexception.
2.LetabetheonecharacterinCharSetA.
3.LetbbetheonecharacterinCharSetB.
4.Letibethecharactervalueofcharactera.
5.Letjbethecharactervalueofcharacterb.
6.Ifi>j,throwaSyntaxErrorexception.
7.Returnthesetcontainingallcharactersnumberedithroughj,inclusive.

21.2.2.16 NonemptyClassRangesNoDash

TheproductionNonemptyClassRangesNoDash :: ClassAtom evaluatesasfollows:

1.ReturntheCharSetthatistheresultofevaluatingClassAtom.

TheproductionNonemptyClassRangesNoDash :: ClassAtomNoDash NonemptyClassRangesNoDash evaluatesasfollows:

1.EvaluateClassAtomNoDashtoobtainaCharSetA.
2.EvaluateNonemptyClassRangesNoDashtoobtainaCharSetB.
3.ReturntheunionofCharSetsAandB.

TheproductionNonemptyClassRangesNoDash :: ClassAtomNoDash ClassAtom ClassRanges evaluatesasfollows:


1.EvaluateClassAtomNoDashtoobtainaCharSetA.
2.EvaluateClassAtomtoobtainaCharSetB.
3.EvaluateClassRangestoobtainaCharSetC.
4.CallCharacterRange(A,B)andletDbetheresultingCharSet.
5.ReturntheunionofCharSetsDandC.

NOTE1 ClassRangescanexpandintoasingleClassAtomand/orrangesoftwoClassAtomseparatedbydashes.Inthe
lattercasetheClassRangesincludesallcharactersbetweentheirstClassAtomandthesecondClassAtom,
inclusive;anerroroccursifeitherClassAtomdoesnotrepresentasinglecharacter(forexample,ifoneis\w)
oriftheirstClassAtom'scharactervalueisgreaterthanthesecondClassAtom'scharactervalue.

NOTE2 Evenifthepatternignorescase,thecaseofthetwoendsofarangeissigniicantindeterminingwhich
charactersbelongtotherange.Thus,forexample,thepattern/[EF]/imatchesonlythelettersE,F,e,andf,
whilethepattern/[Ef]/imatchesallupperandlowercaselettersintheUnicodeBasicLatinblockaswell
asthesymbols[,\,],^,_,and`.

NOTE3 Acharactercanbetreatedliterallyoritcandenotearange.Itistreatedliterallyifitistheirstorlast
characterofClassRanges,thebeginningorendlimitofarangespeciication,orimmediatelyfollowsarange
speciication.

21.2.2.17 ClassAtom

TheproductionClassAtom :: evaluatesbyreturningtheCharSetcontainingtheonecharacter.

TheproductionClassAtom :: ClassAtomNoDash evaluatesbyevaluatingClassAtomNoDashtoobtainaCharSetandreturning


thatCharSet.

21.2.2.18 ClassAtomNoDash

TheproductionClassAtomNoDash :: SourceCharacter butnotoneof\ or] or evaluatesasfollows:

1.ReturntheCharSetcontainingthecharactermatchedbySourceCharacter.

TheproductionClassAtomNoDash :: \ ClassEscape evaluatesasfollows:

1.ReturntheCharSetthatistheresultofevaluatingClassEscape.

21.2.2.19 ClassEscape

TheproductionClassEscape :: DecimalEscape evaluatesasfollows:

1.EvaluateDecimalEscapetoobtainanEscapeValueE.
2.IfEisnotacharacter,throwaSyntaxErrorexception.
3.LetchbeE'scharacter.
4.ReturntheoneelementCharSetcontainingthecharacterch.

TheproductionClassEscape :: b evaluatesasfollows:

1.ReturntheCharSetcontainingthesinglecharacter<BS>U+0008(BACKSPACE).

TheproductionClassEscape :: evaluatesasfollows:

1.ReturntheCharSetcontainingthesinglecharacterU+002D(HYPHENMINUS).

TheproductionClassEscape :: CharacterEscape evaluatesasfollows:

1.ReturntheCharSetcontainingthesinglecharacterthatistheresultofevaluatingCharacterEscape.

TheproductionClassEscape :: CharacterClassEscape evaluatesasfollows:

1.ReturntheCharSetthatistheresultofevaluatingCharacterClassEscape.
NOTE AClassAtomcanuseanyoftheescapesequencesthatareallowedintherestoftheregularexpressionexcept
for\b,\B,andbackreferences.InsideaCharacterClass,\bmeansthebackspacecharacter,while\Band
backreferencesraiseerrors.UsingabackreferenceinsideaClassAtomcausesanerror.

21.2.3 TheRegExpConstructor

TheRegExpconstructoristhe%RegExp%intrinsicobjectandtheinitialvalueoftheRegExppropertyoftheglobalobject.
WhenRegExpiscalledasafunctionratherthanasaconstructor,itcreatesandinitializesanewRegExpobject.Thusthe
functioncallRegExp()isequivalenttotheobjectcreationexpressionnewRegExp()withthesamearguments.

TheRegExpconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedRegExpbehaviourmustincludeasupercalltotheRegExp
constructortocreateandinitializesubclassinstanceswiththenecessaryinternalslots.

21.2.3.1 RegExp(pattern,lags)

Thefollowingstepsaretaken:

1.LetpatternIsRegExpbe?IsRegExp(pattern).
2.IfNewTargetisnotundeined,letnewTargetbeNewTarget.
3.Else,
a.LetnewTargetbetheactivefunctionobject.
b.IfpatternIsRegExpistrueandlagsisundeined,then
i.LetpatternConstructorbe?Get(pattern,"constructor").
ii.IfSameValue(newTarget,patternConstructor)istrue,returnpattern.
4.IfType(pattern)isObjectandpatternhasa[[RegExpMatcher]]internalslot,then
a.LetPbethevalueofpattern's[[OriginalSource]]internalslot.
b.Iflagsisundeined,letFbethevalueofpattern's[[OriginalFlags]]internalslot.
c.Else,letFbelags.
5.ElseifpatternIsRegExpistrue,then
a.LetPbe?Get(pattern,"source").
b.Iflagsisundeined,then
i.LetFbe?Get(pattern,"flags").
c.Else,letFbelags.
6.Else,
a.LetPbepattern.
b.LetFbelags.
7.LetObe?RegExpAlloc(newTarget).
8.Return?RegExpInitialize(O,P,F).

NOTE IfpatternissuppliedusingaStringLiteral,theusualescapesequencesubstitutionsareperformedbeforethe
StringisprocessedbyRegExp.IfpatternmustcontainanescapesequencetoberecognizedbyRegExp,any
U+005C(REVERSESOLIDUS)codepointsmustbeescapedwithintheStringLiteraltopreventthembeing
removedwhenthecontentsoftheStringLiteralareformed.

21.2.3.2 AbstractOperationsfortheRegExpConstructor

21.2.3.2.1 RuntimeSemantics:RegExpAlloc(newTarget)

WhentheabstractoperationRegExpAllocwithargumentnewTargetiscalled,thefollowingstepsaretaken:

1.Letobjbe?OrdinaryCreateFromConstructor(newTarget,"%RegExpPrototype%",[[RegExpMatcher]],
[[OriginalSource]],[[OriginalFlags]]).
2.Perform!DeinePropertyOrThrow(obj,"lastIndex",PropertyDescriptor{[[Writable]]:true,[[Enumerable]]:false,
[[Conigurable]]:false}).
3.Returnobj.
21.2.3.2.2 RuntimeSemantics:RegExpInitialize(obj,pattern,lags)

WhentheabstractoperationRegExpInitializewithargumentsobj,pattern,andlagsiscalled,thefollowingstepsaretaken:

1.Ifpatternisundeined,letPbetheemptyString.
2.Else,letPbe?ToString(pattern).
3.Iflagsisundeined,letFbetheemptyString.
4.Else,letFbe?ToString(lags).
5.IfFcontainsanycodeunitotherthan"g","i","m","u",or"y"orifitcontainsthesamecodeunitmorethanonce,
throwaSyntaxErrorexception.
6.IfFcontains"u",letBMPbefalse;elseletBMPbetrue.
7.IfBMPistrue,then
a.ParsePusingthegrammarsin21.2.1andinterpretingeachofits16bitelementsasaUnicodeBMPcodepoint.
UTF16decodingisnotappliedtotheelements.ThegoalsymbolfortheparseisPattern.ThrowaSyntaxError
exceptionifPdidnotconformtothegrammar,ifanyelementsofPwerenotmatchedbytheparse,orifanyEarly
Errorconditionsexist.
b.LetpatternCharactersbeaListwhoseelementsarethecodeunitelementsofP.
8.Else,
a.ParsePusingthegrammarsin21.2.1andinterpretingPasUTF16encodedUnicodecodepoints(6.1.4).Thegoal
symbolfortheparseisPattern[U] .ThrowaSyntaxErrorexceptionifPdidnotconformtothegrammar,ifany
elementsofPwerenotmatchedbytheparse,orifanyEarlyErrorconditionsexist.
b.LetpatternCharactersbeaListwhoseelementsarethecodepointsresultingfromapplyingUTF16decodingtoP's
sequenceofelements.
9.Setthevalueofobj's[[OriginalSource]]internalslottoP.
10.Setthevalueofobj's[[OriginalFlags]]internalslottoF.
11.Setobj's[[RegExpMatcher]]internalslottotheinternalprocedurethatevaluatestheaboveparseofPbyapplyingthe
semanticsprovidedin21.2.2usingpatternCharactersasthepattern'sListofSourceCharactervaluesandFasthelag
parameters.
12.Perform?Set(obj,"lastIndex",0,true).
13.Returnobj.

21.2.3.2.3 RuntimeSemantics:RegExpCreate(P,F)

WhentheabstractoperationRegExpCreatewithargumentsPandFiscalled,thefollowingstepsaretaken:

1.Letobjbe?RegExpAlloc(%RegExp%).
2.Return?RegExpInitialize(obj,P,F).

21.2.3.2.4 RuntimeSemantics:EscapeRegExpPattern(P,F)

WhentheabstractoperationEscapeRegExpPatternwithargumentsPandFiscalled,thefollowingoccurs:

1.LetSbeaStringintheformofaPattern(Pattern[U] ifFcontains"u")equivalenttoPinterpretedasUTF16encoded
Unicodecodepoints(6.1.4),inwhichcertaincodepointsareescapedasdescribedbelow.Smayormaynotbeidentical
toP;however,theinternalprocedurethatwouldresultfromevaluatingSasaPattern(Pattern[U] ifFcontains"u")
mustbehaveidenticallytotheinternalproceduregivenbytheconstructedobject's[[RegExpMatcher]]internalslot.
MultiplecallstothisabstractoperationusingthesamevaluesforPandFmustproduceidenticalresults.
2.Thecodepoints/oranyLineTerminatoroccurringinthepatternshallbeescapedinSasnecessarytoensurethatthe
StringvalueformedbyconcatenatingtheStrings"/",S,"/",andFcanbeparsed(inanappropriatelexicalcontext)asa
RegularExpressionLiteralthatbehavesidenticallytotheconstructedregularexpression.Forexample,ifPis"/",thenS
couldbe"\/"or"\u002F",amongotherpossibilities,butnot"/",because///followedbyFwouldbeparsedasa
SingleLineCommentratherthanaRegularExpressionLiteral.IfPistheemptyString,thisspeciicationcanbemetby
lettingSbe"(?:)".
3.ReturnS.

21.2.4 PropertiesoftheRegExpConstructor
Thevalueofthe[[Prototype]]internalslotoftheRegExpconstructoristheintrinsicobject%FunctionPrototype%.

TheRegExpconstructorhasthefollowingproperties:

21.2.4.1 RegExp.prototype

TheinitialvalueofRegExp.prototypeistheintrinsicobject%RegExpPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

21.2.4.2 getRegExp[@@species]

RegExp[@@species]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunctionperforms
thefollowingsteps:

1.Returnthethisvalue.

Thevalueofthenamepropertyofthisfunctionis"get[Symbol.species]".

NOTE RegExpprototypemethodsnormallyusetheirthisobject'sconstructortocreateaderivedobject.However,a
subclassconstructormayoverridethatdefaultbehaviourbyredeiningits@@speciesproperty.

21.2.5 PropertiesoftheRegExpPrototypeObject

TheRegExpprototypeobjectistheintrinsicobject%RegExpPrototype%.TheRegExpprototypeobjectisanordinaryobject.
ItisnotaRegExpinstanceanddoesnothavea[[RegExpMatcher]]internalslotoranyoftheotherinternalslotsofRegExp
instanceobjects.

Thevalueofthe[[Prototype]]internalslotoftheRegExpprototypeobjectistheintrinsicobject%ObjectPrototype%.

NOTE TheRegExpprototypeobjectdoesnothaveavalueOfpropertyofitsown;however,itinheritsthevalueOf
propertyfromtheObjectprototypeobject.

21.2.5.1 RegExp.prototype.constructor

TheinitialvalueofRegExp.prototype.constructoristheintrinsicobject%RegExp%.

21.2.5.2 RegExp.prototype.exec(string)

PerformsaregularexpressionmatchofstringagainsttheregularexpressionandreturnsanArrayobjectcontainingthe
resultsofthematch,ornullifstringdidnotmatch.

TheStringToString(string)issearchedforanoccurrenceoftheregularexpressionpatternasfollows:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.IfRdoesnothavea[[RegExpMatcher]]internalslot,throwaTypeErrorexception.
4.LetSbe?ToString(string).
5.Return?RegExpBuiltinExec(R,S).

21.2.5.2.1 RuntimeSemantics:RegExpExec(R,S)

TheabstractoperationRegExpExecwithargumentsRandSperformsthefollowingsteps:

1.Assert:Type(R)isObject.
2.Assert:Type(S)isString.
3.Letexecbe?Get(R,"exec").
4.IfIsCallable(exec)istrue,then
a.Letresultbe?Call(exec,R,S).
b.IfType(result)isneitherObjectorNull,throwaTypeErrorexception.
c.Returnresult.
5.IfRdoesnothavea[[RegExpMatcher]]internalslot,throwaTypeErrorexception.
6.Return?RegExpBuiltinExec(R,S).

NOTE IfacallableexecpropertyisnotfoundthisalgorithmfallsbacktoattemptingtousethebuiltinRegExp
matchingalgorithm.Thisprovidescompatiblebehaviourforcodewrittenforprioreditionswheremostbuilt
inalgorithmsthatuseregularexpressionsdidnotperformadynamicpropertylookupofexec.

21.2.5.2.2 RuntimeSemantics:RegExpBuiltinExec(R,S)

TheabstractoperationRegExpBuiltinExecwithargumentsRandSperformsthefollowingsteps:

1.Assert:RisaninitializedRegExpinstance.
2.Assert:Type(S)isString.
3.LetlengthbethenumberofcodeunitsinS.
4.LetlastIndexbe?ToLength(?Get(R,"lastIndex")).
5.LetglobalbeToBoolean(?Get(R,"global")).
6.LetstickybeToBoolean(?Get(R,"sticky")).
7.Ifglobalisfalseandstickyisfalse,letlastIndexbe0.
8.LetmatcherbethevalueofR's[[RegExpMatcher]]internalslot.
9.LetlagsbethevalueofR's[[OriginalFlags]]internalslot.
10.Iflagscontains"u",letfullUnicodebetrue,elseletfullUnicodebefalse.
11.LetmatchSucceededbefalse.
12.Repeat,whilematchSucceededisfalse
a.IflastIndex>length,then
i.Perform?Set(R,"lastIndex",0,true).
ii.Returnnull.
b.Letrbematcher(S,lastIndex).
c.Ifrisfailure,then
i.Ifstickyistrue,then
1.Perform?Set(R,"lastIndex",0,true).
2.Returnnull.
ii.LetlastIndexbeAdvanceStringIndex(S,lastIndex,fullUnicode).
d.Else,
i.Assert:risaState.
ii.SetmatchSucceededtotrue.
13.Leteber'sendIndexvalue.
14.IffullUnicodeistrue,then
a.eisanindexintotheInputcharacterlist,derivedfromS,matchedbymatcher.LeteUTFbethesmallestindexintoS
thatcorrespondstothecharacteratelementeofInput.IfeisgreaterthanorequaltothelengthofInput,then
eUTFisthenumberofcodeunitsinS.
b.LetebeeUTF.
15.Ifglobalistrueorstickyistrue,then
a.Perform?Set(R,"lastIndex",e,true).
16.Letnbethelengthofr'scapturesList.(Thisisthesamevalueas21.2.2.1'sNcapturingParens.)
17.LetAbeArrayCreate(n+1).
18.Assert:ThevalueofA's"length"propertyisn+1.
19.LetmatchIndexbelastIndex.
20.Perform!CreateDataProperty(A,"index",matchIndex).
21.Perform!CreateDataProperty(A,"input",S).
22.LetmatchedSubstrbethematchedsubstring(i.e.theportionofSbetweenoffsetlastIndexinclusiveandoffsete
exclusive).
23.Perform!CreateDataProperty(A,"0",matchedSubstr).
24.Foreachintegerisuchthati>0andin
a.LetcaptureIbeithelementofr'scapturesList.
b.IfcaptureIisundeined,letcapturedValuebeundeined.
c.ElseiffullUnicodeistrue,then
i.Assert:captureIisaListofcodepoints.
ii.LetcapturedValuebeastringwhosecodeunitsaretheUTF16EncodingofthecodepointsofcaptureI.
d.Else,fullUnicodeisfalse,
i.Assert:captureIisaListofcodeunits.
ii.LetcapturedValuebeastringconsistingofthecodeunitsofcaptureI.
e.Perform!CreateDataProperty(A,!ToString(i),capturedValue).
25.ReturnA.

21.2.5.2.3 AdvanceStringIndex(S,index,unicode)

TheabstractoperationAdvanceStringIndexwithargumentsS,index,andunicodeperformsthefollowingsteps:

1.Assert:Type(S)isString.
2.Assert:indexisanintegersuchthat0index2531.
3.Assert:Type(unicode)isBoolean.
4.Ifunicodeisfalse,returnindex+1.
5.LetlengthbethenumberofcodeunitsinS.
6.Ifindex+1length,returnindex+1.
7.LetirstbethecodeunitvalueatindexindexinS.
8.Ifirst<0xD800orirst>0xDBFF,returnindex+1.
9.Letsecondbethecodeunitvalueatindexindex+1inS.
10.Ifsecond<0xDC00orsecond>0xDFFF,returnindex+1.
11.Returnindex+2.

21.2.5.3 getRegExp.prototype.lags

RegExp.prototype.flagsisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.LetresultbetheemptyString.
4.LetglobalbeToBoolean(?Get(R,"global")).
5.Ifglobalistrue,append"g"asthelastcodeunitofresult.
6.LetignoreCasebeToBoolean(?Get(R,"ignoreCase")).
7.IfignoreCaseistrue,append"i"asthelastcodeunitofresult.
8.LetmultilinebeToBoolean(?Get(R,"multiline")).
9.Ifmultilineistrue,append"m"asthelastcodeunitofresult.
10.LetunicodebeToBoolean(?Get(R,"unicode")).
11.Ifunicodeistrue,append"u"asthelastcodeunitofresult.
12.LetstickybeToBoolean(?Get(R,"sticky")).
13.Ifstickyistrue,append"y"asthelastcodeunitofresult.
14.Returnresult.

21.2.5.4 getRegExp.prototype.global

RegExp.prototype.globalisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.IfRdoesnothavean[[OriginalFlags]]internalslot,throwaTypeErrorexception.
4.LetlagsbethevalueofR's[[OriginalFlags]]internalslot.
5.Iflagscontainsthecodeunit"g",returntrue.
6.Returnfalse.

21.2.5.5 getRegExp.prototype.ignoreCase

RegExp.prototype.ignoreCaseisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.IfRdoesnothavean[[OriginalFlags]]internalslot,throwaTypeErrorexception.
4.LetlagsbethevalueofR's[[OriginalFlags]]internalslot.
5.Iflagscontainsthecodeunit"i",returntrue.
6.Returnfalse.

21.2.5.6 RegExp.prototype[@@match](string)

Whenthe@@matchmethodiscalledwithargumentstring,thefollowingstepsaretaken:

1.Letrxbethethisvalue.
2.IfType(rx)isnotObject,throwaTypeErrorexception.
3.LetSbe?ToString(string).
4.LetglobalbeToBoolean(?Get(rx,"global")).
5.Ifglobalisfalse,then
a.Return?RegExpExec(rx,S).
6.Elseglobalistrue,
a.LetfullUnicodebeToBoolean(?Get(rx,"unicode")).
b.Perform?Set(rx,"lastIndex",0,true).
c.LetAbeArrayCreate(0).
d.Letnbe0.
e.Repeat,
i.Letresultbe?RegExpExec(rx,S).
ii.Ifresultisnull,then
1.Ifn=0,returnnull.
2.Else,returnA.
iii.Elseresultisnotnull,
1.LetmatchStrbe?ToString(?Get(result,"0")).
2.LetstatusbeCreateDataProperty(A,!ToString(n),matchStr).
3.Assert:statusistrue.
4.IfmatchStristheemptyString,then
a.LetthisIndexbe?ToLength(?Get(rx,"lastIndex")).
b.LetnextIndexbeAdvanceStringIndex(S,thisIndex,fullUnicode).
c.Perform?Set(rx,"lastIndex",nextIndex,true).
5.Incrementn.

Thevalueofthenamepropertyofthisfunctionis"[Symbol.match]".

NOTE The@@matchpropertyisusedbytheIsRegExpabstractoperationtoidentifyobjectsthathavethebasic
behaviourofregularexpressions.Theabsenceofa@@matchpropertyortheexistenceofsuchaproperty
whosevaluedoesnotBooleancoercetotrueindicatesthattheobjectisnotintendedtobeusedasaregular
expressionobject.

21.2.5.7 getRegExp.prototype.multiline

RegExp.prototype.multilineisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.IfRdoesnothavean[[OriginalFlags]]internalslot,throwaTypeErrorexception.
4.LetlagsbethevalueofR's[[OriginalFlags]]internalslot.
5.Iflagscontainsthecodeunit"m",returntrue.
6.Returnfalse.

21.2.5.8 RegExp.prototype[@@replace](string,replaceValue)

Whenthe@@replacemethodiscalledwithargumentsstringandreplaceValue,thefollowingstepsaretaken:

1.Letrxbethethisvalue.
2.IfType(rx)isnotObject,throwaTypeErrorexception.
3.LetSbe?ToString(string).
4.LetlengthSbethenumberofcodeunitelementsinS.
5.LetfunctionalReplacebeIsCallable(replaceValue).
6.IffunctionalReplaceisfalse,then
a.LetreplaceValuebe?ToString(replaceValue).
7.LetglobalbeToBoolean(?Get(rx,"global")).
8.Ifglobalistrue,then
a.LetfullUnicodebeToBoolean(?Get(rx,"unicode")).
b.Perform?Set(rx,"lastIndex",0,true).
9.LetresultsbeanewemptyList.
10.Letdonebefalse.
11.Repeat,whiledoneisfalse
a.Letresultbe?RegExpExec(rx,S).
b.Ifresultisnull,setdonetotrue.
c.Elseresultisnotnull,
i.Appendresulttotheendofresults.
ii.Ifglobalisfalse,setdonetotrue.
iii.Else,
1.LetmatchStrbe?ToString(?Get(result,"0")).
2.IfmatchStristheemptyString,then
a.LetthisIndexbe?ToLength(?Get(rx,"lastIndex")).
b.LetnextIndexbeAdvanceStringIndex(S,thisIndex,fullUnicode).
c.Perform?Set(rx,"lastIndex",nextIndex,true).
12.LetaccumulatedResultbetheemptyStringvalue.
13.LetnextSourcePositionbe0.
14.Repeat,foreachresultinresults,
a.LetnCapturesbe?ToLength(?Get(result,"length")).
b.LetnCapturesbemax(nCaptures1,0).
c.Letmatchedbe?ToString(?Get(result,"0")).
d.LetmatchLengthbethenumberofcodeunitsinmatched.
e.Letpositionbe?ToInteger(?Get(result,"index")).
f.Letpositionbemax(min(position,lengthS),0).
g.Letnbe1.
h.LetcapturesbeanewemptyList.
i.RepeatwhilennCaptures
i.LetcapNbe?Get(result,!ToString(n)).
ii.IfcapNisnotundeined,then
1.LetcapNbe?ToString(capN).
iii.AppendcapNasthelastelementofcaptures.
iv.Letnben+1.
j.IffunctionalReplaceistrue,then
i.LetreplacerArgsbematched.
ii.AppendinlistordertheelementsofcapturestotheendoftheListreplacerArgs.
iii.AppendpositionandSasthelasttwoelementsofreplacerArgs.
iv.LetreplValuebe?Call(replaceValue,undeined,replacerArgs).
v.Letreplacementbe?ToString(replValue).
k.Else,
i.LetreplacementbeGetSubstitution(matched,S,position,captures,replaceValue).
l.IfpositionnextSourcePosition,then
i.NOTEpositionshouldnotnormallymovebackwards.Ifitdoes,itisanindicationofanillbehavingRegExp
subclassoruseofanaccesstriggeredsideeffecttochangethegloballagorothercharacteristicsofrx.In
suchcases,thecorrespondingsubstitutionisignored.
ii.LetaccumulatedResultbetheStringformedbyconcatenatingthecodeunitsofthecurrentvalueof
accumulatedResultwiththesubstringofSconsistingofthecodeunitsfromnextSourcePosition(inclusive)up
toposition(exclusive)andwiththecodeunitsofreplacement.
iii.LetnextSourcePositionbeposition+matchLength.
15.IfnextSourcePositionlengthS,returnaccumulatedResult.
16.ReturntheStringformedbyconcatenatingthecodeunitsofaccumulatedResultwiththesubstringofSconsistingofthe
codeunitsfromnextSourcePosition(inclusive)upthroughtheinalcodeunitofS(inclusive).

Thevalueofthenamepropertyofthisfunctionis"[Symbol.replace]".

21.2.5.9 RegExp.prototype[@@search](string)

Whenthe@@searchmethodiscalledwithargumentstring,thefollowingstepsaretaken:

1.Letrxbethethisvalue.
2.IfType(rx)isnotObject,throwaTypeErrorexception.
3.LetSbe?ToString(string).
4.LetpreviousLastIndexbe?Get(rx,"lastIndex").
5.Perform?Set(rx,"lastIndex",0,true).
6.Letresultbe?RegExpExec(rx,S).
7.Perform?Set(rx,"lastIndex",previousLastIndex,true).
8.Ifresultisnull,return1.
9.Return?Get(result,"index").

Thevalueofthenamepropertyofthisfunctionis"[Symbol.search]".

NOTE ThelastIndexandglobalpropertiesofthisRegExpobjectareignoredwhenperformingthesearch.The
lastIndexpropertyisleftunchanged.

21.2.5.10 getRegExp.prototype.source

RegExp.prototype.sourceisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.IfRdoesnothavean[[OriginalSource]]internalslot,throwaTypeErrorexception.
4.IfRdoesnothavean[[OriginalFlags]]internalslot,throwaTypeErrorexception.
5.LetsrcbethevalueofR's[[OriginalSource]]internalslot.
6.LetlagsbethevalueofR's[[OriginalFlags]]internalslot.
7.ReturnEscapeRegExpPattern(src,lags).

21.2.5.11 RegExp.prototype[@@split](string,limit)

NOTE1 ReturnsanArrayobjectintowhichsubstringsoftheresultofconvertingstringtoaStringhavebeenstored.
Thesubstringsaredeterminedbysearchingfromlefttorightformatchesofthethisvalueregularexpression;
theseoccurrencesarenotpartofanysubstringinthereturnedarray,butservetodivideuptheStringvalue.
ThethisvaluemaybeanemptyregularexpressionoraregularexpressionthatcanmatchanemptyString.In
thiscase,theregularexpressiondoesnotmatchtheemptysubstringatthebeginningorendoftheinput
String,nordoesitmatchtheemptysubstringattheendofthepreviousseparatormatch.(Forexample,ifthe
regularexpressionmatchestheemptyString,theStringissplitupintoindividualcodeunitelements;the
lengthoftheresultarrayequalsthelengthoftheString,andeachsubstringcontainsonecodeunit.)Onlythe
irstmatchatagivenindexoftheStringisconsidered,evenifbacktrackingcouldyieldanonemptysubstring
matchatthatindex.(Forexample,/a*?/[Symbol.split]("ab")evaluatestothearray["a","b"],while
/a*/[Symbol.split]("ab")evaluatestothearray["","b"].)

Ifthestringis(orconvertsto)theemptyString,theresultdependsonwhethertheregularexpressioncan
matchtheemptyString.Ifitcan,theresultarraycontainsnoelements.Otherwise,theresultarraycontains
oneelement,whichistheemptyString.

Iftheregularexpressioncontainscapturingparentheses,theneachtimeseparatorismatchedtheresults
(includinganyundeinedresults)ofthecapturingparenthesesaresplicedintotheoutputarray.Forexample,

/<(\/)?([^<>]+)>/[Symbol.split]("A<B>bold</B>and<CODE>coded</CODE>")

evaluatestothearray

["A",undefined,"B","bold","/","B","and",undefined,"CODE","coded","/","CODE",""]

Iflimitisnotundeined,thentheoutputarrayistruncatedsothatitcontainsnomorethanlimitelements.

Whenthe@@splitmethodiscalled,thefollowingstepsaretaken:

1.Letrxbethethisvalue.
2.IfType(rx)isnotObject,throwaTypeErrorexception.
3.LetSbe?ToString(string).
4.LetCbe?SpeciesConstructor(rx,%RegExp%).
5.Letlagsbe?ToString(?Get(rx,"flags")).
6.Iflagscontains"u",letunicodeMatchingbetrue.
7.Else,letunicodeMatchingbefalse.
8.Iflagscontains"y",letnewFlagsbelags.
9.Else,letnewFlagsbethestringthatistheconcatenationoflagsand"y".
10.Letsplitterbe?Construct(C,rx,newFlags).
11.LetAbeArrayCreate(0).
12.LetlengthAbe0.
13.Iflimitisundeined,letlimbe2321;elseletlimbe?ToUint32(limit).
14.LetsizebethenumberofelementsinS.
15.Letpbe0.
16.Iflim=0,returnA.
17.Ifsize=0,then
a.Letzbe?RegExpExec(splitter,S).
b.Ifzisnotnull,returnA.
c.Perform!CreateDataProperty(A,"0",S).
d.ReturnA.
18.Letqbep.
19.Repeat,whileq<size
a.Perform?Set(splitter,"lastIndex",q,true).
b.Letzbe?RegExpExec(splitter,S).
c.Ifzisnull,letqbeAdvanceStringIndex(S,q,unicodeMatching).
d.Elsezisnotnull,
i.Letebe?ToLength(?Get(splitter,"lastIndex")).
ii.Letebemin(e,size).
iii.Ife=p,letqbeAdvanceStringIndex(S,q,unicodeMatching).
iv.Elseep,
1.LetTbeaStringvalueequaltothesubstringofSconsistingoftheelementsatindicesp(inclusive)
throughq(exclusive).
2.Perform!CreateDataProperty(A,!ToString(lengthA),T).
3.LetlengthAbelengthA+1.
4.IflengthA=lim,returnA.
5.Letpbee.
6.LetnumberOfCapturesbe?ToLength(?Get(z,"length")).
7.LetnumberOfCapturesbemax(numberOfCaptures1,0).
8.Letibe1.
9.Repeat,whileinumberOfCaptures,
a.LetnextCapturebe?Get(z,!ToString(i)).
b.Perform!CreateDataProperty(A,!ToString(lengthA),nextCapture).
c.Letibei+1.
d.LetlengthAbelengthA+1.
e.IflengthA=lim,returnA.
10.Letqbep.
20.LetTbeaStringvalueequaltothesubstringofSconsistingoftheelementsatindicesp(inclusive)throughsize
(exclusive).
21.Perform!CreateDataProperty(A,!ToString(lengthA),T).
22.ReturnA.

Thevalueofthenamepropertyofthisfunctionis"[Symbol.split]".

NOTE2 The@@splitmethodignoresthevalueoftheglobalandstickypropertiesofthisRegExpobject.

21.2.5.12 getRegExp.prototype.sticky

RegExp.prototype.stickyisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.IfRdoesnothavean[[OriginalFlags]]internalslot,throwaTypeErrorexception.
4.LetlagsbethevalueofR's[[OriginalFlags]]internalslot.
5.Iflagscontainsthecodeunit"y",returntrue.
6.Returnfalse.

21.2.5.13 RegExp.prototype.test(S)

Thefollowingstepsaretaken:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.Letstringbe?ToString(S).
4.Letmatchbe?RegExpExec(R,string).
5.Ifmatchisnotnull,returntrue;elsereturnfalse.

21.2.5.14 RegExp.prototype.toString()

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.Letpatternbe?ToString(?Get(R,"source")).
4.Letlagsbe?ToString(?Get(R,"flags")).
5.LetresultbetheStringvalueformedbyconcatenating"/",pattern,"/",andlags.
6.Returnresult.
NOTE ThereturnedStringhastheformofaRegularExpressionLiteralthatevaluatestoanotherRegExpobjectwith
thesamebehaviourasthisobject.

21.2.5.15 getRegExp.prototype.unicode

RegExp.prototype.unicodeisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.LetRbethethisvalue.
2.IfType(R)isnotObject,throwaTypeErrorexception.
3.IfRdoesnothavean[[OriginalFlags]]internalslot,throwaTypeErrorexception.
4.LetlagsbethevalueofR's[[OriginalFlags]]internalslot.
5.Iflagscontainsthecodeunit"u",returntrue.
6.Returnfalse.

21.2.6 PropertiesofRegExpInstances

RegExpinstancesareordinaryobjectsthatinheritpropertiesfromtheRegExpprototypeobject.RegExpinstanceshave
internalslots[[RegExpMatcher]],[[OriginalSource]],and[[OriginalFlags]].Thevalueofthe[[RegExpMatcher]]internalslot
isanimplementationdependentrepresentationofthePatternoftheRegExpobject.

NOTE PriortoECMAScript2015,RegExpinstanceswerespeciiedashavingtheowndatapropertiessource,
global,ignoreCase,andmultiline.Thosepropertiesarenowspeciiedasaccessorpropertiesof
RegExp.prototype.

RegExpinstancesalsohavethefollowingproperty:

21.2.6.1 lastIndex

ThevalueofthelastIndexpropertyspeciiestheStringindexatwhichtostartthenextmatch.Itiscoercedtoaninteger
whenused(see21.2.5.2.2).Thispropertyshallhavetheattributes{[[Writable]]:true,[[Enumerable]]:false,
[[Conigurable]]:false}.

22 IndexedCollections
22.1 ArrayObjects
Arrayobjectsareexoticobjectsthatgivespecialtreatmenttoacertainclassofpropertynames.See9.4.2foradeinitionof
thisspecialtreatment.

22.1.1 TheArrayConstructor

TheArrayconstructoristhe%Array%intrinsicobjectandtheinitialvalueoftheArraypropertyoftheglobalobject.When
calledasaconstructoritcreatesandinitializesanewexoticArrayobject.WhenArrayiscalledasafunctionratherthanasa
constructor,italsocreatesandinitializesanewArrayobject.ThusthefunctioncallArray()isequivalenttotheobject
creationexpressionnewArray()withthesamearguments.

TheArrayconstructorisasinglefunctionwhosebehaviourisoverloadedbaseduponthenumberandtypesofits
arguments.

TheArrayconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinherittheexoticArraybehaviourmustincludeasupercalltotheArrayconstructor
toinitializesubclassinstancesthatareexoticArrayobjects.However,mostoftheArray.prototypemethodsaregeneric
methodsthatarenotdependentupontheirthisvaluebeinganexoticArrayobject.

ThelengthpropertyoftheArrayconstructorfunctionis1.
22.1.1.1 Array()

ThisdescriptionappliesifandonlyiftheArrayconstructoriscalledwithnoarguments.

1.LetnumberOfArgsbethenumberofargumentspassedtothisfunctioncall.
2.Assert:numberOfArgs=0.
3.IfNewTargetisundeined,letnewTargetbetheactivefunctionobject,elseletnewTargetbeNewTarget.
4.Letprotobe?GetPrototypeFromConstructor(newTarget,"%ArrayPrototype%").
5.ReturnArrayCreate(0,proto).

22.1.1.2 Array(len)

ThisdescriptionappliesifandonlyiftheArrayconstructoriscalledwithexactlyoneargument.

1.LetnumberOfArgsbethenumberofargumentspassedtothisfunctioncall.
2.Assert:numberOfArgs=1.
3.IfNewTargetisundeined,letnewTargetbetheactivefunctionobject,elseletnewTargetbeNewTarget.
4.Letprotobe?GetPrototypeFromConstructor(newTarget,"%ArrayPrototype%").
5.LetarraybeArrayCreate(0,proto).
6.IfType(len)isnotNumber,then
a.LetdeineStatusbeCreateDataProperty(array,"0",len).
b.Assert:deineStatusistrue.
c.LetintLenbe1.
7.Else,
a.LetintLenbeToUint32(len).
b.IfintLenlen,throwaRangeErrorexception.
8.Perform!Set(array,"length",intLen,true).
9.Returnarray.

22.1.1.3 Array(...items)

ThisdescriptionappliesifandonlyiftheArrayconstructoriscalledwithatleasttwoarguments.

WhentheArrayfunctioniscalled,thefollowingstepsaretaken:

1.LetnumberOfArgsbethenumberofargumentspassedtothisfunctioncall.
2.Assert:numberOfArgs2.
3.IfNewTargetisundeined,letnewTargetbetheactivefunctionobject,elseletnewTargetbeNewTarget.
4.Letprotobe?GetPrototypeFromConstructor(newTarget,"%ArrayPrototype%").
5.Letarraybe?ArrayCreate(numberOfArgs,proto).
6.Letkbe0.
7.LetitemsbeazerooriginedListcontainingtheargumentitemsinorder.
8.Repeat,whilek<numberOfArgs
a.LetPkbe!ToString(k).
b.LetitemKbeitems[k].
c.LetdeineStatusbeCreateDataProperty(array,Pk,itemK).
d.Assert:deineStatusistrue.
e.Increasekby1.
9.Assert:thevalueofarray'slengthpropertyisnumberOfArgs.
10.Returnarray.

22.1.2 PropertiesoftheArrayConstructor

Thevalueofthe[[Prototype]]internalslotoftheArrayconstructoristheintrinsicobject%FunctionPrototype%.

TheArrayconstructorhasthefollowingproperties:
22.1.2.1 Array.from(items[,mapfn[,thisArg]])

WhenthefrommethodiscalledwithargumentitemsandoptionalargumentsmapfnandthisArg,thefollowingstepsare
taken:

1.LetCbethethisvalue.
2.Ifmapfnisundeined,letmappingbefalse.
3.Else,
a.IfIsCallable(mapfn)isfalse,throwaTypeErrorexception.
b.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
c.Letmappingbetrue.
4.LetusingIteratorbe?GetMethod(items,@@iterator).
5.IfusingIteratorisnotundeined,then
a.IfIsConstructor(C)istrue,then
i.LetAbe?Construct(C).
b.Else,
i.LetAbeArrayCreate(0).
c.Letiteratorbe?GetIterator(items,usingIterator).
d.Letkbe0.
e.Repeat
i.Ifk2531,then
1.LeterrorbeCompletion{[[Type]]:throw,[[Value]]:anewlycreatedTypeErrorobject,[[Target]]:
empty}.
2.Return?IteratorClose(iterator,error).
ii.LetPkbe!ToString(k).
iii.Letnextbe?IteratorStep(iterator).
iv.Ifnextisfalse,then
1.Perform?Set(A,"length",k,true).
2.ReturnA.
v.LetnextValuebe?IteratorValue(next).
vi.Ifmappingistrue,then
1.LetmappedValuebeCall(mapfn,T,nextValue,k).
2.IfmappedValueisanabruptcompletion,return?IteratorClose(iterator,mappedValue).
3.LetmappedValuebemappedValue.[[Value]].
vii.Else,letmappedValuebenextValue.
viii.LetdeineStatusbeCreateDataPropertyOrThrow(A,Pk,mappedValue).
ix.IfdeineStatusisanabruptcompletion,return?IteratorClose(iterator,deineStatus).
x.Increasekby1.
6.NOTE:itemsisnotanIterablesoassumeitisanarraylikeobject.
7.LetarrayLikebe!ToObject(items).
8.Letlenbe?ToLength(?Get(arrayLike,"length")).
9.IfIsConstructor(C)istrue,then
a.LetAbe?Construct(C,len).
10.Else,
a.LetAbe?ArrayCreate(len).
11.Letkbe0.
12.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkValuebe?Get(arrayLike,Pk).
c.Ifmappingistrue,then
i.LetmappedValuebe?Call(mapfn,T,kValue,k).
d.Else,letmappedValuebekValue.
e.Perform?CreateDataPropertyOrThrow(A,Pk,mappedValue).
f.Increasekby1.
13.Perform?Set(A,"length",len,true).
14.ReturnA.

NOTE Thefromfunctionisanintentionallygenericfactorymethod;itdoesnotrequirethatitsthisvaluebethe
Arrayconstructor.Thereforeitcanbetransferredtoorinheritedbyanyotherconstructorsthatmaybecalled
withasinglenumericargument.

22.1.2.2 Array.isArray(arg)

TheisArrayfunctiontakesoneargumentarg,andperformsthefollowingsteps:

1.Return?IsArray(arg).

22.1.2.3 Array.of(...items)

Whentheofmethodiscalledwithanynumberofarguments,thefollowingstepsaretaken:

1.Letlenbetheactualnumberofargumentspassedtothisfunction.
2.LetitemsbetheListofargumentspassedtothisfunction.
3.LetCbethethisvalue.
4.IfIsConstructor(C)istrue,then
a.LetAbe?Construct(C,len).
5.Else,
a.LetAbe?ArrayCreate(len).
6.Letkbe0.
7.Repeat,whilek<len
a.LetkValuebeitems[k].
b.LetPkbe!ToString(k).
c.Perform?CreateDataPropertyOrThrow(A,Pk,kValue).
d.Increasekby1.
8.Perform?Set(A,"length",len,true).
9.ReturnA.

NOTE1 Theitemsargumentisassumedtobeawellformedrestargumentvalue.

NOTE2 Theoffunctionisanintentionallygenericfactorymethod;itdoesnotrequirethatitsthisvaluebetheArray
constructor.Thereforeitcanbetransferredtoorinheritedbyotherconstructorsthatmaybecalledwitha
singlenumericargument.

22.1.2.4 Array.prototype

ThevalueofArray.prototypeis%ArrayPrototype%,theintrinsicArrayprototypeobject.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

22.1.2.5 getArray[@@species]

Array[@@species]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunctionperforms
thefollowingsteps:

1.Returnthethisvalue.

Thevalueofthenamepropertyofthisfunctionis"get[Symbol.species]".

NOTE Arrayprototypemethodsnormallyusetheirthisobject'sconstructortocreateaderivedobject.However,a
subclassconstructormayoverridethatdefaultbehaviourbyredeiningits@@speciesproperty.

22.1.3 PropertiesoftheArrayPrototypeObject
TheArrayprototypeobjectistheintrinsicobject%ArrayPrototype%.TheArrayprototypeobjectisanArrayexoticobjects
andhastheinternalmethodsspeciiedforsuchobjects.Ithasalengthpropertywhoseinitialvalueis0andwhose
attributesare{[[Writable]]:true,[[Enumerable]]:false,[[Conigurable]]:false}.

Thevalueofthe[[Prototype]]internalslotoftheArrayprototypeobjectistheintrinsicobject%ObjectPrototype%.

NOTE TheArrayprototypeobjectisspeciiedtobeanArrayexoticobjecttoensurecompatibilitywithECMAScript
codethatwascreatedpriortotheECMAScript2015speciication.

22.1.3.1 Array.prototype.concat(...arguments)

Whentheconcatmethodiscalledwithzeroormorearguments,itreturnsanarraycontainingthearrayelementsofthe
objectfollowedbythearrayelementsofeachargumentinorder.

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.LetAbe?ArraySpeciesCreate(O,0).
3.Letnbe0.
4.LetitemsbeaListwhoseirstelementisOandwhosesubsequentelementsare,inlefttorightorder,theargumentsthat
werepassedtothisfunctioninvocation.
5.Repeat,whileitemsisnotempty
a.RemovetheirstelementfromitemsandletEbethevalueoftheelement.
b.Letspreadablebe?IsConcatSpreadable(E).
c.Ifspreadableistrue,then
i.Letkbe0.
ii.Letlenbe?ToLength(?Get(E,"length")).
iii.Ifn+len>2531,throwaTypeErrorexception.
iv.Repeat,whilek<len
1.LetPbe!ToString(k).
2.Letexistsbe?HasProperty(E,P).
3.Ifexistsistrue,then
a.LetsubElementbe?Get(E,P).
b.Perform?CreateDataPropertyOrThrow(A,!ToString(n),subElement).
4.Increasenby1.
5.Increasekby1.
d.ElseEisaddedasasingleitemratherthanspread,
i.Ifn2531,throwaTypeErrorexception.
ii.Perform?CreateDataPropertyOrThrow(A,!ToString(n),E).
iii.Increasenby1.
6.Perform?Set(A,"length",n,true).
7.ReturnA.

Thelengthpropertyoftheconcatmethodis1.

NOTE1 Theexplicitsettingofthelengthpropertyinstep6isnecessarytoensurethatitsvalueiscorrectinsituations
wherethetrailingelementsoftheresultArrayarenotpresent.

NOTE2 Theconcatfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.1.1 RuntimeSemantics:IsConcatSpreadable(O)

TheabstractoperationIsConcatSpreadablewithargumentOperformsthefollowingsteps:

1.IfType(O)isnotObject,returnfalse.
2.Letspreadablebe?Get(O,@@isConcatSpreadable).
3.Ifspreadableisnotundeined,returnToBoolean(spreadable).
4.Return?IsArray(O).

22.1.3.2 Array.prototype.constructor

TheinitialvalueofArray.prototype.constructoristheintrinsicobject%Array%.

22.1.3.3 Array.prototype.copyWithin(target,start[,end])

ThecopyWithinmethodtakesuptothreeargumentstarget,startandend.

NOTE1 Theendargumentisoptionalwiththelengthofthethisobjectasitsdefaultvalue.Iftargetisnegative,itis
treatedaslength+targetwherelengthisthelengthofthearray.Ifstartisnegative,itistreatedaslength+start.
Ifendisnegative,itistreatedaslength+end.

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.LetrelativeTargetbe?ToInteger(target).
4.IfrelativeTarget<0,lettobemax((len+relativeTarget),0);elselettobemin(relativeTarget,len).
5.LetrelativeStartbe?ToInteger(start).
6.IfrelativeStart<0,letfrombemax((len+relativeStart),0);elseletfrombemin(relativeStart,len).
7.Ifendisundeined,letrelativeEndbelen;elseletrelativeEndbe?ToInteger(end).
8.IfrelativeEnd<0,letinalbemax((len+relativeEnd),0);elseletinalbemin(relativeEnd,len).
9.Letcountbemin(inalfrom,lento).
10.Iffrom<toandto<from+count,then
a.Letdirectionbe1.
b.Letfrombefrom+count1.
c.Lettobeto+count1.
11.Else,
a.Letdirectionbe1.
12.Repeat,whilecount>0
a.LetfromKeybe!ToString(from).
b.LettoKeybe!ToString(to).
c.LetfromPresentbe?HasProperty(O,fromKey).
d.IffromPresentistrue,then
i.LetfromValbe?Get(O,fromKey).
ii.Perform?Set(O,toKey,fromVal,true).
e.ElsefromPresentisfalse,
i.Perform?DeletePropertyOrThrow(O,toKey).
f.Letfrombefrom+direction.
g.Lettobeto+direction.
h.Letcountbecount1.
13.ReturnO.

NOTE2 ThecopyWithinfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.4 Array.prototype.entries()

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.ReturnCreateArrayIterator(O,"key+value").

22.1.3.5 Array.prototype.every(callbackfn[,thisArg])
NOTE1 callbackfnshouldbeafunctionthatacceptsthreeargumentsandreturnsavaluethatiscoercibletothe
Booleanvaluetrueorfalse.everycallscallbackfnonceforeachelementpresentinthearray,inascending
order,untilitindsonewherecallbackfnreturnsfalse.Ifsuchanelementisfound,everyimmediatelyreturns
false.Otherwise,ifcallbackfnreturnedtrueforallelements,everywillreturntrue.callbackfniscalledonly
forelementsofthearraywhichactuallyexist;itisnotcalledformissingelementsofthearray.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofcallbackfn.Ifitisnot
provided,undeinedisusedinstead.

callbackfniscalledwiththreearguments:thevalueoftheelement,theindexoftheelement,andtheobject
beingtraversed.

everydoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.

Therangeofelementsprocessedbyeveryissetbeforetheirstcalltocallbackfn.Elementswhichare
appendedtothearrayafterthecalltoeverybeginswillnotbevisitedbycallbackfn.Ifexistingelementsofthe
arrayarechanged,theirvalueaspassedtocallbackfnwillbethevalueatthetimeeveryvisitsthem;elements
thataredeletedafterthecalltoeverybeginsandbeforebeingvisitedarenotvisited.everyactslikethe"for
all"quantiierinmathematics.Inparticular,foranemptyarray,itreturnstrue.

Whentheeverymethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
4.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
5.Letkbe0.
6.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.LettestResultbeToBoolean(?Call(callbackfn,T,kValue,k,O)).
iii.IftestResultisfalse,returnfalse.
d.Increasekby1.
7.Returntrue.

NOTE2 Theeveryfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.6 Array.prototype.ill(value[,start[,end]])

Thefillmethodtakesuptothreeargumentsvalue,startandend.

NOTE1 Thestartandendargumentsareoptionalwithdefaultvaluesof0andthelengthofthethisobject.Ifstartis
negative,itistreatedaslength+startwherelengthisthelengthofthearray.Ifendisnegative,itistreatedas
length+end.

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.LetrelativeStartbe?ToInteger(start).
4.IfrelativeStart<0,letkbemax((len+relativeStart),0);elseletkbemin(relativeStart,len).
5.Ifendisundeined,letrelativeEndbelen;elseletrelativeEndbe?ToInteger(end).
6.IfrelativeEnd<0,letinalbemax((len+relativeEnd),0);elseletinalbemin(relativeEnd,len).
7.Repeat,whilek<inal
a.LetPkbe!ToString(k).
b.Perform?Set(O,Pk,value,true).
c.Increasekby1.
8.ReturnO.

NOTE2 Thefillfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.7 Array.prototype.ilter(callbackfn[,thisArg])

NOTE1 callbackfnshouldbeafunctionthatacceptsthreeargumentsandreturnsavaluethatiscoercibletothe
Booleanvaluetrueorfalse.filtercallscallbackfnonceforeachelementinthearray,inascendingorder,and
constructsanewarrayofallthevaluesforwhichcallbackfnreturnstrue.callbackfniscalledonlyforelements
ofthearraywhichactuallyexist;itisnotcalledformissingelementsofthearray.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofcallbackfn.Ifitisnot
provided,undeinedisusedinstead.

callbackfniscalledwiththreearguments:thevalueoftheelement,theindexoftheelement,andtheobject
beingtraversed.

filterdoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.

Therangeofelementsprocessedbyfilterissetbeforetheirstcalltocallbackfn.Elementswhichare
appendedtothearrayafterthecalltofilterbeginswillnotbevisitedbycallbackfn.Ifexistingelementsof
thearrayarechangedtheirvalueaspassedtocallbackfnwillbethevalueatthetimefiltervisitsthem;
elementsthataredeletedafterthecalltofilterbeginsandbeforebeingvisitedarenotvisited.

Whenthefiltermethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
4.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
5.LetAbe?ArraySpeciesCreate(O,0).
6.Letkbe0.
7.Lettobe0.
8.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.LetselectedbeToBoolean(?Call(callbackfn,T,kValue,k,O)).
iii.Ifselectedistrue,then
1.Perform?CreateDataPropertyOrThrow(A,!ToString(to),kValue).
2.Increasetoby1.
d.Increasekby1.
9.ReturnA.

NOTE2 Thefilterfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.8 Array.prototype.ind(predicate[,thisArg])

Thefindmethodiscalledwithoneortwoarguments,predicateandthisArg.
NOTE1 predicateshouldbeafunctionthatacceptsthreeargumentsandreturnsavaluethatiscoercibletoaBoolean
value.findcallspredicateonceforeachelementofthearray,inascendingorder,untilitindsonewhere
predicatereturnstrue.Ifsuchanelementisfound,findimmediatelyreturnsthatelementvalue.Otherwise,
findreturnsundeined.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofpredicate.Ifitisnot
provided,undeinedisusedinstead.

predicateiscalledwiththreearguments:thevalueoftheelement,theindexoftheelement,andtheobject
beingtraversed.

finddoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
predicate.

Therangeofelementsprocessedbyfindissetbeforetheirstcalltocallbackfn.Elementsthatareappended
tothearrayafterthecalltofindbeginswillnotbevisitedbycallbackfn.Ifexistingelementsofthearrayare
changed,theirvalueaspassedtopredicatewillbethevalueatthetimethatfindvisitsthem.

Whenthefindmethodiscalled,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(predicate)isfalse,throwaTypeErrorexception.
4.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
5.Letkbe0.
6.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkValuebe?Get(O,Pk).
c.LettestResultbeToBoolean(?Call(predicate,T,kValue,k,O)).
d.IftestResultistrue,returnkValue.
e.Increasekby1.
7.Returnundeined.

NOTE2 Thefindfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.9 Array.prototype.indIndex(predicate[,thisArg])

NOTE1 predicateshouldbeafunctionthatacceptsthreeargumentsandreturnsavaluethatiscoercibletotheBoolean
valuetrueorfalse.findIndexcallspredicateonceforeachelementofthearray,inascendingorder,untilit
indsonewherepredicatereturnstrue.Ifsuchanelementisfound,findIndeximmediatelyreturnstheindex
ofthatelementvalue.Otherwise,findIndexreturns1.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofpredicate.Ifitisnot
provided,undeinedisusedinstead.

predicateiscalledwiththreearguments:thevalueoftheelement,theindexoftheelement,andtheobject
beingtraversed.

findIndexdoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecalls
topredicate.

TherangeofelementsprocessedbyfindIndexissetbeforetheirstcalltocallbackfn.Elementsthatare
appendedtothearrayafterthecalltofindIndexbeginswillnotbevisitedbycallbackfn.Ifexistingelements
ofthearrayarechanged,theirvalueaspassedtopredicatewillbethevalueatthetimethatfindIndexvisits
them.

WhenthefindIndexmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:
1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(predicate)isfalse,throwaTypeErrorexception.
4.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
5.Letkbe0.
6.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkValuebe?Get(O,Pk).
c.LettestResultbeToBoolean(?Call(predicate,T,kValue,k,O)).
d.IftestResultistrue,returnk.
e.Increasekby1.
7.Return1.

NOTE2 ThefindIndexfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.10 Array.prototype.forEach(callbackfn[,thisArg])

NOTE1 callbackfnshouldbeafunctionthatacceptsthreearguments.forEachcallscallbackfnonceforeachelement
presentinthearray,inascendingorder.callbackfniscalledonlyforelementsofthearraywhichactuallyexist;
itisnotcalledformissingelementsofthearray.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofcallbackfn.Ifitisnot
provided,undeinedisusedinstead.

callbackfniscalledwiththreearguments:thevalueoftheelement,theindexoftheelement,andtheobject
beingtraversed.

forEachdoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.

WhentheforEachmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
4.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
5.Letkbe0.
6.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.Perform?Call(callbackfn,T,kValue,k,O).
d.Increasekby1.
7.Returnundeined.

NOTE2 TheforEachfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.11 Array.prototype.includes(searchElement[,fromIndex])

NOTE1 includescomparessearchElementtotheelementsofthearray,inascendingorder,usingtheSameValueZero
algorithm,andiffoundatanyposition,returnstrue;otherwise,falseisreturned.

TheoptionalsecondargumentfromIndexdefaultsto0(i.e.thewholearrayissearched).Ifitisgreaterthanor
equaltothelengthofthearray,falseisreturned,i.e.thearraywillnotbesearched.Ifitisnegative,itisusedas
theoffsetfromtheendofthearraytocomputefromIndex.Ifthecomputedindexislessthan0,thewholearray
willbesearched.

Whentheincludesmethodiscalled,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.Iflenis0,returnfalse.
4.Letnbe?ToInteger(fromIndex).(IffromIndexisundeined,thisstepproducesthevalue0.)
5.Ifn0,then
a.Letkben.
6.Elsen<0,
a.Letkbelen+n.
b.Ifk<0,letkbe0.
7.Repeat,whilek<len
a.LetelementKbetheresultof?Get(O,!ToString(k)).
b.IfSameValueZero(searchElement,elementK)istrue,returntrue.
c.Increasekby1.
8.Returnfalse.

NOTE2 Theincludesfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

NOTE3 TheincludesmethodintentionallydiffersfromthesimilarindexOfmethodintwoways.First,itusesthe
SameValueZeroalgorithm,insteadofStrictEqualityComparison,allowingittodetectNaNarrayelements.
Second,itdoesnotskipmissingarrayelements,insteadtreatingthemasundeined.

22.1.3.12 Array.prototype.indexOf(searchElement[,fromIndex])

NOTE1 indexOfcomparessearchElementtotheelementsofthearray,inascendingorder,usingtheStrictEquality
Comparisonalgorithm,andiffoundatoneormoreindices,returnsthesmallestsuchindex;otherwise,1is
returned.

TheoptionalsecondargumentfromIndexdefaultsto0(i.e.thewholearrayissearched).Ifitisgreaterthanor
equaltothelengthofthearray,1isreturned,i.e.thearraywillnotbesearched.Ifitisnegative,itisusedas
theoffsetfromtheendofthearraytocomputefromIndex.Ifthecomputedindexislessthan0,thewholearray
willbesearched.

WhentheindexOfmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.Iflenis0,return1.
4.Letnbe?ToInteger(fromIndex).(IffromIndexisundeined,thisstepproducesthevalue0.)
5.Ifnlen,return1.
6.Ifn0,then
a.Ifnis0,letkbe+0;elseletkben.
7.Elsen<0,
a.Letkbelen+n.
b.Ifk<0,letkbe0.
8.Repeat,whilek<len
a.LetkPresentbe?HasProperty(O,!ToString(k)).
b.IfkPresentistrue,then
i.LetelementKbe?Get(O,!ToString(k)).
ii.LetsamebetheresultofperformingStrictEqualityComparisonsearchElement===elementK.
iii.Ifsameistrue,returnk.
c.Increasekby1.
9.Return1.

NOTE2 TheindexOffunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.13 Array.prototype.join(separator)

NOTE1 TheelementsofthearrayareconvertedtoStrings,andtheseStringsarethenconcatenated,separatedby
occurrencesoftheseparator.Ifnoseparatorisprovided,asinglecommaisusedastheseparator.

Thejoinmethodtakesoneargument,separator,andperformsthefollowingsteps:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.Ifseparatorisundeined,letseparatorbethesingleelementString",".
4.Letsepbe?ToString(separator).
5.Ifleniszero,returntheemptyString.
6.Letelement0beGet(O,"0").
7.Ifelement0isundeinedornull,letRbetheemptyString;otherwise,letRbe?ToString(element0).
8.Letkbe1.
9.Repeat,whilek<len
a.LetSbetheStringvalueproducedbyconcatenatingRandsep.
b.Letelementbe?Get(O,!ToString(k)).
c.Ifelementisundeinedornull,letnextbetheemptyString;otherwise,letnextbe?ToString(element).
d.LetRbeaStringvalueproducedbyconcatenatingSandnext.
e.Increasekby1.
10.ReturnR.

NOTE2 Thejoinfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore,
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.14 Array.prototype.keys()

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.ReturnCreateArrayIterator(O,"key").

22.1.3.15 Array.prototype.lastIndexOf(searchElement[,fromIndex])

NOTE1 lastIndexOfcomparessearchElementtotheelementsofthearrayindescendingorderusingtheStrict
EqualityComparisonalgorithm,andiffoundatoneormoreindices,returnsthelargestsuchindex;otherwise,
1isreturned.

TheoptionalsecondargumentfromIndexdefaultstothearray'slengthminusone(i.e.thewholearrayis
searched).Ifitisgreaterthanorequaltothelengthofthearray,thewholearraywillbesearched.Ifitis
negative,itisusedastheoffsetfromtheendofthearraytocomputefromIndex.Ifthecomputedindexisless
than0,1isreturned.

WhenthelastIndexOfmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.Iflenis0,return1.
4.IfargumentfromIndexwaspassed,letnbe?ToInteger(fromIndex);elseletnbelen1.
5.Ifn0,then
a.Ifnis0,letkbe+0;elseletkbemin(n,len1).
6.Elsen<0,
a.Letkbelen+n.
7.Repeat,whilek0
a.LetkPresentbe?HasProperty(O,!ToString(k)).
b.IfkPresentistrue,then
i.LetelementKbe?Get(O,!ToString(k)).
ii.LetsamebetheresultofperformingStrictEqualityComparisonsearchElement===elementK.
iii.Ifsameistrue,returnk.
c.Decreasekby1.
8.Return1.

NOTE2 ThelastIndexOffunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.16 Array.prototype.map(callbackfn[,thisArg])

NOTE1 callbackfnshouldbeafunctionthatacceptsthreearguments.mapcallscallbackfnonceforeachelementinthe
array,inascendingorder,andconstructsanewArrayfromtheresults.callbackfniscalledonlyforelementsof
thearraywhichactuallyexist;itisnotcalledformissingelementsofthearray.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofcallbackfn.Ifitisnot
provided,undeinedisusedinstead.

callbackfniscalledwiththreearguments:thevalueoftheelement,theindexoftheelement,andtheobject
beingtraversed.

mapdoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.

Therangeofelementsprocessedbymapissetbeforetheirstcalltocallbackfn.Elementswhichareappended
tothearrayafterthecalltomapbeginswillnotbevisitedbycallbackfn.Ifexistingelementsofthearrayare
changed,theirvalueaspassedtocallbackfnwillbethevalueatthetimemapvisitsthem;elementsthatare
deletedafterthecalltomapbeginsandbeforebeingvisitedarenotvisited.

Whenthemapmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
4.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
5.LetAbe?ArraySpeciesCreate(O,len).
6.Letkbe0.
7.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.LetmappedValuebe?Call(callbackfn,T,kValue,k,O).
iii.Perform?CreateDataPropertyOrThrow(A,Pk,mappedValue).
d.Increasekby1.
8.ReturnA.

NOTE2 Themapfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Thereforeit
canbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.17 Array.prototype.pop()

NOTE1 Thelastelementofthearrayisremovedfromthearrayandreturned.
Whenthepopmethodiscalled,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.Ifleniszero,then
a.Perform?Set(O,"length",0,true).
b.Returnundeined.
4.Elselen>0,
a.LetnewLenbelen1.
b.Letindxbe!ToString(newLen).
c.Letelementbe?Get(O,indx).
d.Perform?DeletePropertyOrThrow(O,indx).
e.Perform?Set(O,"length",newLen,true).
f.Returnelement.

NOTE2 Thepopfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Thereforeit
canbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.18 Array.prototype.push(...items)

NOTE1 Theargumentsareappendedtotheendofthearray,intheorderinwhichtheyappear.Thenewlengthofthe
arrayisreturnedastheresultofthecall.

Whenthepushmethodiscalledwithzeroormorearguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.LetitemsbeaListwhoseelementsare,inlefttorightorder,theargumentsthatwerepassedtothisfunctioninvocation.
4.LetargCountbethenumberofelementsinitems.
5.Iflen+argCount>2531,throwaTypeErrorexception.
6.Repeat,whileitemsisnotempty
a.RemovetheirstelementfromitemsandletEbethevalueoftheelement.
b.Perform?Set(O,!ToString(len),E,true).
c.Letlenbelen+1.
7.Perform?Set(O,"length",len,true).
8.Returnlen.

Thelengthpropertyofthepushmethodis1.

NOTE2 Thepushfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.19 Array.prototype.reduce(callbackfn[,initialValue])

NOTE1 callbackfnshouldbeafunctionthattakesfourarguments.reducecallsthecallback,asafunction,oncefor
eachelementpresentinthearray,inascendingorder.

callbackfniscalledwithfourarguments:thepreviousValue(valuefromthepreviouscalltocallbackfn),the
currentValue(valueofthecurrentelement),thecurrentIndex,andtheobjectbeingtraversed.Theirsttime
thatcallbackiscalled,thepreviousValueandcurrentValuecanbeoneoftwovalues.IfaninitialValuewas
providedinthecalltoreduce,thenpreviousValuewillbeequaltoinitialValueandcurrentValuewillbeequalto
theirstvalueinthearray.IfnoinitialValuewasprovided,thenpreviousValuewillbeequaltotheirstvaluein
thearrayandcurrentValuewillbeequaltothesecond.ItisaTypeErrorifthearraycontainsnoelementsand
initialValueisnotprovided.

reducedoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.
Therangeofelementsprocessedbyreduceissetbeforetheirstcalltocallbackfn.Elementsthatare
appendedtothearrayafterthecalltoreducebeginswillnotbevisitedbycallbackfn.Ifexistingelementsof
thearrayarechanged,theirvalueaspassedtocallbackfnwillbethevalueatthetimereducevisitsthem;
elementsthataredeletedafterthecalltoreducebeginsandbeforebeingvisitedarenotvisited.

Whenthereducemethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
4.Iflenis0andinitialValueisnotpresent,throwaTypeErrorexception.
5.Letkbe0.
6.IfinitialValueispresent,then
a.SetaccumulatortoinitialValue.
7.ElseinitialValueisnotpresent,
a.LetkPresentbefalse.
b.Repeat,whilekPresentisfalseandk<len
i.LetPkbe!ToString(k).
ii.LetkPresentbe?HasProperty(O,Pk).
iii.IfkPresentistrue,then
1.Letaccumulatorbe?Get(O,Pk).
iv.Increasekby1.
c.IfkPresentisfalse,throwaTypeErrorexception.
8.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.Letaccumulatorbe?Call(callbackfn,undeined,accumulator,kValue,k,O).
d.Increasekby1.
9.Returnaccumulator.

NOTE2 Thereducefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.20 Array.prototype.reduceRight(callbackfn[,initialValue])

NOTE1 callbackfnshouldbeafunctionthattakesfourarguments.reduceRightcallsthecallback,asafunction,once
foreachelementpresentinthearray,indescendingorder.

callbackfniscalledwithfourarguments:thepreviousValue(valuefromthepreviouscalltocallbackfn),the
currentValue(valueofthecurrentelement),thecurrentIndex,andtheobjectbeingtraversed.Theirsttimethe
functioniscalled,thepreviousValueandcurrentValuecanbeoneoftwovalues.IfaninitialValuewasprovided
inthecalltoreduceRight,thenpreviousValuewillbeequaltoinitialValueandcurrentValuewillbeequalto
thelastvalueinthearray.IfnoinitialValuewasprovided,thenpreviousValuewillbeequaltothelastvaluein
thearrayandcurrentValuewillbeequaltothesecondtolastvalue.ItisaTypeErrorifthearraycontainsno
elementsandinitialValueisnotprovided.

reduceRightdoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythe
callstocallbackfn.

TherangeofelementsprocessedbyreduceRightissetbeforetheirstcalltocallbackfn.Elementsthatare
appendedtothearrayafterthecalltoreduceRightbeginswillnotbevisitedbycallbackfn.Ifexisting
elementsofthearrayarechangedbycallbackfn,theirvalueaspassedtocallbackfnwillbethevalueatthetime
reduceRightvisitsthem;elementsthataredeletedafterthecalltoreduceRightbeginsandbeforebeing
visitedarenotvisited.
WhenthereduceRightmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
4.Iflenis0andinitialValueisnotpresent,throwaTypeErrorexception.
5.Letkbelen1.
6.IfinitialValueispresent,then
a.SetaccumulatortoinitialValue.
7.ElseinitialValueisnotpresent,
a.LetkPresentbefalse.
b.Repeat,whilekPresentisfalseandk0
i.LetPkbe!ToString(k).
ii.LetkPresentbe?HasProperty(O,Pk).
iii.IfkPresentistrue,then
1.Letaccumulatorbe?Get(O,Pk).
iv.Decreasekby1.
c.IfkPresentisfalse,throwaTypeErrorexception.
8.Repeat,whilek0
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.Letaccumulatorbe?Call(callbackfn,undeined,accumulator,kValue,k,O).
d.Decreasekby1.
9.Returnaccumulator.

NOTE2 ThereduceRightfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.21 Array.prototype.reverse()

NOTE1 Theelementsofthearrayarerearrangedsoastoreversetheirorder.Theobjectisreturnedastheresultofthe
call.

Whenthereversemethodiscalled,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.Letmiddlebeloor(len/2).
4.Letlowerbe0.
5.Repeat,whilelowermiddle
a.Letupperbelenlower1.
b.LetupperPbe!ToString(upper).
c.LetlowerPbe!ToString(lower).
d.LetlowerExistsbe?HasProperty(O,lowerP).
e.IflowerExistsistrue,then
i.LetlowerValuebe?Get(O,lowerP).
f.LetupperExistsbe?HasProperty(O,upperP).
g.IfupperExistsistrue,then
i.LetupperValuebe?Get(O,upperP).
h.IflowerExistsistrueandupperExistsistrue,then
i.Perform?Set(O,lowerP,upperValue,true).
ii.Perform?Set(O,upperP,lowerValue,true).
i.ElseiflowerExistsisfalseandupperExistsistrue,then
i.Perform?Set(O,lowerP,upperValue,true).
ii.Perform?DeletePropertyOrThrow(O,upperP).
j.ElseiflowerExistsistrueandupperExistsisfalse,then
i.Perform?DeletePropertyOrThrow(O,lowerP).
ii.Perform?Set(O,upperP,lowerValue,true).
k.ElsebothlowerExistsandupperExistsarefalse,
i.Noactionisrequired.
l.Increaselowerby1.
6.ReturnO.

NOTE2 Thereversefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Therefore,itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.22 Array.prototype.shift()

NOTE1 Theirstelementofthearrayisremovedfromthearrayandreturned.

Whentheshiftmethodiscalled,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.Ifleniszero,then
a.Perform?Set(O,"length",0,true).
b.Returnundeined.
4.Letirstbe?Get(O,"0").
5.Letkbe1.
6.Repeat,whilek<len
a.Letfrombe!ToString(k).
b.Lettobe!ToString(k1).
c.LetfromPresentbe?HasProperty(O,from).
d.IffromPresentistrue,then
i.LetfromValbe?Get(O,from).
ii.Perform?Set(O,to,fromVal,true).
e.ElsefromPresentisfalse,
i.Perform?DeletePropertyOrThrow(O,to).
f.Increasekby1.
7.Perform?DeletePropertyOrThrow(O,!ToString(len1)).
8.Perform?Set(O,"length",len1,true).
9.Returnirst.

NOTE2 Theshiftfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.23 Array.prototype.slice(start,end)

NOTE1 Theslicemethodtakestwoarguments,startandend,andreturnsanarraycontainingtheelementsofthe
arrayfromelementstartupto,butnotincluding,elementend(orthroughtheendofthearrayifendis
undeined).Ifstartisnegative,itistreatedaslength+startwherelengthisthelengthofthearray.Ifendis
negative,itistreatedaslength+endwherelengthisthelengthofthearray.

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.LetrelativeStartbe?ToInteger(start).
4.IfrelativeStart<0,letkbemax((len+relativeStart),0);elseletkbemin(relativeStart,len).
5.Ifendisundeined,letrelativeEndbelen;elseletrelativeEndbe?ToInteger(end).
6.IfrelativeEnd<0,letinalbemax((len+relativeEnd),0);elseletinalbemin(relativeEnd,len).
7.Letcountbemax(inalk,0).
8.LetAbe?ArraySpeciesCreate(O,count).
9.Letnbe0.
10.Repeat,whilek<inal
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.Perform?CreateDataPropertyOrThrow(A,!ToString(n),kValue).
d.Increasekby1.
e.Increasenby1.
11.Perform?Set(A,"length",n,true).
12.ReturnA.

NOTE2 TheexplicitsettingofthelengthpropertyoftheresultArrayinstep11wasnecessaryinpreviouseditionsof
ECMAScripttoensurethatitslengthwascorrectinsituationswherethetrailingelementsoftheresultArray
werenotpresent.SettinglengthbecameunnecessarystartinginES2015whentheresultArraywasinitialized
toitsproperlengthratherthananemptyArraybutiscarriedforwardtopreservebackwardcompatibility.

NOTE3 Theslicefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.24 Array.prototype.some(callbackfn[,thisArg])

NOTE1 callbackfnshouldbeafunctionthatacceptsthreeargumentsandreturnsavaluethatiscoercibletothe
Booleanvaluetrueorfalse.somecallscallbackfnonceforeachelementpresentinthearray,inascending
order,untilitindsonewherecallbackfnreturnstrue.Ifsuchanelementisfound,someimmediatelyreturns
true.Otherwise,somereturnsfalse.callbackfniscalledonlyforelementsofthearraywhichactuallyexist;itis
notcalledformissingelementsofthearray.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofcallbackfn.Ifitisnot
provided,undeinedisusedinstead.

callbackfniscalledwiththreearguments:thevalueoftheelement,theindexoftheelement,andtheobject
beingtraversed.

somedoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.

Therangeofelementsprocessedbysomeissetbeforetheirstcalltocallbackfn.Elementsthatareappended
tothearrayafterthecalltosomebeginswillnotbevisitedbycallbackfn.Ifexistingelementsofthearrayare
changed,theirvalueaspassedtocallbackfnwillbethevalueatthetimethatsomevisitsthem;elementsthat
aredeletedafterthecalltosomebeginsandbeforebeingvisitedarenotvisited.someactslikethe"exists"
quantiierinmathematics.Inparticular,foranemptyarray,itreturnsfalse.

Whenthesomemethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
4.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
5.Letkbe0.
6.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkPresentbe?HasProperty(O,Pk).
c.IfkPresentistrue,then
i.LetkValuebe?Get(O,Pk).
ii.LettestResultbeToBoolean(?Call(callbackfn,T,kValue,k,O)).
iii.IftestResultistrue,returntrue.
d.Increasekby1.
7.Returnfalse.

NOTE2 Thesomefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.25 Array.prototype.sort(comparefn)

Theelementsofthisarrayaresorted.Thesortisnotnecessarilystable(thatis,elementsthatcompareequaldonot
necessarilyremainintheiroriginalorder).Ifcomparefnisnotundeined,itshouldbeafunctionthatacceptstwoarguments
xandyandreturnsanegativevalueifx<y,zeroifx=y,orapositivevalueifx>y.

Uponentry,thefollowingstepsareperformedtoinitializeevaluationofthesortfunction:

1.Letobjbe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(obj,"length")).

Withinthisspeciicationofthesortmethod,anobject,obj,issaidtobesparseifthefollowingalgorithmreturnstrue:

1.Foreachintegeriintherange0i<len
a.Letelembeobj.[[GetOwnProperty]](!ToString(i)).
b.Ifelemisundeined,returntrue.
2.Returnfalse.

Thesortorderistheordering,aftercompletionofthisfunction,oftheintegerindexedpropertyvaluesofobjwhoseinteger
indexesarelessthanlen.Theresultofthesortfunctionisthendeterminedasfollows:

Ifcomparefnisnotundeinedandisnotaconsistentcomparisonfunctionfortheelementsofthisarray(seebelow),thesort
orderisimplementationdeined.ThesortorderisalsoimplementationdeinedifcomparefnisundeinedandSortCompare
doesnotactasaconsistentcomparisonfunction.

Letprotobeobj.[[GetPrototypeOf]]().Ifprotoisnotnullandthereexistsanintegerjsuchthatalloftheconditionsbeloware
satisiedthenthesortorderisimplementationdeined:

objissparse
0j<len
HasProperty(proto,ToString(j))istrue.

Thesortorderisalsoimplementationdeinedifobjissparseandanyofthefollowingconditionsaretrue:

IsExtensible(obj)isfalse.
Anyintegerindexpropertyofobjwhosenameisanonnegativeintegerlessthanlenisadatapropertywhose
[[Conigurable]]attributeisfalse.

Thesortorderisalsoimplementationdeinedifanyofthefollowingconditionsaretrue:

Ifobjisanexoticobject(includingProxyexoticobjects)whosebehaviourfor[[Get]],[[Set]],[[Delete]],and
[[GetOwnProperty]]isnottheordinaryobjectimplementationoftheseinternalmethods.
Ifanyindexpropertyofobjwhosenameisanonnegativeintegerlessthanlenisanaccessorpropertyorisadata
propertywhose[[Writable]]attributeisfalse.
IfcomparefnisundeinedandtheapplicationofToStringtoanyvaluepassedasanargumenttoSortComparemodiies
objoranyobjectonobj'sprototypechain.
IfcomparefnisundeinedandallapplicationsofToString,toanyspeciicvaluepassedasanargumenttoSortCompare,
donotproducethesameresult.

Thefollowingstepsaretaken:
1.Performanimplementationdependentsequenceofcallstothe[[Get]]and[[Set]]internalmethodsofobj,tothe
DeletePropertyOrThrowandHasOwnPropertyabstractoperationwithobjastheirstargument,andtoSortCompare
(describedbelow),suchthat:
Thepropertykeyargumentforeachcallto[[Get]],[[Set]],HasOwnProperty,orDeletePropertyOrThrowisthe
stringrepresentationofanonnegativeintegerlessthanlen.
TheargumentsforcallstoSortComparearevaluesreturnedbyapreviouscalltothe[[Get]]internalmethod,
unlessthepropertiesaccessedbythosepreviouscallsdidnotexistaccordingtoHasOwnProperty.Ifboth
perspectiveargumentstoSortComparecorrespondtononexistentproperties,use+0insteadofcalling
SortCompare.Ifonlytheirstperspectiveargumentisnonexistentuse+1.Ifonlythesecondperspective
argumentisnonexistentuse1.
IfobjisnotsparsethenDeletePropertyOrThrowmustnotbecalled.
Ifany[[Set]]callreturnsfalseaTypeErrorexceptionisthrown.
Ifanabruptcompletionisreturnedfromanyoftheseoperations,itisimmediatelyreturnedasthevalueofthis
function.
2.Returnobj.

Unlessthesortorderisspeciiedabovetobeimplementationdeined,thereturnedobjectmusthavethefollowingtwo
characteristics:

Theremustbesomemathematicalpermutationofthenonnegativeintegerslessthanlen,suchthatforevery
nonnegativeintegerjlessthanlen,ifpropertyold[j]existed,thennew[(j)]isexactlythesamevalueasold[j].Butif
propertyold[j]didnotexist,thennew[(j)]doesnotexist.
Thenforallnonnegativeintegersjandk,eachlessthanlen,ifSortCompare(old[j],old[k])<0(seeSortComparebelow),
thennew[(j)]<new[(k)].

Herethenotationold[j]isusedtorefertothehypotheticalresultofcallingthe[[Get]]internalmethodofobjwithargumentj
beforethisfunctionisexecuted,andthenotationnew[j]torefertothehypotheticalresultofcallingthe[[Get]]internal
methodofobjwithargumentjafterthisfunctionhasbeenexecuted.

AfunctioncomparefnisaconsistentcomparisonfunctionforasetofvaluesSifalloftherequirementsbelowaremetforall
valuesa,b,andc(possiblythesamevalue)inthesetS:Thenotationa<CFbmeanscomparefn(a,b)<0;a=CFbmeans
comparefn(a,b)=0(ofeithersign);anda>CFbmeanscomparefn(a,b)>0.

Callingcomparefn(a,b)alwaysreturnsthesamevaluevwhengivenaspeciicpairofvaluesaandbasitstwo
arguments.Furthermore,Type(v)isNumber,andvisnotNaN.Notethatthisimpliesthatexactlyoneofa<CFb,a=CFb,
anda>CFbwillbetrueforagivenpairofaandb.
Callingcomparefn(a,b)doesnotmodifyobjoranyobjectonobj'sprototypechain.
a=CFa(relexivity)
Ifa=CFb,thenb=CFa(symmetry)
Ifa=CFbandb=CFc,thena=CFc(transitivityof=CF)
Ifa<CFbandb<CFc,thena<CFc(transitivityof<CF)
Ifa>CFbandb>CFc,thena>CFc(transitivityof>CF)

NOTE1 TheaboveconditionsarenecessaryandsuficienttoensurethatcomparefndividesthesetSintoequivalence
classesandthattheseequivalenceclassesaretotallyordered.

NOTE2 Thesortfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.Therefore,
itcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.25.1 RuntimeSemantics:SortCompare(x,y)

TheSortCompareabstractoperationiscalledwithtwoargumentsxandy.Italsohasaccesstothecomparefnargument
passedtothecurrentinvocationofthesortmethod.Thefollowingstepsaretaken:

1.Ifxandyarebothundeined,return+0.
2.Ifxisundeined,return1.
3.Ifyisundeined,return1.
4.Iftheargumentcomparefnisnotundeined,then
a.Letvbe?ToNumber(?Call(comparefn,undeined,x,y)).
b.IfvisNaN,return+0.
c.Returnv.
5.LetxStringbe?ToString(x).
6.LetyStringbe?ToString(y).
7.LetxSmallerbetheresultofperformingAbstractRelationalComparisonxString<yString.
8.IfxSmalleristrue,return1.
9.LetySmallerbetheresultofperformingAbstractRelationalComparisonyString<xString.
10.IfySmalleristrue,return1.
11.Return+0.

NOTE1 Becausenonexistentpropertyvaluesalwayscomparegreaterthanundeinedpropertyvalues,and
undeinedalwayscomparesgreaterthananyothervalue,undeinedpropertyvaluesalwayssorttotheendof
theresult,followedbynonexistentpropertyvalues.

NOTE2 MethodcallsperformedbytheToStringabstractoperationsinsteps5and7havethepotentialtocause
SortComparetonotbehaveasaconsistentcomparisonfunction.

22.1.3.26 Array.prototype.splice(start,deleteCount,...items)

NOTE1 Whenthesplicemethodiscalledwithtwoormoreargumentsstart,deleteCountandzeroormoreitems,the
deleteCountelementsofthearraystartingatintegerindexstartarereplacedbytheargumentsitems.AnArray
objectcontainingthedeletedelements(ifany)isreturned.

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.LetrelativeStartbe?ToInteger(start).
4.IfrelativeStart<0,letactualStartbemax((len+relativeStart),0);elseletactualStartbemin(relativeStart,len).
5.Ifthenumberofactualargumentsis0,then
a.LetinsertCountbe0.
b.LetactualDeleteCountbe0.
6.Elseifthenumberofactualargumentsis1,then
a.LetinsertCountbe0.
b.LetactualDeleteCountbelenactualStart.
7.Else,
a.LetinsertCountbethenumberofactualargumentsminus2.
b.Letdcbe?ToInteger(deleteCount).
c.LetactualDeleteCountbemin(max(dc,0),lenactualStart).
8.Iflen+insertCountactualDeleteCount>2531,throwaTypeErrorexception.
9.LetAbe?ArraySpeciesCreate(O,actualDeleteCount).
10.Letkbe0.
11.Repeat,whilek<actualDeleteCount
a.Letfrombe!ToString(actualStart+k).
b.LetfromPresentbe?HasProperty(O,from).
c.IffromPresentistrue,then
i.LetfromValuebe?Get(O,from).
ii.Perform?CreateDataPropertyOrThrow(A,!ToString(k),fromValue).
d.Incrementkby1.
12.Perform?Set(A,"length",actualDeleteCount,true).
13.LetitemsbeaListwhoseelementsare,inlefttorightorder,theportionoftheactualargumentliststartingwiththe
thirdargument.Thelistisemptyiffewerthanthreeargumentswerepassed.
14.LetitemCountbethenumberofelementsinitems.
15.IfitemCount<actualDeleteCount,then
a.LetkbeactualStart.
b.Repeat,whilek<(lenactualDeleteCount)
i.Letfrombe!ToString(k+actualDeleteCount).
ii.Lettobe!ToString(k+itemCount).
iii.LetfromPresentbe?HasProperty(O,from).
iv.IffromPresentistrue,then
1.LetfromValuebe?Get(O,from).
2.Perform?Set(O,to,fromValue,true).
v.ElsefromPresentisfalse,
1.Perform?DeletePropertyOrThrow(O,to).
vi.Increasekby1.
c.Letkbelen.
d.Repeat,whilek>(lenactualDeleteCount+itemCount)
i.Perform?DeletePropertyOrThrow(O,!ToString(k1)).
ii.Decreasekby1.
16.ElseifitemCount>actualDeleteCount,then
a.Letkbe(lenactualDeleteCount).
b.Repeat,whilek>actualStart
i.Letfrombe!ToString(k+actualDeleteCount1).
ii.Lettobe!ToString(k+itemCount1).
iii.LetfromPresentbe?HasProperty(O,from).
iv.IffromPresentistrue,then
1.LetfromValuebe?Get(O,from).
2.Perform?Set(O,to,fromValue,true).
v.ElsefromPresentisfalse,
1.Perform?DeletePropertyOrThrow(O,to).
vi.Decreasekby1.
17.LetkbeactualStart.
18.Repeat,whileitemsisnotempty
a.RemovetheirstelementfromitemsandletEbethevalueofthatelement.
b.Perform?Set(O,!ToString(k),E,true).
c.Increasekby1.
19.Perform?Set(O,"length",lenactualDeleteCount+itemCount,true).
20.ReturnA.

NOTE2 TheexplicitsettingofthelengthpropertyoftheresultArrayinstep19wasnecessaryinpreviouseditionsof
ECMAScripttoensurethatitslengthwascorrectinsituationswherethetrailingelementsoftheresultArray
werenotpresent.SettinglengthbecameunnecessarystartinginES2015whentheresultArraywas
initializedtoitsproperlengthratherthananemptyArraybutiscarriedforwardtopreservebackward
compatibility.

NOTE3 Thesplicefunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.27 Array.prototype.toLocaleString([reserved1[,reserved2]])

AnECMAScriptimplementationthatincludestheECMA402InternationalizationAPImustimplementthe
Array.prototype.toLocaleStringmethodasspeciiedintheECMA402speciication.IfanECMAScriptimplementation
doesnotincludetheECMA402APIthefollowingspeciicationofthetoLocaleStringmethodisused.

NOTE1 TheirsteditionofECMA402didnotincludeareplacementspeciicationforthe
Array.prototype.toLocaleStringmethod.

ThemeaningsoftheoptionalparameterstothismethodaredeinedintheECMA402speciication;implementationsthatdo
notincludeECMA402supportmustnotusethoseparameterpositionsforanythingelse.
Thefollowingstepsaretaken:

1.Letarraybe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(array,"length")).
3.LetseparatorbetheStringvalueforthelistseparatorStringappropriateforthehostenvironment'scurrentlocale(this
isderivedinanimplementationdeinedway).
4.Ifleniszero,returntheemptyString.
5.LetirstElementbe?Get(array,"0").
6.IfirstElementisundeinedornull,then
a.LetRbetheemptyString.
7.Else,
a.LetRbe?ToString(?Invoke(irstElement,"toLocaleString")).
8.Letkbe1.
9.Repeat,whilek<len
a.LetSbeaStringvalueproducedbyconcatenatingRandseparator.
b.LetnextElementbe?Get(array,!ToString(k)).
c.IfnextElementisundeinedornull,then
i.LetRbetheemptyString.
d.Else,
i.LetRbe?ToString(?Invoke(nextElement,"toLocaleString")).
e.LetRbeaStringvalueproducedbyconcatenatingSandR.
f.Increasekby1.
10.ReturnR.

NOTE2 TheelementsofthearrayareconvertedtoStringsusingtheirtoLocaleStringmethods,andtheseStrings
arethenconcatenated,separatedbyoccurrencesofaseparatorStringthathasbeenderivedinan
implementationdeinedlocalespeciicway.Theresultofcallingthisfunctionisintendedtobeanalogousto
theresultoftoString,exceptthattheresultofthisfunctionisintendedtobelocalespeciic.

NOTE3 ThetoLocaleStringfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArray
object.Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.28 Array.prototype.toString()

WhenthetoStringmethodiscalled,thefollowingstepsaretaken:

1.Letarraybe?ToObject(thisvalue).
2.Letfuncbe?Get(array,"join").
3.IfIsCallable(func)isfalse,letfuncbetheintrinsicfunction%ObjProto_toString%.
4.Return?Call(func,array).

NOTE ThetoStringfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.29 Array.prototype.unshift(...items)

NOTE1 Theargumentsareprependedtothestartofthearray,suchthattheirorderwithinthearrayisthesameasthe
orderinwhichtheyappearintheargumentlist.

Whentheunshiftmethodiscalledwithzeroormoreargumentsitem1,item2,etc.,thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.Letlenbe?ToLength(?Get(O,"length")).
3.LetargCountbethenumberofactualarguments.
4.IfargCount>0,then
a.Iflen+argCount>2531,throwaTypeErrorexception.
b.Letkbelen.
c.Repeat,whilek>0,
i.Letfrombe!ToString(k1).
ii.Lettobe!ToString(k+argCount1).
iii.LetfromPresentbe?HasProperty(O,from).
iv.IffromPresentistrue,then
1.LetfromValuebe?Get(O,from).
2.Perform?Set(O,to,fromValue,true).
v.ElsefromPresentisfalse,
1.Perform?DeletePropertyOrThrow(O,to).
vi.Decreasekby1.
d.Letjbe0.
e.LetitemsbeaListwhoseelementsare,inlefttorightorder,theargumentsthatwerepassedtothisfunction
invocation.
f.Repeat,whileitemsisnotempty
i.RemovetheirstelementfromitemsandletEbethevalueofthatelement.
ii.Perform?Set(O,!ToString(j),E,true).
iii.Increasejby1.
5.Perform?Set(O,"length",len+argCount,true).
6.Returnlen+argCount.

Thelengthpropertyoftheunshiftmethodis1.

NOTE2 Theunshiftfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeanArrayobject.
Thereforeitcanbetransferredtootherkindsofobjectsforuseasamethod.

22.1.3.30 Array.prototype.values()

Thefollowingstepsaretaken:

1.LetObe?ToObject(thisvalue).
2.ReturnCreateArrayIterator(O,"value").

Thisfunctionisthe%ArrayProto_values%intrinsicobject.

22.1.3.31 Array.prototype[@@iterator]()

Theinitialvalueofthe@@iteratorpropertyisthesamefunctionobjectastheinitialvalueofthe
Array.prototype.valuesproperty.

22.1.3.32 Array.prototype[@@unscopables]

Theinitialvalueofthe@@unscopablesdatapropertyisanobjectcreatedbythefollowingsteps:

1.LetblackListbeObjectCreate(null).
2.PerformCreateDataProperty(blackList,"copyWithin",true).
3.PerformCreateDataProperty(blackList,"entries",true).
4.PerformCreateDataProperty(blackList,"fill",true).
5.PerformCreateDataProperty(blackList,"find",true).
6.PerformCreateDataProperty(blackList,"findIndex",true).
7.PerformCreateDataProperty(blackList,"includes",true).
8.PerformCreateDataProperty(blackList,"keys",true).
9.PerformCreateDataProperty(blackList,"values",true).
10.Assert:Eachoftheabovecallswillreturntrue.
11.ReturnblackList.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.
NOTE Theownpropertynamesofthisobjectarepropertynamesthatwerenotincludedasstandardpropertiesof
Array.prototypepriortotheECMAScript2015speciication.Thesenamesareignoredforwithstatement
bindingpurposesinordertopreservethebehaviourofexistingcodethatmightuseoneofthesenamesasa
bindinginanouterscopethatisshadowedbyawithstatementwhosebindingobjectisanArrayobject.

22.1.4 PropertiesofArrayInstances

ArrayinstancesareArrayexoticobjectsandhavetheinternalmethodsspeciiedforsuchobjects.Arrayinstancesinherit
propertiesfromtheArrayprototypeobject.

Arrayinstanceshavealengthproperty,andasetofenumerablepropertieswitharrayindexnames.

22.1.4.1 length

ThelengthpropertyofanArrayinstanceisadatapropertywhosevalueisalwaysnumericallygreaterthanthenameof
everyconigurableownpropertywhosenameisanarrayindex.

Thelengthpropertyinitiallyhastheattributes{[[Writable]]:true,[[Enumerable]]:false,[[Conigurable]]:false}.

NOTE Reducingthevalueofthelengthpropertyhasthesideeffectofdeletingownarrayelementswhosearray
indexisbetweentheoldandnewlengthvalues.However,nonconigurablepropertiescannotbedeleted.
AttemptingtosetthelengthpropertyofanArrayobjecttoavaluethatisnumericallylessthanorequaltothe
largestnumericownpropertynameofanexistingnonconigurablearrayindexedpropertyofthearraywill
resultinthelengthbeingsettoanumericvaluethatisonegreaterthanthatnonconigurablenumericown
propertyname.See9.4.2.1.

22.1.5 ArrayIteratorObjects

AnArrayIteratorisanobject,thatrepresentsaspeciiciterationoversomespeciicArrayinstanceobject.Thereisnota
namedconstructorforArrayIteratorobjects.Instead,ArrayiteratorobjectsarecreatedbycallingcertainmethodsofArray
instanceobjects.

22.1.5.1 CreateArrayIteratorAbstractOperation

SeveralmethodsofArrayobjectsreturnIteratorobjects.TheabstractoperationCreateArrayIteratorwithargumentsarray
andkindisusedtocreatesuchiteratorobjects.Itperformsthefollowingsteps:

1.Assert:Type(array)isObject.
2.LetiteratorbeObjectCreate(%ArrayIteratorPrototype%,[[IteratedObject]],[[ArrayIteratorNextIndex]],
[[ArrayIterationKind]]).
3.Setiterator's[[IteratedObject]]internalslottoarray.
4.Setiterator's[[ArrayIteratorNextIndex]]internalslotto0.
5.Setiterator's[[ArrayIterationKind]]internalslottokind.
6.Returniterator.

22.1.5.2 The%ArrayIteratorPrototype%Object

AllArrayIteratorObjectsinheritpropertiesfromthe%ArrayIteratorPrototype%intrinsicobject.The
%ArrayIteratorPrototype%objectisanordinaryobjectandits[[Prototype]]internalslotisthe%IteratorPrototype%
intrinsicobject.Inaddition,%ArrayIteratorPrototype%hasthefollowingproperties:

22.1.5.2.1 %ArrayIteratorPrototype%.next()

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavealloftheinternalslotsofanArrayIteratorInstance(22.1.5.3),throwaTypeErrorexception.
4.Letabethevalueofthe[[IteratedObject]]internalslotofO.
5.Ifaisundeined,returnCreateIterResultObject(undeined,true).
6.Letindexbethevalueofthe[[ArrayIteratorNextIndex]]internalslotofO.
7.LetitemKindbethevalueofthe[[ArrayIterationKind]]internalslotofO.
8.Ifahasa[[TypedArrayName]]internalslot,then
a.Letlenbethevalueofa's[[ArrayLength]]internalslot.
9.Else,
a.Letlenbe?ToLength(?Get(a,"length")).
10.Ifindexlen,then
a.Setthevalueofthe[[IteratedObject]]internalslotofOtoundeined.
b.ReturnCreateIterResultObject(undeined,true).
11.Setthevalueofthe[[ArrayIteratorNextIndex]]internalslotofOtoindex+1.
12.IfitemKindis"key",returnCreateIterResultObject(index,false).
13.LetelementKeybe!ToString(index).
14.LetelementValuebe?Get(a,elementKey).
15.IfitemKindis"value",letresultbeelementValue.
16.Else,
a.Assert:itemKindis"key+value".
b.LetresultbeCreateArrayFromList(index,elementValue).
17.ReturnCreateIterResultObject(result,false).

22.1.5.2.2 %ArrayIteratorPrototype%[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"ArrayIterator".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

22.1.5.3 PropertiesofArrayIteratorInstances

ArrayIteratorinstancesareordinaryobjectsthatinheritpropertiesfromthe%ArrayIteratorPrototype%intrinsicobject.
ArrayIteratorinstancesareinitiallycreatedwiththeinternalslotslistedinTable49.

Table49:InternalSlotsofArrayIteratorInstances
InternalSlot Description

[[IteratedObject]] Theobjectwhosearrayelementsarebeingiterated.

[[ArrayIteratorNextIndex]] Theintegerindexofthenextintegerindextobeexaminedbythisiteration.

[[ArrayIterationKind]] AStringvaluethatidentiieswhatisreturnedforeachelementoftheiteration.Thepossible
valuesare:"key","value","key+value".

22.2 TypedArrayObjects
TypedArrayobjectspresentanarraylikeviewofanunderlyingbinarydatabuffer(24.1).EachelementofaTypedArray
instancehasthesameunderlyingbinaryscalardatatype.ThereisadistinctTypedArrayconstructor,listedinTable50,for
eachoftheninesupportedelementtypes.EachconstructorinTable50hasacorrespondingdistinctprototypeobject.
Table50:TheTypedArrayConstructors
ConstructorNameand Element Element Conversion Description EquivalentC
Intrinsic Type Size Operation Type

Int8Array Int8 1 ToInt8 8bit2'scomplementsigned signedchar


%Int8Array% integer

Uint8Array Uint8 1 ToUint8 8bitunsignedinteger unsignedchar


%Uint8Array%

Uint8ClampedArray Uint8C 1 ToUint8Clamp 8bitunsignedinteger(clamped unsignedchar


%Uint8ClampedArray% conversion)

Int16Array Int16 2 ToInt16 16bit2'scomplementsigned short


%Int16Array% integer

Uint16Array Uint16 2 ToUint16 16bitunsignedinteger unsigned


%Uint16Array% short

Int32Array Int32 4 ToInt32 32bit2'scomplementsigned int


%Int32Array% integer

Uint32Array Uint32 4 ToUint32 32bitunsignedinteger unsignedint


%Uint32Array%

Float32Array Float32 4 32bitIEEEloatingpoint loat


%Float32Array%

Float64Array Float64 8 64bitIEEEloatingpoint double


%Float64Array%

Inthedeinitionsbelow,referencestoTypedArrayshouldbereplacedwiththeappropriateconstructornamefromtheabove
table.ThephrasetheelementsizeinbytesreferstothevalueintheElementSizecolumnofthetableintherow
correspondingtotheconstructor.ThephraseelementTypereferstothevalueintheElementTypecolumnforthatrow.

22.2.1 The%TypedArray%IntrinsicObject

The%TypedArray%intrinsicobjectisaconstructorfunctionobjectthatalloftheTypedArrayconstructorobjectinheritfrom.
%TypedArray%anditscorrespondingprototypeobjectprovidecommonpropertiesthatareinheritedbyallTypedArray
constructorsandtheirinstances.The%TypedArray%intrinsicdoesnothaveaglobalnameorappearasapropertyofthe
globalobject.

The%TypedArray%intrinsicfunctionobjectactsastheabstractsuperclassofthevariousTypedArrayconstructors.Because
itisanabstractclassconstructoritwillthrowanerrorwheninvoked.TheTypeArrayconstructorsdonotperformasuper
calltoit.

22.2.1.1 %TypedArray%()

The%TypedArray%constructorperformsthefollowingsteps:

1.ThrowaTypeErrorexception.

Thelengthpropertyofthe%TypedArray%constructorfunctionis0.

22.2.2 Propertiesofthe%TypedArray%IntrinsicObject

Thevalueofthe[[Prototype]]internalslotof%TypedArray%istheintrinsicobject%FunctionPrototype%.

Thenamepropertyofthe%TypedArray%constructorfunctionis"TypedArray".
The%TypedArray%constructorhasthefollowingproperties:

22.2.2.1 %TypedArray%.from(source[,mapfn[,thisArg]])

Whenthefrommethodiscalledwithargumentsource,andoptionalargumentsmapfnandthisArg,thefollowingstepsare
taken:

1.LetCbethethisvalue.
2.IfIsConstructor(C)isfalse,throwaTypeErrorexception.
3.Ifmapfnwassuppliedandmapfnisnotundeined,then
a.IfIsCallable(mapfn)isfalse,throwaTypeErrorexception.
b.Letmappingbetrue.
4.Else,letmappingbefalse.
5.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
6.LetarrayLikebe?IterableToArrayLike(source).
7.Letlenbe?ToLength(?Get(arrayLike,"length")).
8.LettargetObjbe?TypedArrayCreate(C,len).
9.Letkbe0.
10.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkValuebe?Get(arrayLike,Pk).
c.Ifmappingistrue,then
i.LetmappedValuebe?Call(mapfn,T,kValue,k).
d.Else,letmappedValuebekValue.
e.Perform?Set(targetObj,Pk,mappedValue,true).
f.Increasekby1.
11.ReturntargetObj.

22.2.2.1.1 RuntimeSemantics:IterableToArrayLike(items)

TheabstractoperationIterableToArrayLikeperformsthefollowingsteps:

1.LetusingIteratorbe?GetMethod(items,@@iterator).
2.IfusingIteratorisnotundeined,then
a.Letiteratorbe?GetIterator(items,usingIterator).
b.LetvaluesbeanewemptyList.
c.Letnextbetrue.
d.Repeat,whilenextisnotfalse
i.Letnextbe?IteratorStep(iterator).
ii.Ifnextisnotfalse,then
1.LetnextValuebe?IteratorValue(next).
2.AppendnextValuetotheendoftheListvalues.
e.ReturnCreateArrayFromList(values).
3.NOTE:itemsisnotanIterablesoassumeitisalreadyanarraylikeobject.
4.Return!ToObject(items).

22.2.2.2 %TypedArray%.of(...items)

Whentheofmethodiscalledwithanynumberofarguments,thefollowingstepsaretaken:

1.Letlenbetheactualnumberofargumentspassedtothisfunction.
2.LetitemsbetheListofargumentspassedtothisfunction.
3.LetCbethethisvalue.
4.IfIsConstructor(C)isfalse,throwaTypeErrorexception.
5.LetnewObjbe?TypedArrayCreate(C,len).
6.Letkbe0.
7.Repeat,whilek<len
a.LetkValuebeitems[k].
b.LetPkbe!ToString(k).
c.Perform?Set(newObj,Pk,kValue,true).
d.Increasekby1.
8.ReturnnewObj.

NOTE Theitemsargumentisassumedtobeawellformedrestargumentvalue.

22.2.2.3 %TypedArray%.prototype

Theinitialvalueof%TypedArray%.prototypeisthe%TypedArrayPrototype%intrinsicobject.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

22.2.2.4 get%TypedArray%[@@species]

%TypedArray%[@@species]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.Returnthethisvalue.

Thevalueofthenamepropertyofthisfunctionis"get[Symbol.species]".

NOTE %TypedArrayPrototype%methodsnormallyusetheirthisobject'sconstructortocreateaderivedobject.
However,asubclassconstructormayoverridethatdefaultbehaviourbyredeiningits@@speciesproperty.

22.2.3 Propertiesofthe%TypedArrayPrototype%Object

Thevalueofthe[[Prototype]]internalslotofthe%TypedArrayPrototype%objectistheintrinsicobject%ObjectPrototype%.
The%TypedArrayPrototype%objectisanordinaryobject.Itdoesnothavea[[ViewedArrayBuffer]]oranyotherofthe
internalslotsthatarespeciictoTypedArrayinstanceobjects.

22.2.3.1 get%TypedArray%.prototype.buffer

%TypedArray%.prototype.bufferisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[ViewedArrayBuffer]]internalslot,throwaTypeErrorexception.
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.Returnbuffer.

22.2.3.2 get%TypedArray%.prototype.byteLength

%TypedArray%.prototype.byteLengthisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[ViewedArrayBuffer]]internalslot,throwaTypeErrorexception.
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.IfIsDetachedBuffer(buffer)istrue,return0.
6.LetsizebethevalueofO's[[ByteLength]]internalslot.
7.Returnsize.

22.2.3.3 get%TypedArray%.prototype.byteOffset
%TypedArray%.prototype.byteOffsetisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[ViewedArrayBuffer]]internalslot,throwaTypeErrorexception.
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.IfIsDetachedBuffer(buffer)istrue,return0.
6.LetoffsetbethevalueofO's[[ByteOffset]]internalslot.
7.Returnoffset.

22.2.3.4 %TypedArray%.prototype.constructor

Theinitialvalueof%TypedArray%.prototype.constructoristhe%TypedArray%intrinsicobject.

22.2.3.5 %TypedArray%.prototype.copyWithin(target,start[,end])

%TypedArray%.prototype.copyWithinisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.copyWithinasdeinedin22.1.3.3exceptthatthethisobject's[[ArrayLength]]internalslotisaccessed
inplaceofperforminga[[Get]]of"length"andtheactualcopyingofvaluesinstep12mustbeperformedinamannerthat
preservesthebitlevelencodingofthesourcedata

Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethatthethisvalueisanobjectthathasaixed
lengthandwhoseintegerindexedpropertiesarenotsparse.However,suchoptimizationmustnotintroduceanyobservable
changesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.5.1 RuntimeSemantics:ValidateTypedArray(O)

WhencalledwithargumentO,thefollowingstepsaretaken:

1.IfType(O)isnotObject,throwaTypeErrorexception.
2.IfOdoesnothavea[[TypedArrayName]]internalslot,throwaTypeErrorexception.
3.IfOdoesnothavea[[ViewedArrayBuffer]]internalslot,throwaTypeErrorexception.
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
6.Returnbuffer.

22.2.3.6 %TypedArray%.prototype.entries()

Thefollowingstepsaretaken:

1.LetObethethisvalue.
2.Perform?ValidateTypedArray(O).
3.ReturnCreateArrayIterator(O,"key+value").

22.2.3.7 %TypedArray%.prototype.every(callbackfn[,thisArg])

%TypedArray%.prototype.everyisadistinctfunctionthatimplementsthesamealgorithmasArray.prototype.every
asdeinedin22.1.3.5exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedinplaceofperforminga[[Get]]of
"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethatthethisvalueisanobjectthat
hasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,suchoptimizationmustnotintroduceany
observablechangesinthespeciiedbehaviourofthealgorithmandmusttakeintoaccountthepossibilitythatcallsto
callbackfnmaycausethethisvaluetobecomedetached.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.
22.2.3.8 %TypedArray%.prototype.ill(value[,start[,end]])

%TypedArray%.prototype.fillisadistinctfunctionthatimplementsthesamealgorithmasArray.prototype.fillas
deinedin22.1.3.6exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedinplaceofperforminga[[Get]]of
"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethatthethisvalueisanobjectthat
hasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,suchoptimizationmustnotintroduceany
observablechangesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.9 %TypedArray%.prototype.ilter(callbackfn[,thisArg])

Theinterpretationanduseoftheargumentsof%TypedArray%.prototype.filterarethesameasfor
Array.prototype.filterasdeinedin22.1.3.7.

Whenthefiltermethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObethethisvalue.
2.Perform?ValidateTypedArray(O).
3.LetlenbethevalueofO's[[ArrayLength]]internalslot.
4.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
5.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
6.LetkeptbeanewemptyList.
7.Letkbe0.
8.Letcapturedbe0.
9.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkValuebe?Get(O,Pk).
c.LetselectedbeToBoolean(?Call(callbackfn,T,kValue,k,O)).
d.Ifselectedistrue,then
i.AppendkValuetotheendofkept.
ii.Increasecapturedby1.
e.Increasekby1.
10.LetAbe?TypedArraySpeciesCreate(O,captured).
11.Letnbe0.
12.Foreachelementeofkept
a.Perform!Set(A,!ToString(n),e,true).
b.Incrementnby1.
13.ReturnA.

Thisfunctionisnotgeneric.Thethisvaluemustbeanobjectwitha[[TypedArrayName]]internalslot.

22.2.3.10 %TypedArray%.prototype.ind(predicate[,thisArg])

%TypedArray%.prototype.findisadistinctfunctionthatimplementsthesamealgorithmasArray.prototype.findas
deinedin22.1.3.8exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedinplaceofperforminga[[Get]]of
"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethatthethisvalueisanobjectthat
hasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,suchoptimizationmustnotintroduceany
observablechangesinthespeciiedbehaviourofthealgorithmandmusttakeintoaccountthepossibilitythatcallsto
predicatemaycausethethisvaluetobecomedetached.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.11 %TypedArray%.prototype.indIndex(predicate[,thisArg])
%TypedArray%.prototype.findIndexisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.findIndexasdeinedin22.1.3.9exceptthatthethisobject's[[ArrayLength]]internalslotisaccessed
inplaceofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledge
thatthethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,such
optimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithmandmusttakeinto
accountthepossibilitythatcallstopredicatemaycausethethisvaluetobecomedetached.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.12 %TypedArray%.prototype.forEach(callbackfn[,thisArg])

%TypedArray%.prototype.forEachisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.forEachasdeinedin22.1.3.10exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedin
placeofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethat
thethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,such
optimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithmandmusttakeinto
accountthepossibilitythatcallstocallbackfnmaycausethethisvaluetobecomedetached.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.13 %TypedArray%.prototype.indexOf(searchElement[,fromIndex])

%TypedArray%.prototype.indexOfisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.indexOfasdeinedin22.1.3.12exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedin
placeofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethat
thethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,such
optimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.14 %TypedArray%.prototype.includes(searchElement[,fromIndex])

%TypedArray%.prototype.includesisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.includesasdeinedin22.1.3.11exceptthatthethisobject's[[ArrayLength]]internalslotisaccessed
inplaceofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledge
thatthethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,such
optimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.15 %TypedArray%.prototype.join(separator)

%TypedArray%.prototype.joinisadistinctfunctionthatimplementsthesamealgorithmasArray.prototype.joinas
deinedin22.1.3.13exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedinplaceofperforminga[[Get]]of
"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethatthethisvalueisanobjectthat
hasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,suchoptimizationmustnotintroduceany
observablechangesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.16 %TypedArray%.prototype.keys()

Thefollowingstepsaretaken:
1.LetObethethisvalue.
2.Perform?ValidateTypedArray(O).
3.ReturnCreateArrayIterator(O,"key").

22.2.3.17 %TypedArray%.prototype.lastIndexOf(searchElement[,fromIndex])

%TypedArray%.prototype.lastIndexOfisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.lastIndexOfasdeinedin22.1.3.15exceptthatthethisobject's[[ArrayLength]]internalslotis
accessedinplaceofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththe
knowledgethatthethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.
However,suchoptimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.18 get%TypedArray%.prototype.length

%TypedArray%.prototype.lengthisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[TypedArrayName]]internalslot,throwaTypeErrorexception.
4.Assert:Ohas[[ViewedArrayBuffer]]and[[ArrayLength]]internalslots.
5.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
6.IfIsDetachedBuffer(buffer)istrue,return0.
7.LetlengthbethevalueofO's[[ArrayLength]]internalslot.
8.Returnlength.

Thisfunctionisnotgeneric.Thethisvaluemustbeanobjectwitha[[TypedArrayName]]internalslot.

22.2.3.19 %TypedArray%.prototype.map(callbackfn[,thisArg])

Theinterpretationanduseoftheargumentsof%TypedArray%.prototype.maparethesameasfor
Array.prototype.mapasdeinedin22.1.3.16.

Whenthemapmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetObethethisvalue.
2.Perform?ValidateTypedArray(O).
3.LetlenbethevalueofO's[[ArrayLength]]internalslot.
4.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
5.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
6.LetAbe?TypedArraySpeciesCreate(O,len).
7.Letkbe0.
8.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkValuebe?Get(O,Pk).
c.LetmappedValuebe?Call(callbackfn,T,kValue,k,O).
d.Perform?Set(A,Pk,mappedValue,true).
e.Increasekby1.
9.ReturnA.

Thisfunctionisnotgeneric.Thethisvaluemustbeanobjectwitha[[TypedArrayName]]internalslot.

22.2.3.20 %TypedArray%.prototype.reduce(callbackfn[,initialValue])
%TypedArray%.prototype.reduceisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.reduceasdeinedin22.1.3.19exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedin
placeofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethat
thethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,such
optimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithmandmusttakeinto
accountthepossibilitythatcallstocallbackfnmaycausethethisvaluetobecomedetached.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.21 %TypedArray%.prototype.reduceRight(callbackfn[,initialValue])

%TypedArray%.prototype.reduceRightisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.reduceRightasdeinedin22.1.3.20exceptthatthethisobject's[[ArrayLength]]internalslotis
accessedinplaceofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththe
knowledgethatthethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.
However,suchoptimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithmandmust
takeintoaccountthepossibilitythatcallstocallbackfnmaycausethethisvaluetobecomedetached.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.22 %TypedArray%.prototype.reverse()

%TypedArray%.prototype.reverseisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.reverseasdeinedin22.1.3.21exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedin
placeofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethat
thethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,such
optimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.23 %TypedArray%.prototype.set(overloaded[,offset])

%TypedArray%.prototype.setisasinglefunctionwhosebehaviourisoverloadedbaseduponthetypeofitsirst
argument.

Thisfunctionisnotgeneric.Thethisvaluemustbeanobjectwitha[[TypedArrayName]]internalslot.

22.2.3.23.1 %TypedArray%.prototype.set(array[,offset])

SetsmultiplevaluesinthisTypedArray,readingthevaluesfromtheobjectarray.Theoptionaloffsetvalueindicatestheirst
elementindexinthisTypedArraywherevaluesarewritten.Ifomitted,itisassumedtobe0.

1.Assert:arrayisanyECMAScriptlanguagevalueotherthananObjectwitha[[TypedArrayName]]internalslot.Ifitis
suchanObject,thedeinitionin22.2.3.23.2applies.
2.Lettargetbethethisvalue.
3.IfType(target)isnotObject,throwaTypeErrorexception.
4.Iftargetdoesnothavea[[TypedArrayName]]internalslot,throwaTypeErrorexception.
5.Assert:targethasa[[ViewedArrayBuffer]]internalslot.
6.LettargetOffsetbe?ToInteger(offset).
7.IftargetOffset<0,throwaRangeErrorexception.
8.LettargetBufferbethevalueoftarget's[[ViewedArrayBuffer]]internalslot.
9.IfIsDetachedBuffer(targetBuffer)istrue,throwaTypeErrorexception.
10.LettargetLengthbethevalueoftarget's[[ArrayLength]]internalslot.
11.LettargetNamebetheStringvalueoftarget's[[TypedArrayName]]internalslot.
12.LettargetElementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50fortargetName.
13.LettargetTypebetheStringvalueoftheElementTypevalueinTable50fortargetName.
14.LettargetByteOffsetbethevalueoftarget's[[ByteOffset]]internalslot.
15.Letsrcbe?ToObject(array).
16.LetsrcLengthbe?ToLength(?Get(src,"length")).
17.IfsrcLength+targetOffset>targetLength,throwaRangeErrorexception.
18.LettargetByteIndexbetargetOffsettargetElementSize+targetByteOffset.
19.Letkbe0.
20.LetlimitbetargetByteIndex+targetElementSizesrcLength.
21.Repeat,whiletargetByteIndex<limit
a.LetPkbe!ToString(k).
b.LetkNumberbe?ToNumber(?Get(src,Pk)).
c.IfIsDetachedBuffer(targetBuffer)istrue,throwaTypeErrorexception.
d.PerformSetValueInBuffer(targetBuffer,targetByteIndex,targetType,kNumber).
e.Setktok+1.
f.SettargetByteIndextotargetByteIndex+targetElementSize.
22.Returnundeined.

22.2.3.23.2 %TypedArray%.prototype.set(typedArray[,offset])

SetsmultiplevaluesinthisTypedArray,readingthevaluesfromthetypedArrayargumentobject.Theoptionaloffsetvalue
indicatestheirstelementindexinthisTypedArraywherevaluesarewritten.Ifomitted,itisassumedtobe0.

1.Assert:typedArrayhasa[[TypedArrayName]]internalslot.Ifitdoesnot,thedeinitionin22.2.3.23.1applies.
2.Lettargetbethethisvalue.
3.IfType(target)isnotObject,throwaTypeErrorexception.
4.Iftargetdoesnothavea[[TypedArrayName]]internalslot,throwaTypeErrorexception.
5.Assert:targethasa[[ViewedArrayBuffer]]internalslot.
6.LettargetOffsetbe?ToInteger(offset).
7.IftargetOffset<0,throwaRangeErrorexception.
8.LettargetBufferbethevalueoftarget's[[ViewedArrayBuffer]]internalslot.
9.IfIsDetachedBuffer(targetBuffer)istrue,throwaTypeErrorexception.
10.LettargetLengthbethevalueoftarget's[[ArrayLength]]internalslot.
11.LetsrcBufferbethevalueoftypedArray's[[ViewedArrayBuffer]]internalslot.
12.IfIsDetachedBuffer(srcBuffer)istrue,throwaTypeErrorexception.
13.LettargetNamebetheStringvalueoftarget's[[TypedArrayName]]internalslot.
14.LettargetTypebetheStringvalueoftheElementTypevalueinTable50fortargetName.
15.LettargetElementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50fortargetName.
16.LettargetByteOffsetbethevalueoftarget's[[ByteOffset]]internalslot.
17.LetsrcNamebetheStringvalueoftypedArray's[[TypedArrayName]]internalslot.
18.LetsrcTypebetheStringvalueoftheElementTypevalueinTable50forsrcName.
19.LetsrcElementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forsrcName.
20.LetsrcLengthbethevalueoftypedArray's[[ArrayLength]]internalslot.
21.LetsrcByteOffsetbethevalueoftypedArray's[[ByteOffset]]internalslot.
22.IfsrcLength+targetOffset>targetLength,throwaRangeErrorexception.
23.IfSameValue(srcBuffer,targetBuffer)istrue,then
a.LetsrcBufferbe?CloneArrayBuffer(targetBuffer,srcByteOffset,%ArrayBuffer%).
b.NOTE:%ArrayBuffer%isusedtoclonetargetBufferbecauseisitknowntonothaveanyobservablesideeffects.
c.LetsrcByteIndexbe0.
24.Else,letsrcByteIndexbesrcByteOffset.
25.LettargetByteIndexbetargetOffsettargetElementSize+targetByteOffset.
26.LetlimitbetargetByteIndex+targetElementSizesrcLength.
27.IfSameValue(srcType,targetType)isfalse,then
a.Repeat,whiletargetByteIndex<limit
i.LetvaluebeGetValueFromBuffer(srcBuffer,srcByteIndex,srcType).
ii.PerformSetValueInBuffer(targetBuffer,targetByteIndex,targetType,value).
iii.SetsrcByteIndextosrcByteIndex+srcElementSize.
iv.SettargetByteIndextotargetByteIndex+targetElementSize.
28.Else,
a.NOTE:IfsrcTypeandtargetTypearethesame,thetransfermustbeperformedinamannerthatpreservesthebit
levelencodingofthesourcedata.
b.Repeat,whiletargetByteIndex<limit
i.LetvaluebeGetValueFromBuffer(srcBuffer,srcByteIndex,"Uint8").
ii.PerformSetValueInBuffer(targetBuffer,targetByteIndex,"Uint8",value).
iii.SetsrcByteIndextosrcByteIndex+1.
iv.SettargetByteIndextotargetByteIndex+1.
29.Returnundeined.

22.2.3.24 %TypedArray%.prototype.slice(start,end)

Theinterpretationanduseoftheargumentsof%TypedArray%.prototype.slicearethesameasfor
Array.prototype.sliceasdeinedin22.1.3.23.Thefollowingstepsaretaken:

1.LetObethethisvalue.
2.Perform?ValidateTypedArray(O).
3.LetlenbethevalueofO's[[ArrayLength]]internalslot.
4.LetrelativeStartbe?ToInteger(start).
5.IfrelativeStart<0,letkbemax((len+relativeStart),0);elseletkbemin(relativeStart,len).
6.Ifendisundeined,letrelativeEndbelen;elseletrelativeEndbe?ToInteger(end).
7.IfrelativeEnd<0,letinalbemax((len+relativeEnd),0);elseletinalbemin(relativeEnd,len).
8.Letcountbemax(inalk,0).
9.LetAbe?TypedArraySpeciesCreate(O,count).
10.LetsrcNamebetheStringvalueofO's[[TypedArrayName]]internalslot.
11.LetsrcTypebetheStringvalueoftheElementTypevalueinTable50forsrcName.
12.LettargetNamebetheStringvalueofA's[[TypedArrayName]]internalslot.
13.LettargetTypebetheStringvalueoftheElementTypevalueinTable50fortargetName.
14.IfSameValue(srcType,targetType)isfalse,then
a.Letnbe0.
b.Repeat,whilek<inal
i.LetPkbe!ToString(k).
ii.LetkValuebe?Get(O,Pk).
iii.Perform?Set(A,!ToString(n),kValue,true).
iv.Increasekby1.
v.Increasenby1.
15.Elseifcount>0,then
a.LetsrcBufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
b.IfIsDetachedBuffer(srcBuffer)istrue,throwaTypeErrorexception.
c.LettargetBufferbethevalueofA's[[ViewedArrayBuffer]]internalslot.
d.LetelementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forsrcType.
e.NOTE:IfsrcTypeandtargetTypearethesame,thetransfermustbeperformedinamannerthatpreservesthebit
levelencodingofthesourcedata.
f.LetsrcByteOffetbethevalueofO's[[ByteOffset]]internalslot.
g.LettargetByteIndexbeA's[[ByteOffset]]internalslot.
h.LetsrcByteIndexbe(kelementSize)+srcByteOffet.
i.LetlimitbetargetByteIndex+countelementSize.
j.Repeat,whiletargetByteIndex<limit
i.LetvaluebeGetValueFromBuffer(srcBuffer,srcByteIndex,"Uint8").
ii.PerformSetValueInBuffer(targetBuffer,targetByteIndex,"Uint8",value).
iii.IncreasesrcByteIndexby1.
iv.IncreasetargetByteIndexby1.
16.ReturnA.
Thisfunctionisnotgeneric.Thethisvaluemustbeanobjectwitha[[TypedArrayName]]internalslot.

22.2.3.25 %TypedArray%.prototype.some(callbackfn[,thisArg])

%TypedArray%.prototype.someisadistinctfunctionthatimplementsthesamealgorithmasArray.prototype.someas
deinedin22.1.3.24exceptthatthethisobject's[[ArrayLength]]internalslotisaccessedinplaceofperforminga[[Get]]of
"length".Theimplementationofthealgorithmmaybeoptimizedwiththeknowledgethatthethisvalueisanobjectthat
hasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.However,suchoptimizationmustnotintroduceany
observablechangesinthespeciiedbehaviourofthealgorithmandmusttakeintoaccountthepossibilitythatcallsto
callbackfnmaycausethethisvaluetobecomedetached.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

22.2.3.26 %TypedArray%.prototype.sort(comparefn)

%TypedArray%.prototype.sortisadistinctfunctionthat,exceptasdescribedbelow,implementsthesamerequirements
asthoseofArray.prototype.sortasdeinedin22.1.3.25.Theimplementationofthe%TypedArray%.prototype.sort
speciicationmaybeoptimizedwiththeknowledgethatthethisvalueisanobjectthathasaixedlengthandwhoseinteger
indexedpropertiesarenotsparse.Theonlyinternalmethodsofthethisobjectthatthealgorithmmaycallare[[Get]]and
[[Set]].

Thisfunctionisnotgeneric.Thethisvaluemustbeanobjectwitha[[TypedArrayName]]internalslot.

Uponentry,thefollowingstepsareperformedtoinitializeevaluationofthesortfunction.Thesestepsareusedinsteadof
theentrystepsin22.1.3.25:

1.Letobjbethethisvalue.
2.Letbufferbe?ValidateTypedArray(obj).
3.Letlenbethevalueofobj's[[ArrayLength]]internalslot.

Theimplementationdeinedsortorderconditionforexoticobjectsisnotappliedby%TypedArray%.prototype.sort.

ThefollowingversionofSortCompareisusedby%TypedArray%.prototype.sort.Itperformsanumericcomparison
ratherthanthestringcomparisonusedin22.1.3.25.SortComparehasaccesstothecomparefnandbuffervaluesofthe
currentinvocationofthesortmethod.

WhentheTypedArraySortCompareabstractoperationiscalledwithtwoargumentsxandy,thefollowingstepsaretaken:

1.Assert:BothType(x)andType(y)isNumber.
2.Iftheargumentcomparefnisnotundeined,then
a.Letvbe?Call(comparefn,undeined,x,y).
b.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
c.IfvisNaN,return+0.
d.Returnv.
3.IfxandyarebothNaN,return+0.
4.IfxisNaN,return1.
5.IfyisNaN,return1.
6.Ifx<y,return1.
7.Ifx>y,return1.
8.Ifxis0andyis+0,return1.
9.Ifxis+0andyis0,return1.
10.Return+0.

NOTE BecauseNaNalwayscomparesgreaterthananyothervalue,NaNpropertyvaluesalwayssorttotheendofthe
resultwhencomparefnisnotprovided.

22.2.3.27 %TypedArray%.prototype.subarray(begin,end)
ReturnsanewTypedArrayobjectwhoseelementtypeisthesameasthisTypedArrayandwhoseArrayBufferisthesameas
theArrayBufferofthisTypedArray,referencingtheelementsatbegin,inclusive,uptoend,exclusive.Ifeitherbeginorendis
negative,itreferstoanindexfromtheendofthearray,asopposedtofromthebeginning.

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[TypedArrayName]]internalslot,throwaTypeErrorexception.
4.Assert:Ohasa[[ViewedArrayBuffer]]internalslot.
5.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
6.LetsrcLengthbethevalueofO's[[ArrayLength]]internalslot.
7.LetrelativeBeginbe?ToInteger(begin).
8.IfrelativeBegin<0,letbeginIndexbemax((srcLength+relativeBegin),0);elseletbeginIndexbemin(relativeBegin,
srcLength).
9.Ifendisundeined,letrelativeEndbesrcLength;else,letrelativeEndbe?ToInteger(end).
10.IfrelativeEnd<0,letendIndexbemax((srcLength+relativeEnd),0);elseletendIndexbemin(relativeEnd,srcLength).
11.LetnewLengthbemax(endIndexbeginIndex,0).
12.LetconstructorNamebetheStringvalueofO's[[TypedArrayName]]internalslot.
13.LetelementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forconstructorName.
14.LetsrcByteOffsetbethevalueofO's[[ByteOffset]]internalslot.
15.LetbeginByteOffsetbesrcByteOffset+beginIndexelementSize.
16.LetargumentsListbebuffer,beginByteOffset,newLength.
17.Return?TypedArraySpeciesCreate(O,argumentsList).

Thisfunctionisnotgeneric.Thethisvaluemustbeanobjectwitha[[TypedArrayName]]internalslot.

22.2.3.28 %TypedArray%.prototype.toLocaleString([reserved1[,reserved2]])

%TypedArray%.prototype.toLocaleStringisadistinctfunctionthatimplementsthesamealgorithmas
Array.prototype.toLocaleStringasdeinedin22.1.3.27exceptthatthethisobject's[[ArrayLength]]internalslotis
accessedinplaceofperforminga[[Get]]of"length".Theimplementationofthealgorithmmaybeoptimizedwiththe
knowledgethatthethisvalueisanobjectthathasaixedlengthandwhoseintegerindexedpropertiesarenotsparse.
However,suchoptimizationmustnotintroduceanyobservablechangesinthespeciiedbehaviourofthealgorithm.

Thisfunctionisnotgeneric.ValidateTypedArrayisappliedtothethisvaluepriortoevaluatingthealgorithm.Ifitsresultis
anabruptcompletionthatexceptionisthrowninsteadofevaluatingthealgorithm.

NOTE IftheECMAScriptimplementationincludestheECMA402InternationalizationAPIthisfunctionisbasedupon
thealgorithmforArray.prototype.toLocaleStringthatisintheECMA402speciication.

22.2.3.29 %TypedArray%.prototype.toString()

Theinitialvalueofthe%TypedArray%.prototype.toStringdatapropertyisthesamebuiltinfunctionobjectasthe
Array.prototype.toStringmethoddeinedin22.1.3.28.

22.2.3.30 %TypedArray%.prototype.values()

Thefollowingstepsaretaken:

1.LetObethethisvalue.
2.Perform?ValidateTypedArray(O).
3.ReturnCreateArrayIterator(O,"value").

22.2.3.31 %TypedArray%.prototype[@@iterator]()

Theinitialvalueofthe@@iteratorpropertyisthesamefunctionobjectastheinitialvalueofthe
%TypedArray%.prototype.valuesproperty.

22.2.3.32 get%TypedArray%.prototype[@@toStringTag]
%TypedArray%.prototype[@@toStringTag]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsget
accessorfunctionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,returnundeined.
3.IfOdoesnothavea[[TypedArrayName]]internalslot,returnundeined.
4.LetnamebethevalueofO's[[TypedArrayName]]internalslot.
5.Assert:nameisaStringvalue.
6.Returnname.

Thispropertyhastheattributes{[[Enumerable]]:false,[[Conigurable]]:true}.

Theinitialvalueofthenamepropertyofthisfunctionis"get[Symbol.toStringTag]".

22.2.4 TheTypedArrayConstructors

EachoftheTypedArrayconstructorobjectsisanintrinsicobjectthathasthestructuredescribedbelow,differingonlyinthe
nameusedastheconstructornameinsteadofTypedArray,inTable50.

TheTypedArrayintrinsicconstructorfunctionsaresinglefunctionswhosebehaviourisoverloadedbaseduponthenumber
andtypesofitsarguments.TheactualbehaviourofacallofTypedArraydependsuponthenumberandkindofarguments
thatarepassedtoit.

TheTypedArrayconstructorsarenotintendedtobecalledasafunctionandwillthrowanexceptionwhencalledinthat
manner.

TheTypedArrayconstructorsaredesignedtobesubclassable.Theymaybeusedasthevalueofanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedTypedArraybehaviourmustincludeasupercalltothe
TypedArrayconstructortocreateandinitializethesubclassinstancewiththeinternalstatenecessarytosupportthe
%TypedArray%.prototypebuiltinmethods.

ThelengthpropertyoftheTypedArrayconstructorfunctionis3.

22.2.4.1 TypedArray()

ThisdescriptionappliesonlyiftheTypedArrayfunctioniscalledwithnoarguments.

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.LetconstructorNamebetheStringvalueoftheConstructorNamevaluespeciiedinTable50forthisTypedArray
constructor.
3.Return?AllocateTypedArray(constructorName,NewTarget,"%TypedArrayPrototype%",0).

22.2.4.2 TypedArray(length)

ThisdescriptionappliesonlyiftheTypedArrayfunctioniscalledwithatleastoneargumentandtheTypeoftheirst
argumentisnotObject.

TypedArraycalledwithargumentlengthperformsthefollowingsteps:

1.Assert:Type(length)isnotObject.
2.IfNewTargetisundeined,throwaTypeErrorexception.
3.Iflengthisundeined,throwaTypeErrorexception.
4.LetnumberLengthbe?ToNumber(length).
5.LetelementLengthbeToLength(numberLength).
6.IfSameValueZero(numberLength,elementLength)isfalse,throwaRangeErrorexception.
7.LetconstructorNamebetheStringvalueoftheConstructorNamevaluespeciiedinTable50forthisTypedArray
constructor.
8.Return?AllocateTypedArray(constructorName,NewTarget,"%TypedArrayPrototype%",elementLength).
22.2.4.2.1 RuntimeSemantics:AllocateTypedArray(constructorName,newTarget,defaultProto[,length])

TheabstractoperationAllocateTypedArraywithargumentsconstructorName,newTarget,defaultProtoandoptional
argumentlengthisusedtovalidateandcreateaninstanceofaTypedArrayconstructor.constructorNameisrequiredtobe
thenameofaTypedArrayconstructorinTable50.IfthelengthargumentispassedanArrayBufferofthatlengthisalso
allocatedandassociatedwiththenewTypedArrayinstance.AllocateTypedArrayprovidescommonsemanticsthatisusedby
alloftheTypedArrayoverloads.AllocateTypedArrayperformsthefollowingsteps:

1.Letprotobe?GetPrototypeFromConstructor(newTarget,defaultProto).
2.LetobjbeIntegerIndexedObjectCreate(proto,[[ViewedArrayBuffer]],[[TypedArrayName]],[[ByteLength]],
[[ByteOffset]],[[ArrayLength]]).
3.Assert:The[[ViewedArrayBuffer]]internalslotofobjisundeined.
4.Setobj's[[TypedArrayName]]internalslottoconstructorName.
5.Iflengthwasnotpassed,then
a.Setobj's[[ByteLength]]internalslotto0.
b.Setobj's[[ByteOffset]]internalslotto0.
c.Setobj's[[ArrayLength]]internalslotto0.
6.Else,
a.Perform?AllocateTypedArrayBuffer(obj,length).
7.Returnobj.

22.2.4.2.2 RuntimeSemantics:AllocateTypedArrayBuffer(O,length)

TheabstractoperationAllocateTypedArrayBufferwithargumentsOandlengthallocatesandassociatesanArrayBufferwith
theTypedArrayinstanceO.Itperformsthefollowingsteps:

1.Assert:OisanObjectthathasa[[ViewedArrayBuffer]]internalslot.
2.Assert:The[[ViewedArrayBuffer]]internalslotofOisundeined.
3.Assert:length0.
4.LetconstructorNamebetheStringvalueofO's[[TypedArrayName]]internalslot.
5.LetelementSizebetheElementSizevalueinTable50forconstructorName.
6.LetbyteLengthbeelementSizelength.
7.Letdatabe?AllocateArrayBuffer(%ArrayBuffer%,byteLength).
8.SetO's[[ViewedArrayBuffer]]internalslottodata.
9.SetO's[[ByteLength]]internalslottobyteLength.
10.SetO's[[ByteOffset]]internalslotto0.
11.SetO's[[ArrayLength]]internalslottolength.
12.ReturnO.

22.2.4.3 TypedArray(typedArray)

ThisdescriptionappliesonlyiftheTypedArrayfunctioniscalledwithatleastoneargumentandtheTypeoftheirst
argumentisObjectandthatobjecthasa[[TypedArrayName]]internalslot.

TypedArraycalledwithargumenttypedArrayperformsthefollowingsteps:

1.Assert:Type(typedArray)isObjectandtypedArrayhasa[[TypedArrayName]]internalslot.
2.IfNewTargetisundeined,throwaTypeErrorexception.
3.LetconstructorNamebetheStringvalueoftheConstructorNamevaluespeciiedinTable50forthisTypedArray
constructor.
4.LetObe?AllocateTypedArray(constructorName,NewTarget,"%TypedArrayPrototype%").
5.LetsrcArraybetypedArray.
6.LetsrcDatabethevalueofsrcArray's[[ViewedArrayBuffer]]internalslot.
7.IfIsDetachedBuffer(srcData)istrue,throwaTypeErrorexception.
8.LetconstructorNamebetheStringvalueofO's[[TypedArrayName]]internalslot.
9.LetelementTypebetheStringvalueoftheElementTypevalueinTable50forconstructorName.
10.LetelementLengthbethevalueofsrcArray's[[ArrayLength]]internalslot.
11.LetsrcNamebetheStringvalueofsrcArray's[[TypedArrayName]]internalslot.
12.LetsrcTypebetheStringvalueoftheElementTypevalueinTable50forsrcName.
13.LetsrcElementSizebetheElementSizevalueinTable50forsrcName.
14.LetsrcByteOffsetbethevalueofsrcArray's[[ByteOffset]]internalslot.
15.LetelementSizebetheElementSizevalueinTable50forconstructorName.
16.LetbyteLengthbeelementSizeelementLength.
17.IfSameValue(elementType,srcType)istrue,then
a.Letdatabe?CloneArrayBuffer(srcData,srcByteOffset).
18.Else,
a.LetbufferConstructorbe?SpeciesConstructor(srcData,%ArrayBuffer%).
b.Letdatabe?AllocateArrayBuffer(bufferConstructor,byteLength).
c.IfIsDetachedBuffer(srcData)istrue,throwaTypeErrorexception.
d.LetsrcByteIndexbesrcByteOffset.
e.LettargetByteIndexbe0.
f.LetcountbeelementLength.
g.Repeat,whilecount>0
i.LetvaluebeGetValueFromBuffer(srcData,srcByteIndex,srcType).
ii.PerformSetValueInBuffer(data,targetByteIndex,elementType,value).
iii.SetsrcByteIndextosrcByteIndex+srcElementSize.
iv.SettargetByteIndextotargetByteIndex+elementSize.
v.Decrementcountby1.
19.SetO's[[ViewedArrayBuffer]]internalslottodata.
20.SetO's[[ByteLength]]internalslottobyteLength.
21.SetO's[[ByteOffset]]internalslotto0.
22.SetO's[[ArrayLength]]internalslottoelementLength.
23.ReturnO.

22.2.4.4 TypedArray(object)

ThisdescriptionappliesonlyiftheTypedArrayfunctioniscalledwithatleastoneargumentandtheTypeoftheirst
argumentisObjectandthatobjectdoesnothaveeithera[[TypedArrayName]]oran[[ArrayBufferData]]internalslot.

TypedArraycalledwithargumentobjectperformsthefollowingsteps:

1.Assert:Type(object)isObjectandobjectdoesnothaveeithera[[TypedArrayName]]oran[[ArrayBufferData]]internal
slot.
2.IfNewTargetisundeined,throwaTypeErrorexception.
3.LetconstructorNamebetheStringvalueoftheConstructorNamevaluespeciiedinTable50forthisTypedArray
constructor.
4.LetObe?AllocateTypedArray(constructorName,NewTarget,"%TypedArrayPrototype%").
5.LetarrayLikebe?IterableToArrayLike(object).
6.Letlenbe?ToLength(?Get(arrayLike,"length")).
7.Perform?AllocateTypedArrayBuffer(O,len).
8.Letkbe0.
9.Repeat,whilek<len
a.LetPkbe!ToString(k).
b.LetkValuebe?Get(arrayLike,Pk).
c.Perform?Set(O,Pk,kValue,true).
d.Increasekby1.
10.ReturnO.

22.2.4.5 TypedArray(buffer[,byteOffset[,length]])

ThisdescriptionappliesonlyiftheTypedArrayfunctioniscalledwithatleastoneargumentandtheTypeoftheirst
argumentisObjectandthatobjecthasan[[ArrayBufferData]]internalslot.
TypedArraycalledwithargumentsbuffer,byteOffset,andlengthperformsthefollowingsteps:

1.Assert:Type(buffer)isObjectandbufferhasan[[ArrayBufferData]]internalslot.
2.IfNewTargetisundeined,throwaTypeErrorexception.
3.LetconstructorNamebetheStringvalueoftheConstructorNamevaluespeciiedinTable50forthisTypedArray
constructor.
4.LetObe?AllocateTypedArray(constructorName,NewTarget,"%TypedArrayPrototype%").
5.LetconstructorNamebetheStringvalueofO's[[TypedArrayName]]internalslot.
6.LetelementSizebetheNumbervalueoftheElementSizevalueinTable50forconstructorName.
7.Letoffsetbe?ToInteger(byteOffset).
8.Ifoffset<0,throwaRangeErrorexception.
9.Ifoffsetis0,letoffsetbe+0.
10.IfoffsetmoduloelementSize0,throwaRangeErrorexception.
11.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
12.LetbufferByteLengthbethevalueofbuffer's[[ArrayBufferByteLength]]internalslot.
13.Iflengthisundeined,then
a.IfbufferByteLengthmoduloelementSize0,throwaRangeErrorexception.
b.LetnewByteLengthbebufferByteLengthoffset.
c.IfnewByteLength<0,throwaRangeErrorexception.
14.Else,
a.LetnewLengthbe?ToLength(length).
b.LetnewByteLengthbenewLengthelementSize.
c.Ifoffset+newByteLength>bufferByteLength,throwaRangeErrorexception.
15.SetO's[[ViewedArrayBuffer]]internalslottobuffer.
16.SetO's[[ByteLength]]internalslottonewByteLength.
17.SetO's[[ByteOffset]]internalslottooffset.
18.SetO's[[ArrayLength]]internalslottonewByteLength/elementSize.
19.ReturnO.

22.2.4.6 TypedArrayCreate(constructor,argumentList)

TheabstractoperationTypedArrayCreatewithargumentsconstructorandargumentListisusedtospecifythecreationofa
newTypedArrayobjectusingaconstructorfunction.Itperformsthefollowingsteps:

1.LetnewTypedArraybe?Construct(constructor,argumentList).
2.Perform?ValidateTypedArray(newTypedArray).
3.IfargumentListisaListofasingleNumber,then
a.IfthevalueofnewTypedArray's[[ArrayLength]]internalslot<argumentList[0],throwaTypeErrorexception.
4.ReturnnewTypedArray.

22.2.4.7 TypedArraySpeciesCreate(exemplar,argumentList)

TheabstractoperationTypedArraySpeciesCreatewithargumentsexemplarandargumentListisusedtospecifythecreation
ofanewTypedArrayobjectusingaconstructorfunctionthatisderivedfromexemplar.Itperformsthefollowingsteps:

1.Assert:exemplarisanObjectthathasa[[TypedArrayName]]internalslot.
2.LetdefaultConstructorbetheintrinsicobjectlistedincolumnoneofTable50forthevalueofexemplar's
[[TypedArrayName]]internalslot.
3.Letconstructorbe?SpeciesConstructor(exemplar,defaultConstructor).
4.Return?TypedArrayCreate(constructor,argumentList).

22.2.5 PropertiesoftheTypedArrayConstructors

Thevalueofthe[[Prototype]]internalslotofeachTypedArrayconstructoristhe%TypedArray%intrinsicobject.

EachTypedArrayconstructorhasanamepropertywhosevalueistheStringvalueoftheconstructornamespeciiedforitin
Table50.
EachTypedArrayconstructorhasthefollowingproperties:

22.2.5.1 TypedArray.BYTES_PER_ELEMENT

ThevalueofTypedArray.BYTES_PER_ELEMENTistheNumbervalueoftheElementSizevaluespeciiedinTable50for
TypedArray.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

22.2.5.2 TypedArray.prototype

TheinitialvalueofTypedArray.prototypeisthecorrespondingTypedArrayprototypeintrinsicobject(22.2.6).

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

22.2.6 PropertiesofTypedArrayPrototypeObjects

Thevalueofthe[[Prototype]]internalslotofaTypedArrayprototypeobjectistheintrinsicobject%TypedArrayPrototype%.
ATypedArrayprototypeobjectisanordinaryobject.Itdoesnothavea[[ViewedArrayBuffer]]oranyotheroftheinternal
slotsthatarespeciictoTypedArrayinstanceobjects.

22.2.6.1 TypedArray.prototype.BYTES_PER_ELEMENT

ThevalueofTypedArray.prototype.BYTES_PER_ELEMENTistheNumbervalueoftheElementSizevaluespeciiedin
Table50forTypedArray.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

22.2.6.2 TypedArray.prototype.constructor

TheinitialvalueofaTypedArray.prototype.constructoristhecorresponding%TypedArray%intrinsicobject.

22.2.7 PropertiesofTypedArrayInstances

TypedArrayinstancesareIntegerIndexedexoticobjects.EachTypedArrayinstanceinheritspropertiesfromthe
correspondingTypedArrayprototypeobject.EachTypedArrayinstancehasthefollowinginternalslots:[[TypedArrayName]],
[[ViewedArrayBuffer]],[[ByteLength]],[[ByteOffset]],and[[ArrayLength]].

23 KeyedCollection
23.1 MapObjects
Mapobjectsarecollectionsofkey/valuepairswhereboththekeysandvaluesmaybearbitraryECMAScriptlanguagevalues.
Adistinctkeyvaluemayonlyoccurinonekey/valuepairwithintheMap'scollection.Distinctkeyvaluesarediscriminated
usingtheSameValueZerocomparisonalgorithm.

Mapobjectmustbeimplementedusingeitherhashtablesorothermechanismsthat,onaverage,provideaccesstimesthat
aresublinearonthenumberofelementsinthecollection.ThedatastructuresusedinthisMapobjectsspeciicationisonly
intendedtodescribetherequiredobservablesemanticsofMapobjects.Itisnotintendedtobeaviableimplementation
model.

23.1.1 TheMapConstructor

TheMapconstructoristhe%Map%intrinsicobjectandtheinitialvalueoftheMappropertyoftheglobalobject.Whencalled
asaconstructoritcreatesandinitializesanewMapobject.Mapisnotintendedtobecalledasafunctionandwillthrowan
exceptionwhencalledinthatmanner.
TheMapconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueinanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedMapbehaviourmustincludeasupercalltotheMapconstructorto
createandinitializethesubclassinstancewiththeinternalstatenecessarytosupporttheMap.prototypebuiltinmethods.

23.1.1.1 Map([iterable])

WhentheMapfunctioniscalledwithoptionalargument,thefollowingstepsaretaken:

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.Letmapbe?OrdinaryCreateFromConstructor(NewTarget,"%MapPrototype%",[[MapData]]).
3.Setmap's[[MapData]]internalslottoanewemptyList.
4.Ifiterableisnotpresent,letiterablebeundeined.
5.Ifiterableiseitherundeinedornull,letiterbeundeined.
6.Else,
a.Letadderbe?Get(map,"set").
b.IfIsCallable(adder)isfalse,throwaTypeErrorexception.
c.Letiterbe?GetIterator(iterable).
7.Ifiterisundeined,returnmap.
8.Repeat
a.Letnextbe?IteratorStep(iter).
b.Ifnextisfalse,returnmap.
c.LetnextItembe?IteratorValue(next).
d.IfType(nextItem)isnotObject,then
i.LeterrorbeCompletion{[[Type]]:throw,[[Value]]:anewlycreatedTypeErrorobject,[[Target]]:empty}.
ii.Return?IteratorClose(iter,error).
e.LetkbeGet(nextItem,"0").
f.Ifkisanabruptcompletion,return?IteratorClose(iter,k).
g.LetvbeGet(nextItem,"1").
h.Ifvisanabruptcompletion,return?IteratorClose(iter,v).
i.LetstatusbeCall(adder,map,k.[[Value]],v.[[Value]]).
j.Ifstatusisanabruptcompletion,return?IteratorClose(iter,status).

NOTE Iftheparameteriterableispresent,itisexpectedtobeanobjectthatimplementsan@@iteratormethodthat
returnsaniteratorobjectthatproducesatwoelementarraylikeobjectwhoseirstelementisavaluethatwill
beusedasaMapkeyandwhosesecondelementisthevaluetoassociatewiththatkey.

23.1.2 PropertiesoftheMapConstructor

Thevalueofthe[[Prototype]]internalslotoftheMapconstructoristheintrinsicobject%FunctionPrototype%.

TheMapconstructorhasthefollowingproperties:

23.1.2.1 Map.prototype

TheinitialvalueofMap.prototypeistheintrinsicobject%MapPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

23.1.2.2 getMap[@@species]

Map[@@species]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunctionperformsthe
followingsteps:

1.Returnthethisvalue.

Thevalueofthenamepropertyofthisfunctionis"get[Symbol.species]".
NOTE Methodsthatcreatederivedcollectionobjectsshouldcall@@speciestodeterminetheconstructortouseto
createthederivedobjects.Subclassconstructormayoverride@@speciestochangethedefaultconstructor
assignment.

23.1.3 PropertiesoftheMapPrototypeObject

TheMapprototypeobjectistheintrinsicobject%MapPrototype%.Thevalueofthe[[Prototype]]internalslotoftheMap
prototypeobjectistheintrinsicobject%ObjectPrototype%.TheMapprototypeobjectisanordinaryobject.Itdoesnothave
a[[MapData]]internalslot.

23.1.3.1 Map.prototype.clear()

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[MapData]]internalslot.
5.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Setp.[[Key]]toempty.
b.Setp.[[Value]]toempty.
6.Returnundeined.

NOTE Theexisting[[MapData]]ListispreservedbecausetheremaybeexistingMapIteratorobjectsthatare
suspendedmidwaythroughiteratingoverthatList.

23.1.3.2 Map.prototype.constructor

TheinitialvalueofMap.prototype.constructoristheintrinsicobject%Map%.

23.1.3.3 Map.prototype.delete(key)

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[MapData]]internalslot.
5.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValueZero(p.[[Key]],key)istrue,then
i.Setp.[[Key]]toempty.
ii.Setp.[[Value]]toempty.
iii.Returntrue.
6.Returnfalse.

NOTE Thevalueemptyisusedasaspeciicationdevicetoindicatethatanentryhasbeendeleted.Actual
implementationsmaytakeotheractionssuchasphysicallyremovingtheentryfrominternaldatastructures.

23.1.3.4 Map.prototype.entries()

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.Return?CreateMapIterator(M,"key+value").

23.1.3.5 Map.prototype.forEach(callbackfn[,thisArg])

WhentheforEachmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:
1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
4.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
5.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
6.LetentriesbetheListthatisthevalueofM's[[MapData]]internalslot.
7.RepeatforeachRecord{[[Key]],[[Value]]}ethatisanelementofentries,inoriginalkeyinsertionorder
a.Ife.[[Key]]isnotempty,then
i.Perform?Call(callbackfn,T,e.[[Value]],e.[[Key]],M).
8.Returnundeined.

NOTE callbackfnshouldbeafunctionthatacceptsthreearguments.forEachcallscallbackfnonceforeachkey/value
pairpresentinthemapobject,inkeyinsertionorder.callbackfniscalledonlyforkeysofthemapwhich
actuallyexist;itisnotcalledforkeysthathavebeendeletedfromthemap.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofcallbackfn.Ifitisnot
provided,undeinedisusedinstead.

callbackfniscalledwiththreearguments:thevalueoftheitem,thekeyoftheitem,andtheMapobjectbeing
traversed.

forEachdoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.Eachentryofamap's[[MapData]]isonlyvisitedonce.NewkeysaddedafterthecalltoforEach
beginsarevisited.Akeywillberevisitedifitisdeletedafterithasbeenvisitedandthenreaddedbeforethe
forEachcallcompletes.KeysthataredeletedafterthecalltoforEachbeginsandbeforebeingvisitedarenot
visitedunlessthekeyisaddedagainbeforetheforEachcallcompletes.

23.1.3.6 Map.prototype.get(key)

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[MapData]]internalslot.
5.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValueZero(p.[[Key]],key)istrue,returnp.[[Value]].
6.Returnundeined.

23.1.3.7 Map.prototype.has(key)

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[MapData]]internalslot.
5.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValueZero(p.[[Key]],key)istrue,returntrue.
6.Returnfalse.

23.1.3.8 Map.prototype.keys()

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.Return?CreateMapIterator(M,"key").
23.1.3.9 Map.prototype.set(key,value)

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[MapData]]internalslot.
5.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValueZero(p.[[Key]],key)istrue,then
i.Setp.[[Value]]tovalue.
ii.ReturnM.
6.Ifkeyis0,letkeybe+0.
7.LetpbetheRecord{[[Key]]:key,[[Value]]:value}.
8.Appendpasthelastelementofentries.
9.ReturnM.

23.1.3.10 getMap.prototype.size

Map.prototype.sizeisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunctionperformsthe
followingsteps:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[MapData]]internalslot.
5.Letcountbe0.
6.ForeachRecord{[[Key]],[[Value]]}pthatisanelementofentries
a.Ifp.[[Key]]isnotempty,setcounttocount+1.
7.Returncount.

23.1.3.11 Map.prototype.values()

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.Return?CreateMapIterator(M,"value").

23.1.3.12 Map.prototype[@@iterator]()

Theinitialvalueofthe@@iteratorpropertyisthesamefunctionobjectastheinitialvalueoftheentriesproperty.

23.1.3.13 Map.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"Map".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

23.1.4 PropertiesofMapInstances

MapinstancesareordinaryobjectsthatinheritpropertiesfromtheMapprototype.Mapinstancesalsohavea[[MapData]]
internalslot.

23.1.5 MapIteratorObjects

AMapIteratorisanobject,thatrepresentsaspeciiciterationoversomespeciicMapinstanceobject.Thereisnotanamed
constructorforMapIteratorobjects.Instead,mapiteratorobjectsarecreatedbycallingcertainmethodsofMapinstance
objects.
23.1.5.1 CreateMapIteratorAbstractOperation

SeveralmethodsofMapobjectsreturnIteratorobjects.TheabstractoperationCreateMapIteratorwithargumentsmapand
kindisusedtocreatesuchiteratorobjects.Itperformsthefollowingsteps:

1.IfType(map)isnotObject,throwaTypeErrorexception.
2.Ifmapdoesnothavea[[MapData]]internalslot,throwaTypeErrorexception.
3.LetiteratorbeObjectCreate(%MapIteratorPrototype%,[[Map]],[[MapNextIndex]],[[MapIterationKind]]).
4.Setiterator's[[Map]]internalslottomap.
5.Setiterator's[[MapNextIndex]]internalslotto0.
6.Setiterator's[[MapIterationKind]]internalslottokind.
7.Returniterator.

23.1.5.2 The%MapIteratorPrototype%Object

AllMapIteratorObjectsinheritpropertiesfromthe%MapIteratorPrototype%intrinsicobject.The%MapIteratorPrototype%
intrinsicobjectisanordinaryobjectandits[[Prototype]]internalslotisthe%IteratorPrototype%intrinsicobject.In
addition,%MapIteratorPrototype%hasthefollowingproperties:

23.1.5.2.1 %MapIteratorPrototype%.next()

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavealloftheinternalslotsofaMapIteratorInstance(23.1.5.3),throwaTypeErrorexception.
4.Letmbethevalueofthe[[Map]]internalslotofO.
5.Letindexbethevalueofthe[[MapNextIndex]]internalslotofO.
6.LetitemKindbethevalueofthe[[MapIterationKind]]internalslotofO.
7.Ifmisundeined,returnCreateIterResultObject(undeined,true).
8.Assert:mhasa[[MapData]]internalslot.
9.LetentriesbetheListthatisthevalueofthe[[MapData]]internalslotofm.
10.Repeatwhileindexislessthanthetotalnumberofelementsofentries.Thenumberofelementsmustberedetermined
eachtimethismethodisevaluated.
a.LetebetheRecord{[[Key]],[[Value]]}thatisthevalueofentries[index].
b.Setindextoindex+1.
c.Setthe[[MapNextIndex]]internalslotofOtoindex.
d.Ife.[[Key]]isnotempty,then
i.IfitemKindis"key",letresultbee.[[Key]].
ii.ElseifitemKindis"value",letresultbee.[[Value]].
iii.Else,
1.Assert:itemKindis"key+value".
2.LetresultbeCreateArrayFromList(e.[[Key]],e.[[Value]]).
iv.ReturnCreateIterResultObject(result,false).
11.Setthe[[Map]]internalslotofOtoundeined.
12.ReturnCreateIterResultObject(undeined,true).

23.1.5.2.2 %MapIteratorPrototype%[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"MapIterator".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

23.1.5.3 PropertiesofMapIteratorInstances

MapIteratorinstancesareordinaryobjectsthatinheritpropertiesfromthe%MapIteratorPrototype%intrinsicobject.Map
IteratorinstancesareinitiallycreatedwiththeinternalslotsdescribedinTable51.
Table51:InternalSlotsofMapIteratorInstances
InternalSlot Description

[[Map]] TheMapobjectthatisbeingiterated.

[[MapNextIndex]] TheintegerindexofthenextMapdataelementtobeexaminedbythisiterator.

[[MapIterationKind]] AStringvaluethatidentiieswhatistobereturnedforeachelementoftheiteration.Thepossible
valuesare:"key","value","key+value".

23.2 SetObjects
SetobjectsarecollectionsofECMAScriptlanguagevalues.AdistinctvaluemayonlyoccuronceasanelementofaSet's
collection.DistinctvaluesarediscriminatedusingtheSameValueZerocomparisonalgorithm.

Setobjectsmustbeimplementedusingeitherhashtablesorothermechanismsthat,onaverage,provideaccesstimesthat
aresublinearonthenumberofelementsinthecollection.ThedatastructuresusedinthisSetobjectsspeciicationisonly
intendedtodescribetherequiredobservablesemanticsofSetobjects.Itisnotintendedtobeaviableimplementation
model.

23.2.1 TheSetConstructor

TheSetconstructoristhe%Set%intrinsicobjectandtheinitialvalueoftheSetpropertyoftheglobalobject.Whencalledas
aconstructoritcreatesandinitializesanewSetobject.Setisnotintendedtobecalledasafunctionandwillthrowan
exceptionwhencalledinthatmanner.

TheSetconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueinanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedSetbehaviourmustincludeasupercalltotheSetconstructorto
createandinitializethesubclassinstancewiththeinternalstatenecessarytosupporttheSet.prototypebuiltinmethods.

23.2.1.1 Set([iterable])

WhentheSetfunctioniscalledwithoptionalargumentiterable,thefollowingstepsaretaken:

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.Letsetbe?OrdinaryCreateFromConstructor(NewTarget,"%SetPrototype%",[[SetData]]).
3.Setset's[[SetData]]internalslottoanewemptyList.
4.Ifiterableisnotpresent,letiterablebeundeined.
5.Ifiterableiseitherundeinedornull,letiterbeundeined.
6.Else,
a.Letadderbe?Get(set,"add").
b.IfIsCallable(adder)isfalse,throwaTypeErrorexception.
c.Letiterbe?GetIterator(iterable).
7.Ifiterisundeined,returnset.
8.Repeat
a.Letnextbe?IteratorStep(iter).
b.Ifnextisfalse,returnset.
c.LetnextValuebe?IteratorValue(next).
d.LetstatusbeCall(adder,set,nextValue.[[Value]]).
e.Ifstatusisanabruptcompletion,return?IteratorClose(iter,status).

23.2.2 PropertiesoftheSetConstructor

Thevalueofthe[[Prototype]]internalslotoftheSetconstructoristheintrinsicobject%FunctionPrototype%.

TheSetconstructorhasthefollowingproperties:
23.2.2.1 Set.prototype

TheinitialvalueofSet.prototypeistheintrinsic%SetPrototype%object.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

23.2.2.2 getSet[@@species]

Set[@@species]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunctionperformsthe
followingsteps:

1.Returnthethisvalue.

Thevalueofthenamepropertyofthisfunctionis"get[Symbol.species]".

NOTE Methodsthatcreatederivedcollectionobjectsshouldcall@@speciestodeterminetheconstructortouseto
createthederivedobjects.Subclassconstructormayoverride@@speciestochangethedefaultconstructor
assignment.

23.2.3 PropertiesoftheSetPrototypeObject

TheSetprototypeobjectistheintrinsicobject%SetPrototype%.Thevalueofthe[[Prototype]]internalslotoftheSet
prototypeobjectistheintrinsicobject%ObjectPrototype%.TheSetprototypeobjectisanordinaryobject.Itdoesnothavea
[[SetData]]internalslot.

23.2.3.1 Set.prototype.add(value)

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[SetData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofS's[[SetData]]internalslot.
5.Repeatforeachethatisanelementofentries,
a.IfeisnotemptyandSameValueZero(e,value)istrue,then
i.ReturnS.
6.Ifvalueis0,letvaluebe+0.
7.Appendvalueasthelastelementofentries.
8.ReturnS.

23.2.3.2 Set.prototype.clear()

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[SetData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofS's[[SetData]]internalslot.
5.Repeatforeachethatisanelementofentries,
a.Replacetheelementofentrieswhosevalueisewithanelementwhosevalueisempty.
6.Returnundeined.

NOTE Theexisting[[SetData]]ListispreservedbecausetheremaybeexistingSetIteratorobjectsthataresuspended
midwaythroughiteratingoverthatList.

23.2.3.3 Set.prototype.constructor

TheinitialvalueofSet.prototype.constructoristheintrinsicobject%Set%.
23.2.3.4 Set.prototype.delete(value)

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[SetData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofS's[[SetData]]internalslot.
5.Repeatforeachethatisanelementofentries,
a.IfeisnotemptyandSameValueZero(e,value)istrue,then
i.Replacetheelementofentrieswhosevalueisewithanelementwhosevalueisempty.
ii.Returntrue.
6.Returnfalse.

NOTE Thevalueemptyisusedasaspeciicationdevicetoindicatethatanentryhasbeendeleted.Actual
implementationsmaytakeotheractionssuchasphysicallyremovingtheentryfrominternaldatastructures.

23.2.3.5 Set.prototype.entries()

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateSetIterator(S,"key+value").

NOTE Foriterationpurposes,aSetappearssimilartoaMapwhereeachentryhasthesamevalueforitskeyand
value.

23.2.3.6 Set.prototype.forEach(callbackfn[,thisArg])

WhentheforEachmethodiscalledwithoneortwoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[SetData]]internalslot,throwaTypeErrorexception.
4.IfIsCallable(callbackfn)isfalse,throwaTypeErrorexception.
5.IfthisArgwassupplied,letTbethisArg;elseletTbeundeined.
6.LetentriesbetheListthatisthevalueofS's[[SetData]]internalslot.
7.Repeatforeachethatisanelementofentries,inoriginalinsertionorder
a.Ifeisnotempty,then
i.Perform?Call(callbackfn,T,e,e,S).
8.Returnundeined.

NOTE callbackfnshouldbeafunctionthatacceptsthreearguments.forEachcallscallbackfnonceforeachvalue
presentinthesetobject,invalueinsertionorder.callbackfniscalledonlyforvaluesoftheSetwhichactually
exist;itisnotcalledforkeysthathavebeendeletedfromtheset.

IfathisArgparameterisprovided,itwillbeusedasthethisvalueforeachinvocationofcallbackfn.Ifitisnot
provided,undeinedisusedinstead.

callbackfniscalledwiththreearguments:theirsttwoargumentsareavaluecontainedintheSet.Thesame
valueispassedforbotharguments.TheSetobjectbeingtraversedispassedasthethirdargument.

ThecallbackfniscalledwiththreeargumentstobeconsistentwiththecallbackfunctionsusedbyforEach
methodsforMapandArray.ForSets,eachitemvalueisconsideredtobeboththekeyandthevalue.

forEachdoesnotdirectlymutatetheobjectonwhichitiscalledbuttheobjectmaybemutatedbythecallsto
callbackfn.
Eachvalueisnormallyvisitedonlyonce.However,avaluewillberevisitedifitisdeletedafterithasbeen
visitedandthenreaddedbeforetheforEachcallcompletes.ValuesthataredeletedafterthecalltoforEach
beginsandbeforebeingvisitedarenotvisitedunlessthevalueisaddedagainbeforetheforEachcall
completes.NewvaluesaddedafterthecalltoforEachbeginsarevisited.

23.2.3.7 Set.prototype.has(value)

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[SetData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofS's[[SetData]]internalslot.
5.Repeatforeachethatisanelementofentries,
a.IfeisnotemptyandSameValueZero(e,value)istrue,returntrue.
6.Returnfalse.

23.2.3.8 Set.prototype.keys()

Theinitialvalueofthekeyspropertyisthesamefunctionobjectastheinitialvalueofthevaluesproperty.

NOTE Foriterationpurposes,aSetappearssimilartoaMapwhereeachentryhasthesamevalueforitskeyand
value.

23.2.3.9 getSet.prototype.size

Set.prototype.sizeisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunctionperforms
thefollowingsteps:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[SetData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofS's[[SetData]]internalslot.
5.Letcountbe0.
6.Foreachethatisanelementofentries
a.Ifeisnotempty,setcounttocount+1.
7.Returncount.

23.2.3.10 Set.prototype.values()

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateSetIterator(S,"value").

23.2.3.11 Set.prototype[@@iterator]()

Theinitialvalueofthe@@iteratorpropertyisthesamefunctionobjectastheinitialvalueofthevaluesproperty.

23.2.3.12 Set.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"Set".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

23.2.4 PropertiesofSetInstances

SetinstancesareordinaryobjectsthatinheritpropertiesfromtheSetprototype.Setinstancesalsohavea[[SetData]]
internalslot.
23.2.5 SetIteratorObjects

ASetIteratorisanordinaryobject,withthestructuredeinedbelow,thatrepresentsaspeciiciterationoversomespeciic
Setinstanceobject.ThereisnotanamedconstructorforSetIteratorobjects.Instead,setiteratorobjectsarecreatedby
callingcertainmethodsofSetinstanceobjects.

23.2.5.1 CreateSetIteratorAbstractOperation

SeveralmethodsofSetobjectsreturnIteratorobjects.TheabstractoperationCreateSetIteratorwithargumentssetandkind
isusedtocreatesuchiteratorobjects.Itperformsthefollowingsteps:

1.IfType(set)isnotObject,throwaTypeErrorexception.
2.Ifsetdoesnothavea[[SetData]]internalslot,throwaTypeErrorexception.
3.LetiteratorbeObjectCreate(%SetIteratorPrototype%,[[IteratedSet]],[[SetNextIndex]],[[SetIterationKind]]).
4.Setiterator's[[IteratedSet]]internalslottoset.
5.Setiterator's[[SetNextIndex]]internalslotto0.
6.Setiterator's[[SetIterationKind]]internalslottokind.
7.Returniterator.

23.2.5.2 The%SetIteratorPrototype%Object

AllSetIteratorObjectsinheritpropertiesfromthe%SetIteratorPrototype%intrinsicobject.The%SetIteratorPrototype%
intrinsicobjectisanordinaryobjectandits[[Prototype]]internalslotisthe%IteratorPrototype%intrinsicobject.In
addition,%SetIteratorPrototype%hasthefollowingproperties:

23.2.5.2.1 %SetIteratorPrototype%.next()

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavealloftheinternalslotsofaSetIteratorInstance(23.2.5.3),throwaTypeErrorexception.
4.Letsbethevalueofthe[[IteratedSet]]internalslotofO.
5.Letindexbethevalueofthe[[SetNextIndex]]internalslotofO.
6.LetitemKindbethevalueofthe[[SetIterationKind]]internalslotofO.
7.Ifsisundeined,returnCreateIterResultObject(undeined,true).
8.Assert:shasa[[SetData]]internalslot.
9.LetentriesbetheListthatisthevalueofthe[[SetData]]internalslotofs.
10.Repeatwhileindexislessthanthetotalnumberofelementsofentries.Thenumberofelementsmustberedetermined
eachtimethismethodisevaluated.
a.Letebeentries[index].
b.Setindextoindex+1.
c.Setthe[[SetNextIndex]]internalslotofOtoindex.
d.Ifeisnotempty,then
i.IfitemKindis"key+value",then
1.ReturnCreateIterResultObject(CreateArrayFromList(e,e),false).
ii.ReturnCreateIterResultObject(e,false).
11.Setthe[[IteratedSet]]internalslotofOtoundeined.
12.ReturnCreateIterResultObject(undeined,true).

23.2.5.2.2 %SetIteratorPrototype%[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"SetIterator".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

23.2.5.3 PropertiesofSetIteratorInstances

SetIteratorinstancesareordinaryobjectsthatinheritpropertiesfromthe%SetIteratorPrototype%intrinsicobject.Set
IteratorinstancesareinitiallycreatedwiththeinternalslotsspeciiedinTable52.
Table52:InternalSlotsofSetIteratorInstances
InternalSlot Description

[[IteratedSet]] TheSetobjectthatisbeingiterated.

[[SetNextIndex]] TheintegerindexofthenextSetdataelementtobeexaminedbythisiterator

[[SetIterationKind]] AStringvaluethatidentiieswhatistobereturnedforeachelementoftheiteration.Thepossible
valuesare:"key","value","key+value"."key"and"value"havethesamemeaning.

23.3 WeakMapObjects
WeakMapobjectsarecollectionsofkey/valuepairswherethekeysareobjectsandvaluesmaybearbitraryECMAScript
languagevalues.AWeakMapmaybequeriedtoseeifitcontainsakey/valuepairwithaspeciickey,butnomechanismis
providedforenumeratingtheobjectsitholdsaskeys.IfanobjectthatisbeingusedasthekeyofaWeakMapkey/valuepair
isonlyreachablebyfollowingachainofreferencesthatstartwithinthatWeakMap,thenthatkey/valuepairisinaccessible
andisautomaticallyremovedfromtheWeakMap.WeakMapimplementationsmustdetectandremovesuchkey/valuepairs
andanyassociatedresources.

Animplementationmayimposeanarbitrarilydeterminedlatencybetweenthetimeakey/valuepairofaWeakMapbecomes
inaccessibleandthetimewhenthekey/valuepairisremovedfromtheWeakMap.Ifthislatencywasobservableto
ECMAScriptprogram,itwouldbeasourceofindeterminacythatcouldimpactprogramexecution.Forthatreason,an
ECMAScriptimplementationmustnotprovideanymeanstoobserveakeyofaWeakMapthatdoesnotrequiretheobserver
topresenttheobservedkey.

WeakMapobjectsmustbeimplementedusingeitherhashtablesorothermechanismsthat,onaverage,provideaccesstimes
thataresublinearonthenumberofkey/valuepairsinthecollection.ThedatastructureusedinthisWeakMapobjects
speciicationareonlyintendedtodescribetherequiredobservablesemanticsofWeakMapobjects.Itisnotintendedtobea
viableimplementationmodel.

NOTE WeakMapandWeakSetsareintendedtoprovidemechanismsfordynamicallyassociatingstatewithanobject
inamannerthatdoesnotleakmemoryresourcesif,intheabsenceoftheWeakMaporWeakSet,theobject
otherwisebecameinaccessibleandsubjecttoresourcereclamationbytheimplementation'sgarbagecollection
mechanisms.Thischaracteristiccanbeachievedbyusinganinvertedperobjectmappingofweakmap
instancestokeys.Alternativelyeachweakmapmayinternallystoreitskeytovaluemappingsbutthis
approachrequirescoordinationbetweentheWeakMaporWeakSetimplementationandthegarbagecollector.
ThefollowingreferencesdescribemechanismthatmaybeusefultoimplementationsofWeakMapand
WeakSets:

BarryHayes.1997.Ephemerons:anewinalizationmechanism.InProceedingsofthe12thACMSIGPLAN
conferenceonObjectorientedprogramming,systems,languages,andapplications(OOPSLA'97),A.Michael
Berman(Ed.).ACM,NewYork,NY,USA,176183,http://doi.acm.org/10.1145/263698.263733.

AlexandraBarros,RobertoIerusalimschy,EliminatingCyclesinWeakTables.JournalofUniversalComputer
ScienceJ.UCS,vol.14,no.21,pp.34813497,2008,
http://www.jucs.org/jucs_14_21/eliminating_cycles_in_weak

23.3.1 TheWeakMapConstructor

TheWeakMapconstructoristhe%WeakMap%intrinsicobjectandtheinitialvalueoftheWeakMappropertyoftheglobal
object.WhencalledasaconstructoritcreatesandinitializesanewWeakMapobject.WeakMapisnotintendedtobecalledas
afunctionandwillthrowanexceptionwhencalledinthatmanner.

TheWeakMapconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueinanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedWeakMapbehaviourmustincludeasupercalltothe
WeakMapconstructortocreateandinitializethesubclassinstancewiththeinternalstatenecessarytosupportthe
WeakMap.prototypebuiltinmethods.

23.3.1.1 WeakMap([iterable])

WhentheWeakMapfunctioniscalledwithoptionalargumentiterable,thefollowingstepsaretaken:

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.Letmapbe?OrdinaryCreateFromConstructor(NewTarget,"%WeakMapPrototype%",[[WeakMapData]]).
3.Setmap's[[WeakMapData]]internalslottoanewemptyList.
4.Ifiterableisnotpresent,letiterablebeundeined.
5.Ifiterableiseitherundeinedornull,letiterbeundeined.
6.Else,
a.Letadderbe?Get(map,"set").
b.IfIsCallable(adder)isfalse,throwaTypeErrorexception.
c.Letiterbe?GetIterator(iterable).
7.Ifiterisundeined,returnmap.
8.Repeat
a.Letnextbe?IteratorStep(iter).
b.Ifnextisfalse,returnmap.
c.LetnextItembe?IteratorValue(next).
d.IfType(nextItem)isnotObject,then
i.LeterrorbeCompletion{[[Type]]:throw,[[Value]]:anewlycreatedTypeErrorobject,[[Target]]:empty}.
ii.Return?IteratorClose(iter,error).
e.LetkbeGet(nextItem,"0").
f.Ifkisanabruptcompletion,return?IteratorClose(iter,k).
g.LetvbeGet(nextItem,"1").
h.Ifvisanabruptcompletion,return?IteratorClose(iter,v).
i.LetstatusbeCall(adder,map,k.[[Value]],v.[[Value]]).
j.Ifstatusisanabruptcompletion,return?IteratorClose(iter,status).

NOTE Iftheparameteriterableispresent,itisexpectedtobeanobjectthatimplementsan@@iteratormethodthat
returnsaniteratorobjectthatproducesatwoelementarraylikeobjectwhoseirstelementisavaluethatwill
beusedasaWeakMapkeyandwhosesecondelementisthevaluetoassociatewiththatkey.

23.3.2 PropertiesoftheWeakMapConstructor

Thevalueofthe[[Prototype]]internalslotoftheWeakMapconstructoristheintrinsicobject%FunctionPrototype%.

TheWeakMapconstructorhasthefollowingproperties:

23.3.2.1 WeakMap.prototype

TheinitialvalueofWeakMap.prototypeistheintrinsicobject%WeakMapPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

23.3.3 PropertiesoftheWeakMapPrototypeObject

TheWeakMapprototypeobjectistheintrinsicobject%WeakMapPrototype%.Thevalueofthe[[Prototype]]internalslotof
theWeakMapprototypeobjectistheintrinsicobject%ObjectPrototype%.TheWeakMapprototypeobjectisanordinary
object.Itdoesnothavea[[WeakMapData]]internalslot.

23.3.3.1 WeakMap.prototype.constructor

TheinitialvalueofWeakMap.prototype.constructoristheintrinsicobject%WeakMap%.

23.3.3.2 WeakMap.prototype.delete(key)
Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[WeakMapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[WeakMapData]]internalslot.
5.IfType(key)isnotObject,returnfalse.
6.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValue(p.[[Key]],key)istrue,then
i.Setp.[[Key]]toempty.
ii.Setp.[[Value]]toempty.
iii.Returntrue.
7.Returnfalse.

NOTE Thevalueemptyisusedasaspeciicationdevicetoindicatethatanentryhasbeendeleted.Actual
implementationsmaytakeotheractionssuchasphysicallyremovingtheentryfrominternaldatastructures.

23.3.3.3 WeakMap.prototype.get(key)

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[WeakMapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[WeakMapData]]internalslot.
5.IfType(key)isnotObject,returnundeined.
6.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValue(p.[[Key]],key)istrue,returnp.[[Value]].
7.Returnundeined.

23.3.3.4 WeakMap.prototype.has(key)

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[WeakMapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[WeakMapData]]internalslot.
5.IfType(key)isnotObject,returnfalse.
6.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValue(p.[[Key]],key)istrue,returntrue.
7.Returnfalse.

23.3.3.5 WeakMap.prototype.set(key,value)

Thefollowingstepsaretaken:

1.LetMbethethisvalue.
2.IfType(M)isnotObject,throwaTypeErrorexception.
3.IfMdoesnothavea[[WeakMapData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofM's[[WeakMapData]]internalslot.
5.IfType(key)isnotObject,throwaTypeErrorexception.
6.RepeatforeachRecord{[[Key]],[[Value]]}pthatisanelementofentries,
a.Ifp.[[Key]]isnotemptyandSameValue(p.[[Key]],key)istrue,then
i.Setp.[[Value]]tovalue.
ii.ReturnM.
7.LetpbetheRecord{[[Key]]:key,[[Value]]:value}.
8.Appendpasthelastelementofentries.
9.ReturnM.

23.3.3.6 WeakMap.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"WeakMap".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

23.3.4 PropertiesofWeakMapInstances

WeakMapinstancesareordinaryobjectsthatinheritpropertiesfromtheWeakMapprototype.WeakMapinstancesalsohave
a[[WeakMapData]]internalslot.

23.4 WeakSetObjects
WeakSetobjectsarecollectionsofobjects.AdistinctobjectmayonlyoccuronceasanelementofaWeakSet'scollection.A
WeakSetmaybequeriedtoseeifitcontainsaspeciicobject,butnomechanismisprovidedforenumeratingtheobjectsit
holds.IfanobjectthatiscontainedbyaWeakSetisonlyreachablebyfollowingachainofreferencesthatstartwithinthat
WeakSet,thenthatobjectisinaccessibleandisautomaticallyremovedfromtheWeakSet.WeakSetimplementationsmust
detectandremovesuchobjectsandanyassociatedresources.

AnimplementationmayimposeanarbitrarilydeterminedlatencybetweenthetimeanobjectcontainedinaWeakSet
becomesinaccessibleandthetimewhentheobjectisremovedfromtheWeakSet.Ifthislatencywasobservableto
ECMAScriptprogram,itwouldbeasourceofindeterminacythatcouldimpactprogramexecution.Forthatreason,an
ECMAScriptimplementationmustnotprovideanymeanstodetermineifaWeakSetcontainsaparticularobjectthatdoes
notrequiretheobservertopresenttheobservedobject.

WeakSetobjectsmustbeimplementedusingeitherhashtablesorothermechanismsthat,onaverage,provideaccesstimes
thataresublinearonthenumberofelementsinthecollection.ThedatastructureusedinthisWeakSetobjectsspeciication
isonlyintendedtodescribetherequiredobservablesemanticsofWeakSetobjects.Itisnotintendedtobeaviable
implementationmodel.

NOTE SeetheNOTEin23.3.

23.4.1 TheWeakSetConstructor

TheWeakSetconstructoristhe%WeakSet%intrinsicobjectandtheinitialvalueoftheWeakSetpropertyoftheglobal
object.WhencalledasaconstructoritcreatesandinitializesanewWeakSetobject.WeakSetisnotintendedtobecalledasa
functionandwillthrowanexceptionwhencalledinthatmanner.

TheWeakSetconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueinanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedWeakSetbehaviourmustincludeasupercalltothe
WeakSetconstructortocreateandinitializethesubclassinstancewiththeinternalstatenecessarytosupportthe
WeakSet.prototypebuiltinmethods.

23.4.1.1 WeakSet([iterable])

WhentheWeakSetfunctioniscalledwithoptionalargumentiterable,thefollowingstepsaretaken:

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.Letsetbe?OrdinaryCreateFromConstructor(NewTarget,"%WeakSetPrototype%",[[WeakSetData]]).
3.Setset's[[WeakSetData]]internalslottoanewemptyList.
4.Ifiterableisnotpresent,letiterablebeundeined.
5.Ifiterableiseitherundeinedornull,letiterbeundeined.
6.Else,
a.Letadderbe?Get(set,"add").
b.IfIsCallable(adder)isfalse,throwaTypeErrorexception.
c.Letiterbe?GetIterator(iterable).
7.Ifiterisundeined,returnset.
8.Repeat
a.Letnextbe?IteratorStep(iter).
b.Ifnextisfalse,returnset.
c.LetnextValuebe?IteratorValue(next).
d.LetstatusbeCall(adder,set,nextValue).
e.Ifstatusisanabruptcompletion,return?IteratorClose(iter,status).

23.4.2 PropertiesoftheWeakSetConstructor

Thevalueofthe[[Prototype]]internalslotoftheWeakSetconstructoristheintrinsicobject%FunctionPrototype%.

TheWeakSetconstructorhasthefollowingproperties:

23.4.2.1 WeakSet.prototype

TheinitialvalueofWeakSet.prototypeistheintrinsic%WeakSetPrototype%object.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

23.4.3 PropertiesoftheWeakSetPrototypeObject

TheWeakSetprototypeobjectistheintrinsicobject%WeakSetPrototype%.Thevalueofthe[[Prototype]]internalslotofthe
WeakSetprototypeobjectistheintrinsicobject%ObjectPrototype%.TheWeakSetprototypeobjectisanordinaryobject.It
doesnothavea[[WeakSetData]]internalslot.

23.4.3.1 WeakSet.prototype.add(value)

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[WeakSetData]]internalslot,throwaTypeErrorexception.
4.IfType(value)isnotObject,throwaTypeErrorexception.
5.LetentriesbetheListthatisthevalueofS's[[WeakSetData]]internalslot.
6.Repeatforeachethatisanelementofentries,
a.IfeisnotemptyandSameValue(e,value)istrue,then
i.ReturnS.
7.Appendvalueasthelastelementofentries.
8.ReturnS.

23.4.3.2 WeakSet.prototype.constructor

TheinitialvalueofWeakSet.prototype.constructoristhe%WeakSet%intrinsicobject.

23.4.3.3 WeakSet.prototype.delete(value)

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[WeakSetData]]internalslot,throwaTypeErrorexception.
4.IfType(value)isnotObject,returnfalse.
5.LetentriesbetheListthatisthevalueofS's[[WeakSetData]]internalslot.
6.Repeatforeachethatisanelementofentries,
a.IfeisnotemptyandSameValue(e,value)istrue,then
i.Replacetheelementofentrieswhosevalueisewithanelementwhosevalueisempty.
ii.Returntrue.
7.Returnfalse.

NOTE Thevalueemptyisusedasaspeciicationdevicetoindicatethatanentryhasbeendeleted.Actual
implementationsmaytakeotheractionssuchasphysicallyremovingtheentryfrominternaldatastructures.

23.4.3.4 WeakSet.prototype.has(value)

Thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.IfType(S)isnotObject,throwaTypeErrorexception.
3.IfSdoesnothavea[[WeakSetData]]internalslot,throwaTypeErrorexception.
4.LetentriesbetheListthatisthevalueofS's[[WeakSetData]]internalslot.
5.IfType(value)isnotObject,returnfalse.
6.Repeatforeachethatisanelementofentries,
a.IfeisnotemptyandSameValue(e,value)istrue,returntrue.
7.Returnfalse.

23.4.3.5 WeakSet.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"WeakSet".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

23.4.4 PropertiesofWeakSetInstances

WeakSetinstancesareordinaryobjectsthatinheritpropertiesfromtheWeakSetprototype.WeakSetinstancesalsohavea
[[WeakSetData]]internalslot.

24 StructuredData
24.1 ArrayBufferObjects
24.1.1 AbstractOperationsForArrayBufferObjects

24.1.1.1 AllocateArrayBuffer(constructor,byteLength)

TheabstractoperationAllocateArrayBufferwithargumentsconstructorandbyteLengthisusedtocreateanArrayBuffer
object.Itperformsthefollowingsteps:

1.Letobjbe?OrdinaryCreateFromConstructor(constructor,"%ArrayBufferPrototype%",[[ArrayBufferData]],
[[ArrayBufferByteLength]]).
2.Assert:byteLengthisanintegervalue0.
3.Letblockbe?CreateByteDataBlock(byteLength).
4.Setobj's[[ArrayBufferData]]internalslottoblock.
5.Setobj's[[ArrayBufferByteLength]]internalslottobyteLength.
6.Returnobj.

24.1.1.2 IsDetachedBuffer(arrayBuffer)

TheabstractoperationIsDetachedBufferwithargumentarrayBufferperformsthefollowingsteps:

1.Assert:Type(arrayBuffer)isObjectandithasan[[ArrayBufferData]]internalslot.
2.IfarrayBuffer's[[ArrayBufferData]]internalslotisnull,returntrue.
3.Returnfalse.
24.1.1.3 DetachArrayBuffer(arrayBuffer)

TheabstractoperationDetachArrayBufferwithargumentarrayBufferperformsthefollowingsteps:

1.Assert:Type(arrayBuffer)isObjectandithas[[ArrayBufferData]]and[[ArrayBufferByteLength]]internalslots.
2.SetarrayBuffer's[[ArrayBufferData]]internalslottonull.
3.SetarrayBuffer's[[ArrayBufferByteLength]]internalslotto0.
4.ReturnNormalCompletion(null).

NOTE DetachinganArrayBufferinstancedisassociatestheDataBlockusedasitsbackingstorefromtheinstanceand
setsthebytelengthofthebufferto0.NooperationsdeinedbythisspeciicationusetheDetachArrayBuffer
abstractoperation.However,anECMAScriptimplementationorhostenvironmentmaydeinesuchoperations.

24.1.1.4 CloneArrayBuffer(srcBuffer,srcByteOffset[,cloneConstructor])

TheabstractoperationCloneArrayBuffertakesthreeparameters,anArrayBuffersrcBuffer,anintegersrcByteOffsetand
optionallyaconstructorfunctioncloneConstructor.ItcreatesanewArrayBufferwhosedataisacopyofsrcBuffer'sdata
startingatsrcByteOffset.Thisoperationperformsthefollowingsteps:

1.Assert:Type(srcBuffer)isObjectandithasan[[ArrayBufferData]]internalslot.
2.IfcloneConstructorisnotpresent,then
a.LetcloneConstructorbe?SpeciesConstructor(srcBuffer,%ArrayBuffer%).
b.IfIsDetachedBuffer(srcBuffer)istrue,throwaTypeErrorexception.
3.Else,Assert:IsConstructor(cloneConstructor)istrue.
4.LetsrcLengthbethevalueofsrcBuffer's[[ArrayBufferByteLength]]internalslot.
5.Assert:srcByteOffsetsrcLength.
6.LetcloneLengthbesrcLengthsrcByteOffset.
7.LetsrcBlockbethevalueofsrcBuffer's[[ArrayBufferData]]internalslot.
8.LettargetBufferbe?AllocateArrayBuffer(cloneConstructor,cloneLength).
9.IfIsDetachedBuffer(srcBuffer)istrue,throwaTypeErrorexception.
10.LettargetBlockbethevalueoftargetBuffer's[[ArrayBufferData]]internalslot.
11.PerformCopyDataBlockBytes(targetBlock,0,srcBlock,srcByteOffset,cloneLength).
12.ReturntargetBuffer.

24.1.1.5 GetValueFromBuffer(arrayBuffer,byteIndex,type[,isLittleEndian])

TheabstractoperationGetValueFromBuffertakesfourparameters,anArrayBufferarrayBuffer,anintegerbyteIndex,aString
type,andoptionallyaBooleanisLittleEndian.Thisoperationperformsthefollowingsteps:

1.Assert:IsDetachedBuffer(arrayBuffer)isfalse.
2.Assert:TherearesuficientbytesinarrayBufferstartingatbyteIndextorepresentavalueoftype.
3.Assert:byteIndexisanintegervalue0.
4.LetblockbearrayBuffer's[[ArrayBufferData]]internalslot.
5.LetelementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forElementTypetype.
6.LetrawValuebeaListofelementSizecontaining,inorder,theelementSizesequenceofbytesstartingwith
block[byteIndex].
7.IfisLittleEndianisnotpresent,setisLittleEndiantoeithertrueorfalse.Thechoiceisimplementationdependentand
shouldbethealternativethatismosteficientfortheimplementation.Animplementationmustusethesamevalue
eachtimethisstepisexecutedandthesamevaluemustbeusedforthecorrespondingstepintheSetValueInBuffer
abstractoperation.
8.IfisLittleEndianisfalse,reversetheorderoftheelementsofrawValue.
9.Iftypeis"Float32",then
a.LetvaluebethebyteelementsofrawValueconcatenatedandinterpretedasalittleendianbitstringencodingof
anIEEE7542008binary32value.
b.IfvalueisanIEEE7542008binary32NaNvalue,returntheNaNNumbervalue.
c.ReturntheNumbervaluethatcorrespondstovalue.
10.Iftypeis"Float64",then
a.LetvaluebethebyteelementsofrawValueconcatenatedandinterpretedasalittleendianbitstringencodingof
anIEEE7542008binary64value.
b.IfvalueisanIEEE7542008binary64NaNvalue,returntheNaNNumbervalue.
c.ReturntheNumbervaluethatcorrespondstovalue.
11.Iftheirstcodeunitoftypeis"U",then
a.LetintValuebethebyteelementsofrawValueconcatenatedandinterpretedasabitstringencodingofanunsigned
littleendianbinarynumber.
12.Else,
a.LetintValuebethebyteelementsofrawValueconcatenatedandinterpretedasabitstringencodingofabinary
littleendian2'scomplementnumberofbitlengthelementSize8.
13.ReturntheNumbervaluethatcorrespondstointValue.

24.1.1.6 SetValueInBuffer(arrayBuffer,byteIndex,type,value[,isLittleEndian])

TheabstractoperationSetValueInBuffertakesiveparameters,anArrayBufferarrayBuffer,anintegerbyteIndex,aString
type,aNumbervalue,andoptionallyaBooleanisLittleEndian.Thisoperationperformsthefollowingsteps:

1.Assert:IsDetachedBuffer(arrayBuffer)isfalse.
2.Assert:TherearesuficientbytesinarrayBufferstartingatbyteIndextorepresentavalueoftype.
3.Assert:byteIndexisanintegervalue0.
4.Assert:Type(value)isNumber.
5.LetblockbearrayBuffer's[[ArrayBufferData]]internalslot.
6.Assert:blockisnotundeined.
7.IfisLittleEndianisnotpresent,setisLittleEndiantoeithertrueorfalse.Thechoiceisimplementationdependentand
shouldbethealternativethatismosteficientfortheimplementation.Animplementationmustusethesamevalue
eachtimethisstepisexecutedandthesamevaluemustbeusedforthecorrespondingstepintheGetValueFromBuffer
abstractoperation.
8.Iftypeis"Float32",then
a.SetrawBytestoaListcontainingthe4bytesthataretheresultofconvertingvaluetoIEEE7542008binary32
formatusingRoundtonearest,tiestoevenroundingmode.IfisLittleEndianisfalse,thebytesarearrangedinbig
endianorder.Otherwise,thebytesarearrangedinlittleendianorder.IfvalueisNaN,rawValuemaybesettoany
implementationchosenIEEE7542008binary64formatNotaNumberencoding.Animplementationmustalways
choosethesameencodingforeachimplementationdistinguishableNaNvalue.
9.Else,iftypeis"Float64",then
a.SetrawBytestoaListcontainingthe8bytesthataretheIEEE7542008binary64formatencodingofvalue.If
isLittleEndianisfalse,thebytesarearrangedinbigendianorder.Otherwise,thebytesarearrangedinlittleendian
order.IfvalueisNaN,rawValuemaybesettoanyimplementationchosenIEEE7542008binary32formatNota
Numberencoding.Animplementationmustalwayschoosethesameencodingforeachimplementation
distinguishableNaNvalue.
10.Else,
a.LetnbetheNumbervalueoftheElementSizespeciiedinTable50forElementTypetype.
b.LetconvOpbetheabstractoperationnamedintheConversionOperationcolumninTable50forElementType
type.
c.LetintValuebeconvOp(value).
d.IfintValue0,then
i.LetrawBytesbeaListcontainingthenbytebinaryencodingofintValue.IfisLittleEndianisfalse,thebytes
areorderedinbigendianorder.Otherwise,thebytesareorderedinlittleendianorder.
e.Else,
i.LetrawBytesbeaListcontainingthenbytebinary2'scomplementencodingofintValue.IfisLittleEndianis
false,thebytesareorderedinbigendianorder.Otherwise,thebytesareorderedinlittleendianorder.
11.StoretheindividualbytesofrawBytesintoblock,inorder,startingatblock[byteIndex].
12.ReturnNormalCompletion(undeined).

24.1.2 TheArrayBufferConstructor
TheArrayBufferconstructoristhe%ArrayBuffer%intrinsicobjectandtheinitialvalueoftheArrayBufferpropertyofthe
globalobject.WhencalledasaconstructoritcreatesandinitializesanewArrayBufferobject.ArrayBufferisnotintended
tobecalledasafunctionandwillthrowanexceptionwhencalledinthatmanner.

TheArrayBufferconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedArrayBufferbehaviourmustincludeasupercallto
theArrayBufferconstructortocreateandinitializesubclassinstanceswiththeinternalstatenecessarytosupportthe
ArrayBuffer.prototypebuiltinmethods.

24.1.2.1 ArrayBuffer(length)

ArrayBuffercalledwithargumentlengthperformsthefollowingsteps:

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.LetnumberLengthbe?ToNumber(length).
3.LetbyteLengthbeToLength(numberLength).
4.IfSameValueZero(numberLength,byteLength)isfalse,throwaRangeErrorexception.
5.Return?AllocateArrayBuffer(NewTarget,byteLength).

24.1.3 PropertiesoftheArrayBufferConstructor

Thevalueofthe[[Prototype]]internalslotoftheArrayBufferconstructoristheintrinsicobject%FunctionPrototype%.

TheArrayBufferconstructorhasthefollowingproperties:

24.1.3.1 ArrayBuffer.isView(arg)

TheisViewfunctiontakesoneargumentarg,andperforms,thefollowingstepsaretaken:

1.IfType(arg)isnotObject,returnfalse.
2.Ifarghasa[[ViewedArrayBuffer]]internalslot,returntrue.
3.Returnfalse.

24.1.3.2 ArrayBuffer.prototype

TheinitialvalueofArrayBuffer.prototypeistheintrinsicobject%ArrayBufferPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

24.1.3.3 getArrayBuffer[@@species]

ArrayBuffer[@@species]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.Returnthethisvalue.

Thevalueofthenamepropertyofthisfunctionis"get[Symbol.species]".

NOTE ArrayBufferprototypemethodsnormallyusetheirthisobject'sconstructortocreateaderivedobject.
However,asubclassconstructormayoverridethatdefaultbehaviourbyredeiningits@@speciesproperty.

24.1.4 PropertiesoftheArrayBufferPrototypeObject

TheArrayBufferprototypeobjectistheintrinsicobject%ArrayBufferPrototype%.Thevalueofthe[[Prototype]]internalslot
oftheArrayBufferprototypeobjectistheintrinsicobject%ObjectPrototype%.TheArrayBufferprototypeobjectisan
ordinaryobject.Itdoesnothavean[[ArrayBufferData]]or[[ArrayBufferByteLength]]internalslot.

24.1.4.1 getArrayBuffer.prototype.byteLength
ArrayBuffer.prototype.byteLengthisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavean[[ArrayBufferData]]internalslot,throwaTypeErrorexception.
4.IfIsDetachedBuffer(O)istrue,throwaTypeErrorexception.
5.LetlengthbethevalueofO's[[ArrayBufferByteLength]]internalslot.
6.Returnlength.

24.1.4.2 ArrayBuffer.prototype.constructor

TheinitialvalueofArrayBuffer.prototype.constructoristheintrinsicobject%ArrayBuffer%.

24.1.4.3 ArrayBuffer.prototype.slice(start,end)

Thefollowingstepsaretaken:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavean[[ArrayBufferData]]internalslot,throwaTypeErrorexception.
4.IfIsDetachedBuffer(O)istrue,throwaTypeErrorexception.
5.LetlenbethevalueofO's[[ArrayBufferByteLength]]internalslot.
6.LetrelativeStartbe?ToInteger(start).
7.IfrelativeStart<0,letirstbemax((len+relativeStart),0);elseletirstbemin(relativeStart,len).
8.Ifendisundeined,letrelativeEndbelen;elseletrelativeEndbe?ToInteger(end).
9.IfrelativeEnd<0,letinalbemax((len+relativeEnd),0);elseletinalbemin(relativeEnd,len).
10.LetnewLenbemax(inalirst,0).
11.Letctorbe?SpeciesConstructor(O,%ArrayBuffer%).
12.Letnewbe?Construct(ctor,newLen).
13.Ifnewdoesnothavean[[ArrayBufferData]]internalslot,throwaTypeErrorexception.
14.IfIsDetachedBuffer(new)istrue,throwaTypeErrorexception.
15.IfSameValue(new,O)istrue,throwaTypeErrorexception.
16.Ifthevalueofnew's[[ArrayBufferByteLength]]internalslot<newLen,throwaTypeErrorexception.
17.NOTE:SideeffectsoftheabovestepsmayhavedetachedO.
18.IfIsDetachedBuffer(O)istrue,throwaTypeErrorexception.
19.LetfromBufbethevalueofO's[[ArrayBufferData]]internalslot.
20.LettoBufbethevalueofnew's[[ArrayBufferData]]internalslot.
21.PerformCopyDataBlockBytes(toBuf,0,fromBuf,irst,newLen).
22.Returnnew.

24.1.4.4 ArrayBuffer.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"ArrayBuffer".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

24.1.5 PropertiesoftheArrayBufferInstances

ArrayBufferinstancesinheritpropertiesfromtheArrayBufferprototypeobject.ArrayBufferinstanceseachhavean
[[ArrayBufferData]]internalslotandan[[ArrayBufferByteLength]]internalslot.

ArrayBufferinstanceswhose[[ArrayBufferData]]isnullareconsideredtobedetachedandalloperatorstoaccessormodify
datacontainedintheArrayBufferinstancewillfail.

24.2 DataViewObjects
24.2.1 AbstractOperationsForDataViewObjects

24.2.1.1 GetViewValue(view,requestIndex,isLittleEndian,type)

TheabstractoperationGetViewValuewithargumentsview,requestIndex,isLittleEndian,andtypeisusedbyfunctionson
DataViewinstancesistoretrievevaluesfromtheview'sbuffer.Itperformsthefollowingsteps:

1.IfType(view)isnotObject,throwaTypeErrorexception.
2.Ifviewdoesnothavea[[DataView]]internalslot,throwaTypeErrorexception.
3.LetnumberIndexbe?ToNumber(requestIndex).
4.LetgetIndexbeToInteger(numberIndex).
5.IfnumberIndexgetIndexorgetIndex<0,throwaRangeErrorexception.
6.LetisLittleEndianbeToBoolean(isLittleEndian).
7.Letbufferbethevalueofview's[[ViewedArrayBuffer]]internalslot.
8.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
9.LetviewOffsetbethevalueofview's[[ByteOffset]]internalslot.
10.LetviewSizebethevalueofview's[[ByteLength]]internalslot.
11.LetelementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forElementTypetype.
12.IfgetIndex+elementSize>viewSize,throwaRangeErrorexception.
13.LetbufferIndexbegetIndex+viewOffset.
14.ReturnGetValueFromBuffer(buffer,bufferIndex,type,isLittleEndian).

24.2.1.2 SetViewValue(view,requestIndex,isLittleEndian,type,value)

TheabstractoperationSetViewValuewithargumentsview,requestIndex,isLittleEndian,type,andvalueisusedbyfunctions
onDataViewinstancestostorevaluesintotheview'sbuffer.Itperformsthefollowingsteps:

1.IfType(view)isnotObject,throwaTypeErrorexception.
2.Ifviewdoesnothavea[[DataView]]internalslot,throwaTypeErrorexception.
3.LetnumberIndexbe?ToNumber(requestIndex).
4.LetgetIndexbeToInteger(numberIndex).
5.IfnumberIndexgetIndexorgetIndex<0,throwaRangeErrorexception.
6.LetnumberValuebe?ToNumber(value).
7.LetisLittleEndianbeToBoolean(isLittleEndian).
8.Letbufferbethevalueofview's[[ViewedArrayBuffer]]internalslot.
9.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
10.LetviewOffsetbethevalueofview's[[ByteOffset]]internalslot.
11.LetviewSizebethevalueofview's[[ByteLength]]internalslot.
12.LetelementSizebetheNumbervalueoftheElementSizevaluespeciiedinTable50forElementTypetype.
13.IfgetIndex+elementSize>viewSize,throwaRangeErrorexception.
14.LetbufferIndexbegetIndex+viewOffset.
15.ReturnSetValueInBuffer(buffer,bufferIndex,type,numberValue,isLittleEndian).

24.2.2 TheDataViewConstructor

TheDataViewconstructoristhe%DataView%intrinsicobjectandtheinitialvalueoftheDataViewpropertyoftheglobal
object.WhencalledasaconstructoritcreatesandinitializesanewDataViewobject.DataViewisnotintendedtobecalledas
afunctionandwillthrowanexceptionwhencalledinthatmanner.

TheDataViewconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedDataViewbehaviourmustincludeasupercalltothe
DataViewconstructortocreateandinitializesubclassinstanceswiththeinternalstatenecessarytosupportthe
DataView.prototypebuiltinmethods.

24.2.2.1 DataView(buffer,byteOffset,byteLength)

DataViewcalledwithargumentsbuffer,byteOffset,andbyteLengthperformsthefollowingsteps:
1.IfNewTargetisundeined,throwaTypeErrorexception.
2.IfType(buffer)isnotObject,throwaTypeErrorexception.
3.Ifbufferdoesnothavean[[ArrayBufferData]]internalslot,throwaTypeErrorexception.
4.LetnumberOffsetbe?ToNumber(byteOffset).
5.LetoffsetbeToInteger(numberOffset).
6.IfnumberOffsetoffsetoroffset<0,throwaRangeErrorexception.
7.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
8.LetbufferByteLengthbethevalueofbuffer's[[ArrayBufferByteLength]]internalslot.
9.Ifoffset>bufferByteLength,throwaRangeErrorexception.
10.IfbyteLengthisundeined,then
a.LetviewByteLengthbebufferByteLengthoffset.
11.Else,
a.LetviewByteLengthbe?ToLength(byteLength).
b.Ifoffset+viewByteLength>bufferByteLength,throwaRangeErrorexception.
12.LetObe?OrdinaryCreateFromConstructor(NewTarget,"%DataViewPrototype%",[[DataView]],
[[ViewedArrayBuffer]],[[ByteLength]],[[ByteOffset]]).
13.SetO's[[DataView]]internalslottotrue.
14.SetO's[[ViewedArrayBuffer]]internalslottobuffer.
15.SetO's[[ByteLength]]internalslottoviewByteLength.
16.SetO's[[ByteOffset]]internalslottooffset.
17.ReturnO.

24.2.3 PropertiesoftheDataViewConstructor

Thevalueofthe[[Prototype]]internalslotoftheDataViewconstructoristheintrinsicobject%FunctionPrototype%.

TheDataViewconstructorhasthefollowingproperties:

24.2.3.1 DataView.prototype

TheinitialvalueofDataView.prototypeistheintrinsicobject%DataViewPrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

24.2.4 PropertiesoftheDataViewPrototypeObject

TheDataViewprototypeobjectistheintrinsicobject%DataViewPrototype%.Thevalueofthe[[Prototype]]internalslotof
theDataViewprototypeobjectistheintrinsicobject%ObjectPrototype%.TheDataViewprototypeobjectisanordinary
object.Itdoesnothavea[[DataView]],[[ViewedArrayBuffer]],[[ByteLength]],or[[ByteOffset]]internalslot.

24.2.4.1 getDataView.prototype.buffer

DataView.prototype.bufferisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunction
performsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[ViewedArrayBuffer]]internalslot,throwaTypeErrorexception.
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.Returnbuffer.

24.2.4.2 getDataView.prototype.byteLength

DataView.prototype.byteLengthisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[ViewedArrayBuffer]]internalslot,throwaTypeErrorexception.
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
6.LetsizebethevalueofO's[[ByteLength]]internalslot.
7.Returnsize.

24.2.4.3 getDataView.prototype.byteOffset

DataView.prototype.byteOffsetisanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessor
functionperformsthefollowingsteps:

1.LetObethethisvalue.
2.IfType(O)isnotObject,throwaTypeErrorexception.
3.IfOdoesnothavea[[ViewedArrayBuffer]]internalslot,throwaTypeErrorexception.
4.LetbufferbethevalueofO's[[ViewedArrayBuffer]]internalslot.
5.IfIsDetachedBuffer(buffer)istrue,throwaTypeErrorexception.
6.LetoffsetbethevalueofO's[[ByteOffset]]internalslot.
7.Returnoffset.

24.2.4.4 DataView.prototype.constructor

TheinitialvalueofDataView.prototype.constructoristheintrinsicobject%DataView%.

24.2.4.5 DataView.prototype.getFloat32(byteOffset[,littleEndian])

WhenthegetFloat32methodiscalledwithargumentbyteOffsetandoptionalargumentlittleEndian,thefollowingstepsare
taken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?GetViewValue(v,byteOffset,littleEndian,"Float32").

24.2.4.6 DataView.prototype.getFloat64(byteOffset[,littleEndian])

WhenthegetFloat64methodiscalledwithargumentbyteOffsetandoptionalargumentlittleEndian,thefollowingstepsare
taken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?GetViewValue(v,byteOffset,littleEndian,"Float64").

24.2.4.7 DataView.prototype.getInt8(byteOffset)

WhenthegetInt8methodiscalledwithargumentbyteOffset,thefollowingstepsaretaken:

1.Letvbethethisvalue.
2.Return?GetViewValue(v,byteOffset,true,"Int8").

24.2.4.8 DataView.prototype.getInt16(byteOffset[,littleEndian])

WhenthegetInt16methodiscalledwithargumentbyteOffsetandoptionalargumentlittleEndian,thefollowingstepsare
taken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?GetViewValue(v,byteOffset,littleEndian,"Int16").

24.2.4.9 DataView.prototype.getInt32(byteOffset[,littleEndian])
WhenthegetInt32methodiscalledwithargumentbyteOffsetandoptionalargumentlittleEndian,thefollowingstepsare
taken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbeundeined.
3.Return?GetViewValue(v,byteOffset,littleEndian,"Int32").

24.2.4.10 DataView.prototype.getUint8(byteOffset)

WhenthegetUint8methodiscalledwithargumentbyteOffset,thefollowingstepsaretaken:

1.Letvbethethisvalue.
2.Return?GetViewValue(v,byteOffset,true,"Uint8").

24.2.4.11 DataView.prototype.getUint16(byteOffset[,littleEndian])

WhenthegetUint16methodiscalledwithargumentbyteOffsetandoptionalargumentlittleEndian,thefollowingstepsare
taken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?GetViewValue(v,byteOffset,littleEndian,"Uint16").

24.2.4.12 DataView.prototype.getUint32(byteOffset[,littleEndian])

WhenthegetUint32methodiscalledwithargumentbyteOffsetandoptionalargumentlittleEndian,thefollowingstepsare
taken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?GetViewValue(v,byteOffset,littleEndian,"Uint32").

24.2.4.13 DataView.prototype.setFloat32(byteOffset,value[,littleEndian])

WhenthesetFloat32methodiscalledwithargumentsbyteOffsetandvalueandoptionalargumentlittleEndian,the
followingstepsaretaken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?SetViewValue(v,byteOffset,littleEndian,"Float32",value).

24.2.4.14 DataView.prototype.setFloat64(byteOffset,value[,littleEndian])

WhenthesetFloat64methodiscalledwithargumentsbyteOffsetandvalueandoptionalargumentlittleEndian,the
followingstepsaretaken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?SetViewValue(v,byteOffset,littleEndian,"Float64",value).

24.2.4.15 DataView.prototype.setInt8(byteOffset,value)

WhenthesetInt8methodiscalledwithargumentsbyteOffsetandvalue,thefollowingstepsaretaken:

1.Letvbethethisvalue.
2.Return?SetViewValue(v,byteOffset,true,"Int8",value).

24.2.4.16 DataView.prototype.setInt16(byteOffset,value[,littleEndian])
WhenthesetInt16methodiscalledwithargumentsbyteOffsetandvalueandoptionalargumentlittleEndian,thefollowing
stepsaretaken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?SetViewValue(v,byteOffset,littleEndian,"Int16",value).

24.2.4.17 DataView.prototype.setInt32(byteOffset,value[,littleEndian])

WhenthesetInt32methodiscalledwithargumentsbyteOffsetandvalueandoptionalargumentlittleEndian,thefollowing
stepsaretaken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?SetViewValue(v,byteOffset,littleEndian,"Int32",value).

24.2.4.18 DataView.prototype.setUint8(byteOffset,value)

WhenthesetUint8methodiscalledwithargumentsbyteOffsetandvalue,thefollowingstepsaretaken:

1.Letvbethethisvalue.
2.Return?SetViewValue(v,byteOffset,true,"Uint8",value).

24.2.4.19 DataView.prototype.setUint16(byteOffset,value[,littleEndian])

WhenthesetUint16methodiscalledwithargumentsbyteOffsetandvalueandoptionalargumentlittleEndian,thefollowing
stepsaretaken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?SetViewValue(v,byteOffset,littleEndian,"Uint16",value).

24.2.4.20 DataView.prototype.setUint32(byteOffset,value[,littleEndian])

WhenthesetUint32methodiscalledwithargumentsbyteOffsetandvalueandoptionalargumentlittleEndian,thefollowing
stepsaretaken:

1.Letvbethethisvalue.
2.IflittleEndianisnotpresent,letlittleEndianbefalse.
3.Return?SetViewValue(v,byteOffset,littleEndian,"Uint32",value).

24.2.4.21 DataView.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"DataView".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

24.2.5 PropertiesofDataViewInstances

DataViewinstancesareordinaryobjectsthatinheritpropertiesfromtheDataViewprototypeobject.DataViewinstances
eachhave[[DataView]],[[ViewedArrayBuffer]],[[ByteLength]],and[[ByteOffset]]internalslots.

NOTE Thevalueofthe[[DataView]]internalslotisnotusedwithinthisspeciication.Thesimplepresenceofthat
internalslotisusedwithinthespeciicationtoidentifyobjectscreatedusingtheDataViewconstructor.

24.3 TheJSONObject
TheJSONobjectisthe%JSON%intrinsicobjectandtheinitialvalueoftheJSONpropertyoftheglobalobject.TheJSON
objectisasingleordinaryobjectthatcontainstwofunctions,parseandstringify,thatareusedtoparseandconstruct
JSONtexts.TheJSONDataInterchangeFormatisdeinedinECMA404.TheJSONinterchangeformatusedinthis
speciicationisexactlythatdescribedbyECMA404.

ConformingimplementationsofJSON.parseandJSON.stringifymustsupporttheexactinterchangeformatdescribedin
theECMA404speciicationwithoutanydeletionsorextensionstotheformat.

Thevalueofthe[[Prototype]]internalslotoftheJSONobjectistheintrinsicobject%ObjectPrototype%.Thevalueofthe
[[Extensible]]internalslotoftheJSONobjectissettotrue.

TheJSONobjectdoesnothavea[[Construct]]internalmethod;itisnotpossibletousetheJSONobjectasaconstructorwith
thenewoperator.

TheJSONobjectdoesnothavea[[Call]]internalmethod;itisnotpossibletoinvoketheJSONobjectasafunction.

24.3.1 JSON.parse(text[,reviver])

TheparsefunctionparsesaJSONtext(aJSONformattedString)andproducesanECMAScriptvalue.TheJSONformatisa
subsetofthesyntaxforECMAScriptliterals,ArrayInitializersandObjectInitializers.Afterparsing,JSONobjectsarerealized
asECMAScriptobjects.JSONarraysarerealizedasECMAScriptArrayinstances.JSONstrings,numbers,booleans,andnull
arerealizedasECMAScriptStrings,Numbers,Booleans,andnull.

Theoptionalreviverparameterisafunctionthattakestwoparameters,keyandvalue.Itcanilterandtransformtheresults.
Itiscalledwitheachofthekey/valuepairsproducedbytheparse,anditsreturnvalueisusedinsteadoftheoriginalvalue.If
itreturnswhatitreceived,thestructureisnotmodiied.Ifitreturnsundeinedthenthepropertyisdeletedfromtheresult.

1.LetJTextbe?ToString(text).
2.ParseJTextinterpretedasUTF16encodedUnicodepoints(6.1.4)asaJSONtextasspeciiedinECMA404.Throwa
SyntaxErrorexceptionifJTextisnotavalidJSONtextasdeinedinthatspeciication.
3.LetscriptTextbetheresultofconcatenating"(",JText,and");".
4.LetcompletionbetheresultofparsingandevaluatingscriptTextasifitwasthesourcetextofanECMAScriptScript,but
usingthealternativedeinitionofDoubleStringCharacterprovidedbelow.TheextendedPropertyDeinitionEvaluation
semanticsdeinedinB.3.1mustnotbeusedduringtheevaluation.
5.Letunilteredbecompletion.[[Value]].
6.Assert:unilteredwillbeeitheraprimitivevalueoranobjectthatisdeinedbyeitheranArrayLiteraloranObjectLiteral.
7.IfIsCallable(reviver)istrue,then
a.LetrootbeObjectCreate(%ObjectPrototype%).
b.LetrootNamebetheemptyString.
c.LetstatusbeCreateDataProperty(root,rootName,uniltered).
d.Assert:statusistrue.
e.Return?InternalizeJSONProperty(root,rootName).
8.Else,
a.Returnuniltered.

Thelengthpropertyoftheparsefunctionis2.

JSONallowsUnicodecodeunits0x2028(LINESEPARATOR)and0x2029(PARAGRAPHSEPARATOR)todirectlyappearin
Stringliteralswithoutusinganescapesequence.Thisisenabledbyusingthefollowingalternativedeinitionof
DoubleStringCharacterwhenparsingscriptTextinstep4:

DoubleStringCharacter ::
SourceCharacter butnotoneof" or\ orU+0000throughU+001F
\ EscapeSequence

TheSVofDoubleStringCharacter :: SourceCharacter butnotoneof" or\ orU+0000throughU+001Fisthe


UTF16EncodingofthecodepointvalueofSourceCharacter.

NOTE ThesyntaxofavalidJSONtextisasubsetoftheECMAScriptPrimaryExpressionsyntax.HenceavalidJSONtext
isalsoavalidPrimaryExpression.Step2aboveveriiesthatJTextconformstothatsubset.WhenscriptTextis
parsedandevaluatedasaScripttheresultwillbeeitheraString,Number,Boolean,orNullprimitivevalueor
anObjectdeinedasifbyanArrayLiteralorObjectLiteral.

24.3.1.1 RuntimeSemantics:InternalizeJSONProperty(holder,name)

TheabstractoperationInternalizeJSONPropertyisarecursiveabstractoperationthattakestwoparameters:aholderobject
andtheStringnameofapropertyinthatobject.InternalizeJSONPropertyusesthevalueofreviverthatwasoriginallypassed
totheaboveparsefunction.

1.Letvalbe?Get(holder,name).
2.IfType(val)isObject,then
a.LetisArraybe?IsArray(val).
b.IfisArrayistrue,then
i.SetIto0.
ii.Letlenbe?ToLength(?Get(val,"length")).
iii.RepeatwhileI<len,
1.LetnewElementbe?InternalizeJSONProperty(val,!ToString(I)).
2.IfnewElementisundeined,then
a.Perform?val.[[Delete]](!ToString(I)).
3.Else,
a.Perform?CreateDataProperty(val,!ToString(I),newElement).
b.NOTEThisalgorithmintentionallydoesnotthrowanexceptionifCreateDataPropertyreturns
false.
4.Add1toI.
c.Else,
i.Letkeysbe?EnumerableOwnNames(val).
ii.ForeachStringPinkeysdo,
1.LetnewElementbe?InternalizeJSONProperty(val,P).
2.IfnewElementisundeined,then
a.Perform?val.[[Delete]](P).
3.Else,
a.Perform?CreateDataProperty(val,P,newElement).
b.NOTEThisalgorithmintentionallydoesnotthrowanexceptionifCreateDataPropertyreturns
false.
3.Return?Call(reviver,holder,name,val).

ItisnotpermittedforaconformingimplementationofJSON.parsetoextendtheJSONgrammars.Ifanimplementation
wishestosupportamodiiedorextendedJSONinterchangeformatitmustdosobydeiningadifferentparsefunction.

NOTE InthecasewherethereareduplicatenameStringswithinanobject,lexicallyprecedingvaluesforthesamekey
shallbeoverwritten.

24.3.2 JSON.stringify(value[,replacer[,space]])

ThestringifyfunctionreturnsaStringinUTF16encodedJSONformatrepresentinganECMAScriptvalue.Itcantake
threeparameters.ThevalueparameterisanECMAScriptvalue,whichisusuallyanobjectorarray,althoughitcanalsobea
String,Boolean,Numberornull.Theoptionalreplacerparameteriseitherafunctionthataltersthewayobjectsandarrays
arestringiied,oranarrayofStringsandNumbersthatactsasawhitelistforselectingtheobjectpropertiesthatwillbe
stringiied.TheoptionalspaceparameterisaStringorNumberthatallowstheresulttohavewhitespaceinjectedintoitto
improvehumanreadability.

Thesearethestepsinstringifyinganobject:

1.LetstackbeanewemptyList.
2.LetindentbetheemptyString.
3.LetPropertyListandReplacerFunctionbeundeined.
4.IfType(replacer)isObject,then
a.IfIsCallable(replacer)istrue,then
i.LetReplacerFunctionbereplacer.
b.Else,
i.LetisArraybe?IsArray(replacer).
ii.IfisArrayistrue,then
1.LetPropertyListbeanewemptyList.
2.Letlenbe?ToLength(?Get(replacer,"length")).
3.Letkbe0.
4.Repeatwhilek<len,
a.Letvbe?Get(replacer,!ToString(k)).
b.Letitembeundeined.
c.IfType(v)isString,letitembev.
d.ElseifType(v)isNumber,letitembe!ToString(v).
e.ElseifType(v)isObject,then
i.Ifvhasa[[StringData]]or[[NumberData]]internalslot,letitembe?ToString(v).
f.IfitemisnotundeinedanditemisnotcurrentlyanelementofPropertyList,then
i.AppenditemtotheendofPropertyList.
g.Letkbek+1.
5.IfType(space)isObject,then
a.Ifspacehasa[[NumberData]]internalslot,then
i.Letspacebe?ToNumber(space).
b.Elseifspacehasa[[StringData]]internalslot,then
i.Letspacebe?ToString(space).
6.IfType(space)isNumber,then
a.Letspacebemin(10,ToInteger(space)).
b.SetgaptoaStringcontainingspaceoccurrencesofcodeunit0x0020(SPACE).ThiswillbetheemptyStringif
spaceislessthan1.
7.ElseifType(space)isString,then
a.Ifthenumberofelementsinspaceis10orless,setgaptospace;otherwisesetgaptoaStringconsistingoftheirst
10elementsofspace.
8.Else,
a.SetgaptotheemptyString.
9.LetwrapperbeObjectCreate(%ObjectPrototype%).
10.LetstatusbeCreateDataProperty(wrapper,theemptyString,value).
11.Assert:statusistrue.
12.Return?SerializeJSONProperty(theemptyString,wrapper).

Thelengthpropertyofthestringifyfunctionis3.

NOTE1 JSONstructuresareallowedtobenestedtoanydepth,buttheymustbeacyclic.Ifvalueisorcontainsacyclic
structure,thenthestringifyfunctionmustthrowaTypeErrorexception.Thisisanexampleofavaluethat
cannotbestringiied:

a=[];
a[0]=a;
my_text=JSON.stringify(a);//ThismustthrowaTypeError.

NOTE2 Symbolicprimitivevaluesarerenderedasfollows:

ThenullvalueisrenderedinJSONtextastheStringnull.
Theundeinedvalueisnotrendered.
ThetruevalueisrenderedinJSONtextastheStringtrue.
ThefalsevalueisrenderedinJSONtextastheStringfalse.
NOTE3 StringvaluesarewrappedinQUOTATIONMARK(")codeunits.Thecodeunits"and\areescapedwith\
preixes.Controlcharacterscodeunitsarereplacedwithescapesequences\uHHHH,orwiththeshorter
forms,\b(BACKSPACE),\f(FORMFEED),\n(LINEFEED),\r(CARRIAGERETURN),\t(CHARACTER
TABULATION).

NOTE4 FinitenumbersarestringiiedasifbycallingToString(number).NaNandIninityregardlessofsignare
representedastheStringnull.

NOTE5 ValuesthatdonothaveaJSONrepresentation(suchasundeinedandfunctions)donotproduceaString.
Insteadtheyproducetheundeinedvalue.InarraysthesevaluesarerepresentedastheStringnull.Inobjects
anunrepresentablevaluecausesthepropertytobeexcludedfromstringiication.

NOTE6 AnobjectisrenderedasU+007B(LEFTCURLYBRACKET)followedbyzeroormoreproperties,separatedwith
aU+002C(COMMA),closedwithaU+007D(RIGHTCURLYBRACKET).ApropertyisaquotedString
representingthekeyorpropertyname,aU+003A(COLON),andthenthestringiiedpropertyvalue.Anarrayis
renderedasanopeningU+005B(LEFTSQUAREBRACKETfollowedbyzeroormorevalues,separatedwitha
U+002C(COMMA),closedwithaU+005D(RIGHTSQUAREBRACKET).

24.3.2.1 RuntimeSemantics:SerializeJSONProperty(key,holder)

TheabstractoperationSerializeJSONPropertywithargumentskey,andholderhasaccesstoReplacerFunctionfromthe
invocationofthestringifymethod.Itsalgorithmisasfollows:

1.Letvaluebe?Get(holder,key).
2.IfType(value)isObject,then
a.LettoJSONbe?Get(value,"toJSON").
b.IfIsCallable(toJSON)istrue,then
i.Letvaluebe?Call(toJSON,value,key).
3.IfReplacerFunctionisnotundeined,then
a.Letvaluebe?Call(ReplacerFunction,holder,key,value).
4.IfType(value)isObject,then
a.Ifvaluehasa[[NumberData]]internalslot,then
i.Letvaluebe?ToNumber(value).
b.Elseifvaluehasa[[StringData]]internalslot,then
i.Letvaluebe?ToString(value).
c.Elseifvaluehasa[[BooleanData]]internalslot,then
i.Letvaluebethevalueofthe[[BooleanData]]internalslotofvalue.
5.Ifvalueisnull,return"null".
6.Ifvalueistrue,return"true".
7.Ifvalueisfalse,return"false".
8.IfType(value)isString,returnQuoteJSONString(value).
9.IfType(value)isNumber,then
a.Ifvalueisinite,return!ToString(value).
b.Else,return"null".
10.IfType(value)isObjectandIsCallable(value)isfalse,then
a.LetisArraybe?IsArray(value).
b.IfisArrayistrue,return?SerializeJSONArray(value).
c.Else,return?SerializeJSONObject(value).
11.Returnundeined.

24.3.2.2 RuntimeSemantics:QuoteJSONString(value)

TheabstractoperationQuoteJSONStringwithargumentvaluewrapsaStringvalueinQUOTATIONMARKcodeunitsand
escapescertainothercodeunitswithinit.

1.Letproductbecodeunit0x0022(QUOTATIONMARK).
2.ForeachcodeunitCinvalue
a.IfCis0x0022(QUOTATIONMARK)or0x005C(REVERSESOLIDUS),then
i.Letproductbetheconcatenationofproductandcodeunit0x005C(REVERSESOLIDUS).
ii.LetproductbetheconcatenationofproductandC.
b.ElseifCis0x0008(BACKSPACE),0x000C(FORMFEED),0x000A(LINEFEED),0x000D(CARRIAGERETURN),or
0x0009(CHARACTERTABULATION),then
i.Letproductbetheconcatenationofproductandcodeunit0x005C(REVERSESOLIDUS).
ii.LetabbrevbetheStringvaluecorrespondingtothevalueofCasfollows:
BACKSPACE "b"
FORMFEED(FF) "f"
LINEFEED(LF) "n"
CARRIAGERETURN(CR) "r"
CHARACTERTABULATION "t"
iii.Letproductbetheconcatenationofproductandabbrev.
c.ElseifChasacodeunitvaluelessthan0x0020(SPACE),then
i.Letproductbetheconcatenationofproductandcodeunit0x005C(REVERSESOLIDUS).
ii.Letproductbetheconcatenationofproductand"u".
iii.LethexbethestringresultofconvertingthenumericcodeunitvalueofCtoaStringoffourhexadecimal
digits.AlphabetichexadecimaldigitsarepresentedaslowercaseLatinletters.
iv.Letproductbetheconcatenationofproductandhex.
d.Else,
i.LetproductbetheconcatenationofproductandC.
3.Letproductbetheconcatenationofproductandcodeunit0x0022(QUOTATIONMARK).
4.Returnproduct.

24.3.2.3 RuntimeSemantics:SerializeJSONObject(value)

TheabstractoperationSerializeJSONObjectwithargumentvalueserializesanobject.Ithasaccesstothestack,indent,gap,
andPropertyListvaluesofthecurrentinvocationofthestringifymethod.

1.Ifstackcontainsvalue,throwaTypeErrorexceptionbecausethestructureiscyclical.
2.Appendvaluetostack.
3.Letstepbackbeindent.
4.Letindentbetheconcatenationofindentandgap.
5.IfPropertyListisnotundeined,then
a.LetKbePropertyList.
6.Else,
a.LetKbe?EnumerableOwnNames(value).
7.LetpartialbeanewemptyList.
8.ForeachelementPofK,
a.LetstrPbe?SerializeJSONProperty(P,value).
b.IfstrPisnotundeined,then
i.LetmemberbeQuoteJSONString(P).
ii.Letmemberbetheconcatenationofmemberandthestring":".
iii.IfgapisnottheemptyString,then
1.Letmemberbetheconcatenationofmemberandcodeunit0x0020(SPACE).
iv.LetmemberbetheconcatenationofmemberandstrP.
v.Appendmembertopartial.
9.Ifpartialisempty,then
a.Letinalbe"{}".
10.Else,
a.IfgapistheemptyString,then
i.LetpropertiesbeaStringformedbyconcatenatingalltheelementStringsofpartialwitheachadjacentpairof
Stringsseparatedwithcodeunit0x002C(COMMA).AcommaisnotinsertedeitherbeforetheirstStringor
afterthelastString.
ii.Letinalbetheresultofconcatenating"{",properties,and"}".
b.ElsegapisnottheemptyString
i.Letseparatorbetheresultofconcatenatingcodeunit0x002C(COMMA),codeunit0x000A(LINEFEED),and
indent.
ii.LetpropertiesbeaStringformedbyconcatenatingalltheelementStringsofpartialwitheachadjacentpairof
Stringsseparatedwithseparator.TheseparatorStringisnotinsertedeitherbeforetheirstStringorafterthe
lastString.
iii.Letinalbetheresultofconcatenating"{",codeunit0x000A(LINEFEED),indent,properties,codeunit
0x000A(LINEFEED),stepback,and"}".
11.Removethelastelementofstack.
12.Letindentbestepback.
13.Returninal.

24.3.2.4 RuntimeSemantics:SerializeJSONArray(value)

TheabstractoperationSerializeJSONArraywithargumentvalueserializesanarray.Ithasaccesstothestack,indent,andgap
valuesofthecurrentinvocationofthestringifymethod.

1.Ifstackcontainsvalue,throwaTypeErrorexceptionbecausethestructureiscyclical.
2.Appendvaluetostack.
3.Letstepbackbeindent.
4.Letindentbetheconcatenationofindentandgap.
5.LetpartialbeanewemptyList.
6.Letlenbe?ToLength(?Get(value,"length")).
7.Letindexbe0.
8.Repeatwhileindex<len
a.LetstrPbe?SerializeJSONProperty(!ToString(index),value).
b.IfstrPisundeined,then
i.Append"null"topartial.
c.Else,
i.AppendstrPtopartial.
d.Incrementindexby1.
9.Ifpartialisempty,then
a.Letinalbe"[]".
10.Else,
a.IfgapistheemptyString,then
i.LetpropertiesbeaStringformedbyconcatenatingalltheelementStringsofpartialwitheachadjacentpairof
Stringsseparatedwithcodeunit0x002C(COMMA).AcommaisnotinsertedeitherbeforetheirstStringor
afterthelastString.
ii.Letinalbetheresultofconcatenating"[",properties,and"]".
b.Else,
i.Letseparatorbetheresultofconcatenatingcodeunit0x002C(COMMA),codeunit0x000A(LINEFEED),and
indent.
ii.LetpropertiesbeaStringformedbyconcatenatingalltheelementStringsofpartialwitheachadjacentpairof
Stringsseparatedwithseparator.TheseparatorStringisnotinsertedeitherbeforetheirstStringorafterthe
lastString.
iii.Letinalbetheresultofconcatenating"[",codeunit0x000A(LINEFEED),indent,properties,codeunit
0x000A(LINEFEED),stepback,and"]".
11.Removethelastelementofstack.
12.Letindentbestepback.
13.Returninal.

NOTE Therepresentationofarraysincludesonlytheelementsbetweenzeroandarray.length1inclusive.
Propertieswhosekeysarenotarrayindexesareexcludedfromthestringiication.Anarrayisstringiiedasan
openingLEFTSQUAREBRACKET,elementsseparatedbyCOMMA,andaclosingRIGHTSQUAREBRACKET.

24.3.3 JSON[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"JSON".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25 ControlAbstractionObjects
25.1 Iteration
25.1.1 CommonIterationInterfaces

Aninterfaceisasetofpropertykeyswhoseassociatedvaluesmatchaspeciicspeciication.Anyobjectthatprovidesallthe
propertiesasdescribedbyaninterface'sspeciicationconformstothatinterface.Aninterfaceisnotrepresentedbyadistinct
object.Theremaybemanyseparatelyimplementedobjectsthatconformtoanyinterface.Anindividualobjectmayconform
tomultipleinterfaces.

25.1.1.1 TheIterableInterface

TheIterableinterfaceincludesthepropertydescribedinTable53:

Table53:IterableInterfaceRequiredProperties
Property Value Requirements

@@iterator AfunctionthatreturnsanIteratorobject. ThereturnedobjectmustconformtotheIteratorinterface.

25.1.1.2 TheIteratorInterface

AnobjectthatimplementstheIteratorinterfacemustincludethepropertyinTable54.Suchobjectsmayalsoimplementthe
propertiesinTable55.

Table54:IteratorInterfaceRequiredProperties
Property Value Requirements

next Afunction ThereturnedobjectmustconformtotheIteratorResultinterface.Ifapreviouscalltothenext


thatreturns methodofanIteratorhasreturnedanIteratorResultobjectwhosedonepropertyistrue,then
an allsubsequentcallstothenextmethodofthatobjectshouldalsoreturnanIteratorResult
IteratorResult objectwhosedonepropertyistrue.However,thisrequirementisnotenforced.
object.

NOTE1 Argumentsmaybepassedtothenextfunctionbuttheirinterpretationandvalidityisdependentuponthe
targetIterator.TheforofstatementandothercommonusersofIteratorsdonotpassanyarguments,so
Iteratorobjectsthatexpecttobeusedinsuchamannermustbepreparedtodealwithbeingcalledwithno
arguments.
Table55:IteratorInterfaceOptionalProperties
Property Value Requirements

return Afunction ThereturnedobjectmustconformtotheIteratorResultinterface.Invokingthismethodnotiies


thatreturns theIteratorobjectthatthecallerdoesnotintendtomakeanymorenextmethodcallstothe
an Iterator.ThereturnedIteratorResultobjectwilltypicallyhaveadonepropertywhosevalueis
IteratorResult true,andavaluepropertywiththevaluepassedastheargumentofthereturnmethod.
object. However,thisrequirementisnotenforced.

throw Afunction ThereturnedobjectmustconformtotheIteratorResultinterface.Invokingthismethodnotiies


thatreturns theIteratorobjectthatthecallerhasdetectedanerrorcondition.Theargumentmaybeusedto
an identifytheerrorconditionandtypicallywillbeanexceptionobject.Atypicalresponseisto
IteratorResult throwthevaluepassedastheargument.Ifthemethoddoesnotthrow,thereturned
object. IteratorResultobjectwilltypicallyhaveadonepropertywhosevalueistrue.

NOTE2 Typicallycallersofthesemethodsshouldcheckfortheirexistencebeforeinvokingthem.CertainECMAScript
languagefeaturesincludingforof,yield*,andarraydestructuringcallthesemethodsafterperformingan
existencecheck.MostECMAScriptlibraryfunctionsthatacceptIterableobjectsasargumentsalsoconditionally
callthem.

25.1.1.3 TheIteratorResultInterface

TheIteratorResultinterfaceincludesthepropertieslistedinTable56:

Table56:IteratorResultInterfaceProperties
Property Value Requirements

done Eithertrue Thisistheresultstatusofaniteratornextmethodcall.Iftheendoftheiteratorwasreached


orfalse. doneistrue.Iftheendwasnotreacheddoneisfalseandavalueisavailable.Ifadoneproperty
(eitherownorinherited)doesnotexist,itisconsidertohavethevaluefalse.

value Any Ifdoneisfalse,thisisthecurrentiterationelementvalue.Ifdoneistrue,thisisthereturnvalue


ECMAScript oftheiterator,ifitsuppliedone.Iftheiteratordoesnothaveareturnvalue,valueisundeined.
language Inthatcase,thevaluepropertymaybeabsentfromtheconformingobjectifitdoesnotinherit
value. anexplicitvalueproperty.

25.1.2 The%IteratorPrototype%Object

Thevalueofthe[[Prototype]]internalslotofthe%IteratorPrototype%objectistheintrinsicobject%ObjectPrototype%.The
%IteratorPrototype%objectisanordinaryobject.Theinitialvalueofthe[[Extensible]]internalslotofthe
%IteratorPrototype%objectistrue.

NOTE AllobjectsdeinedinthisspeciicationthatimplementtheIteratorinterfacealsoinheritfrom
%IteratorPrototype%.ECMAScriptcodemayalsodeineobjectsthatinheritfrom%IteratorPrototype%.The
%IteratorPrototype%objectprovidesaplacewhereadditionalmethodsthatareapplicabletoalliterator
objectsmaybeadded.

ThefollowingexpressionisonewaythatECMAScriptcodecanaccessthe%IteratorPrototype%object:

Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))

25.1.2.1 %IteratorPrototype%[@@iterator]()

Thefollowingstepsaretaken:
1.Returnthethisvalue.

Thevalueofthenamepropertyofthisfunctionis"[Symbol.iterator]".

25.2 GeneratorFunctionObjects
GeneratorFunctionobjectsarefunctionsthatareusuallycreatedbyevaluatingGeneratorDeclaration,GeneratorExpression,
andGeneratorMethodsyntacticproductions.Theymayalsobecreatedbycallingthe%GeneratorFunction%intrinsic.

Figure2(Informative):GeneratorObjectsRelationships

25.2.1 TheGeneratorFunctionConstructor

TheGeneratorFunctionconstructoristhe%GeneratorFunction%intrinsic.WhenGeneratorFunctioniscalledasa
functionratherthanasaconstructor,itcreatesandinitializesanewGeneratorFunctionobject.Thusthefunctioncall
GeneratorFunction()isequivalenttotheobjectcreationexpressionnewGeneratorFunction()withthesame
arguments.

GeneratorFunctionisdesignedtobesubclassable.Itmaybeusedasthevalueofanextendsclauseofaclassdeinition.
SubclassconstructorsthatintendtoinheritthespeciiedGeneratorFunctionbehaviourmustincludeasupercalltothe
GeneratorFunctionconstructortocreateandinitializesubclassinstanceswiththeinternalslotsnecessaryforbuiltin
GeneratorFunctionbehaviour.AllECMAScriptsyntacticformsfordeininggeneratorfunctionobjectscreatedirectinstances
ofGeneratorFunction.ThereisnosyntacticmeanstocreateinstancesofGeneratorFunctionsubclasses.

25.2.1.1 GeneratorFunction(p1,p2,,pn,body)

Thelastargumentspeciiesthebody(executablecode)ofageneratorfunction;anyprecedingargumentsspecifyformal
parameters.
WhentheGeneratorFunctionfunctioniscalledwithsomeargumentsp1,p2,,pn,body(wherenmightbe0,thatis,there
arenoparguments,andwherebodymightalsonotbeprovided),thefollowingstepsaretaken:

1.LetCbetheactivefunctionobject.
2.LetargsbetheargumentsListthatwaspassedtothisfunctionby[[Call]]or[[Construct]].
3.Return?CreateDynamicFunction(C,NewTarget,"generator",args).

NOTE SeeNOTEfor19.2.1.1.

25.2.2 PropertiesoftheGeneratorFunctionConstructor

TheGeneratorFunctionconstructorisastandardbuiltinfunctionobjectthatinheritsfromtheFunctionconstructor.The
valueofthe[[Prototype]]internalslotoftheGeneratorFunctionconstructoristheintrinsicobject%Function%.

Thevalueofthe[[Extensible]]internalslotoftheGeneratorFunctionconstructoristrue.

ThevalueofthenamepropertyoftheGeneratorFunctionis"GeneratorFunction".

TheGeneratorFunctionconstructorhasthefollowingproperties:

25.2.2.1 GeneratorFunction.length

Thisisadatapropertywithavalueof1.Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,
[[Conigurable]]:true}.

25.2.2.2 GeneratorFunction.prototype

TheinitialvalueofGeneratorFunction.prototypeistheintrinsicobject%Generator%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

25.2.3 PropertiesoftheGeneratorFunctionPrototypeObject

TheGeneratorFunctionprototypeobjectisanordinaryobject.Itisnotafunctionobjectanddoesnothavean
[[ECMAScriptCode]]internalslotoranyotheroftheinternalslotslistedinTable27orTable57.Inadditiontobeingthe
valueoftheprototypepropertyofthe%GeneratorFunction%intrinsic,itisthe%Generator%intrinsic(seeFigure2).

Thevalueofthe[[Prototype]]internalslotoftheGeneratorFunctionprototypeobjectisthe%FunctionPrototype%intrinsic
object.Theinitialvalueofthe[[Extensible]]internalslotoftheGeneratorFunctionprototypeobjectistrue.

25.2.3.1 GeneratorFunction.prototype.constructor

TheinitialvalueofGeneratorFunction.prototype.constructoristheintrinsicobject%GeneratorFunction%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25.2.3.2 GeneratorFunction.prototype.prototype

ThevalueofGeneratorFunction.prototype.prototypeisthe%GeneratorPrototype%intrinsicobject.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25.2.3.3 GeneratorFunction.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"GeneratorFunction".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25.2.4 GeneratorFunctionInstances
EveryGeneratorFunctioninstanceisanECMAScriptfunctionobjectandhastheinternalslotslistedinTable27.Thevalueof
the[[FunctionKind]]internalslotforallsuchinstancesis"generator".

EachGeneratorFunctioninstancehasthefollowingownproperties:

25.2.4.1 length

Thevalueofthelengthpropertyisanintegerthatindicatesthetypicalnumberofargumentsexpectedbythe
GeneratorFunction.However,thelanguagepermitsthefunctiontobeinvokedwithsomeothernumberofarguments.The
behaviourofaGeneratorFunctionwheninvokedonanumberofargumentsotherthanthenumberspeciiedbyitslength
propertydependsonthefunction.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25.2.4.2 name

ThespeciicationforthenamepropertyofFunctioninstancesgivenin19.2.4.2alsoappliestoGeneratorFunctioninstances.

25.2.4.3 prototype

WheneveraGeneratorFunctioninstanceiscreatedanotherordinaryobjectisalsocreatedandistheinitialvalueofthe
generatorfunction'sprototypeproperty.Thevalueoftheprototypepropertyisusedtoinitializethe[[Prototype]]internal
slotofanewlycreatedGeneratorobjectwhenthegeneratorfunctionobjectisinvokedusing[[Call]].

Thispropertyhastheattributes{[[Writable]]:true,[[Enumerable]]:false,[[Conigurable]]:false}.

NOTE Unlikefunctioninstances,theobjectthatisthevalueoftheaGeneratorFunction'sprototypepropertydoes
nothaveaconstructorpropertywhosevalueistheGeneratorFunctioninstance.

25.3 GeneratorObjects
AGeneratorobjectisaninstanceofageneratorfunctionandconformstoboththeIteratorandIterableinterfaces.

GeneratorinstancesdirectlyinheritpropertiesfromtheobjectthatisthevalueoftheprototypepropertyoftheGenerator
functionthatcreatedtheinstance.GeneratorinstancesindirectlyinheritpropertiesfromtheGeneratorPrototypeintrinsic,
%GeneratorPrototype%.

25.3.1 PropertiesofGeneratorPrototype

TheGeneratorprototypeobjectisthe%GeneratorPrototype%intrinsic.Itisalsotheinitialvalueoftheprototypeproperty
ofthe%Generator%intrinsic(theGeneratorFunction.prototype).

TheGeneratorprototypeisanordinaryobject.ItisnotaGeneratorinstanceanddoesnothavea[[GeneratorState]]internal
slot.

Thevalueofthe[[Prototype]]internalslotoftheGeneratorprototypeobjectistheintrinsicobject%IteratorPrototype%.
Theinitialvalueofthe[[Extensible]]internalslotoftheGeneratorprototypeobjectistrue.

AllGeneratorinstancesindirectlyinheritpropertiesoftheGeneratorprototypeobject.

25.3.1.1 Generator.prototype.constructor

TheinitialvalueofGenerator.prototype.constructoristheintrinsicobject%Generator%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25.3.1.2 Generator.prototype.next(value)

Thenextmethodperformsthefollowingsteps:
1.Letgbethethisvalue.
2.Return?GeneratorResume(g,value).

25.3.1.3 Generator.prototype.return(value)

Thereturnmethodperformsthefollowingsteps:

1.Letgbethethisvalue.
2.LetCbeCompletion{[[Type]]:return,[[Value]]:value,[[Target]]:empty}.
3.Return?GeneratorResumeAbrupt(g,C).

25.3.1.4 Generator.prototype.throw(exception)

Thethrowmethodperformsthefollowingsteps:

1.Letgbethethisvalue.
2.LetCbeCompletion{[[Type]]:throw,[[Value]]:exception,[[Target]]:empty}.
3.Return?GeneratorResumeAbrupt(g,C).

25.3.1.5 Generator.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"Generator".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25.3.2 PropertiesofGeneratorInstances

GeneratorinstancesareinitiallycreatedwiththeinternalslotsdescribedinTable57.

Table57:InternalSlotsofGeneratorInstances
InternalSlot Description

[[GeneratorState]] Thecurrentexecutionstateofthegenerator.Thepossiblevaluesare:undeined,
"suspendedStart","suspendedYield","executing",and"completed".

[[GeneratorContext]] Theexecutioncontextthatisusedwhenexecutingthecodeofthisgenerator.

25.3.3 GeneratorAbstractOperations

25.3.3.1 GeneratorStart(generator,generatorBody)

TheabstractoperationGeneratorStartwithargumentsgeneratorandgeneratorBodyperformsthefollowingsteps:

1.Assert:Thevalueofgenerator's[[GeneratorState]]internalslotisundeined.
2.LetgenContextbetherunningexecutioncontext.
3.SettheGeneratorcomponentofgenContexttogenerator.
4.SetthecodeevaluationstateofgenContextsuchthatwhenevaluationisresumedforthatexecutioncontextthe
followingstepswillbeperformed:
a.LetresultbetheresultofevaluatinggeneratorBody.
b.Assert:Ifwereturnhere,thegeneratoreitherthrewanexceptionorperformedeitheranimplicitorexplicit
return.
c.RemovegenContextfromtheexecutioncontextstackandrestoretheexecutioncontextthatisatthetopofthe
executioncontextstackastherunningexecutioncontext.
d.Setgenerator's[[GeneratorState]]internalslotto"completed".
e.Onceageneratorentersthe"completed"stateitneverleavesitanditsassociatedexecutioncontextisnever
resumed.Anyexecutionstateassociatedwithgeneratorcanbediscardedatthispoint.
f.Ifresultisanormalcompletion,letresultValuebeundeined.
g.Else,
i.Ifresult.[[Type]]isreturn,letresultValueberesult.[[Value]].
ii.Else,returnCompletion(result).
h.ReturnCreateIterResultObject(resultValue,true).
5.Setgenerator's[[GeneratorContext]]internalslottogenContext.
6.Setgenerator's[[GeneratorState]]internalslotto"suspendedStart".
7.ReturnNormalCompletion(undeined).

25.3.3.2 GeneratorValidate(generator)

TheabstractoperationGeneratorValidatewithargumentgeneratorperformsthefollowingsteps:

1.IfType(generator)isnotObject,throwaTypeErrorexception.
2.Ifgeneratordoesnothavea[[GeneratorState]]internalslot,throwaTypeErrorexception.
3.Assert:generatoralsohasa[[GeneratorContext]]internalslot.
4.Letstatebethevalueofgenerator's[[GeneratorState]]internalslot.
5.Ifstateis"executing",throwaTypeErrorexception.
6.Returnstate.

25.3.3.3 GeneratorResume(generator,value)

TheabstractoperationGeneratorResumewithargumentsgeneratorandvalueperformsthefollowingsteps:

1.Letstatebe?GeneratorValidate(generator).
2.Ifstateis"completed",returnCreateIterResultObject(undeined,true).
3.Assert:stateiseither"suspendedStart"or"suspendedYield".
4.LetgenContextbethevalueofgenerator's[[GeneratorContext]]internalslot.
5.LetmethodContextbetherunningexecutioncontext.
6.SuspendmethodContext.
7.Setgenerator's[[GeneratorState]]internalslotto"executing".
8.PushgenContextontotheexecutioncontextstack;genContextisnowtherunningexecutioncontext.
9.ResumethesuspendedevaluationofgenContextusingNormalCompletion(value)astheresultoftheoperationthat
suspendedit.Letresultbethevaluereturnedbytheresumedcomputation.
10.Assert:Whenwereturnhere,genContexthasalreadybeenremovedfromtheexecutioncontextstackand
methodContextisthecurrentlyrunningexecutioncontext.
11.ReturnCompletion(result).

25.3.3.4 GeneratorResumeAbrupt(generator,abruptCompletion)

TheabstractoperationGeneratorResumeAbruptwithargumentsgeneratorandabruptCompletionperformsthefollowing
steps:

1.Letstatebe?GeneratorValidate(generator).
2.Ifstateis"suspendedStart",then
a.Setgenerator's[[GeneratorState]]internalslotto"completed".
b.Onceageneratorentersthe"completed"stateitneverleavesitanditsassociatedexecutioncontextisnever
resumed.Anyexecutionstateassociatedwithgeneratorcanbediscardedatthispoint.
c.Letstatebe"completed".
3.Ifstateis"completed",then
a.IfabruptCompletion.[[Type]]isreturn,then
i.ReturnCreateIterResultObject(abruptCompletion.[[Value]],true).
b.ReturnCompletion(abruptCompletion).
4.Assert:stateis"suspendedYield".
5.LetgenContextbethevalueofgenerator's[[GeneratorContext]]internalslot.
6.LetmethodContextbetherunningexecutioncontext.
7.SuspendmethodContext.
8.Setgenerator's[[GeneratorState]]internalslotto"executing".
9.PushgenContextontotheexecutioncontextstack;genContextisnowtherunningexecutioncontext.
10.ResumethesuspendedevaluationofgenContextusingabruptCompletionastheresultoftheoperationthatsuspended
it.Letresultbethecompletionrecordreturnedbytheresumedcomputation.
11.Assert:Whenwereturnhere,genContexthasalreadybeenremovedfromtheexecutioncontextstackand
methodContextisthecurrentlyrunningexecutioncontext.
12.ReturnCompletion(result).

25.3.3.5 GeneratorYield(iterNextObj)

TheabstractoperationGeneratorYieldwithargumentiterNextObjperformsthefollowingsteps:

1.Assert:iterNextObjisanObjectthatimplementstheIteratorResultinterface.
2.LetgenContextbetherunningexecutioncontext.
3.Assert:genContextistheexecutioncontextofagenerator.
4.LetgeneratorbethevalueoftheGeneratorcomponentofgenContext.
5.Setthevalueofgenerator's[[GeneratorState]]internalslotto"suspendedYield".
6.RemovegenContextfromtheexecutioncontextstackandrestoretheexecutioncontextthatisatthetopoftheexecution
contextstackastherunningexecutioncontext.
7.SetthecodeevaluationstateofgenContextsuchthatwhenevaluationisresumedwithaCompletionresumptionValue
thefollowingstepswillbeperformed:
a.ReturnresumptionValue.
b.NOTE:ThisreturnstotheevaluationoftheYieldExpressionproductionthatoriginallycalledthisabstract
operation.
8.ReturnNormalCompletion(iterNextObj).
9.NOTE:ThisreturnstotheevaluationoftheoperationthathadmostpreviouslyresumedevaluationofgenContext.

25.4 PromiseObjects
APromiseisanobjectthatisusedasaplaceholderfortheeventualresultsofadeferred(andpossiblyasynchronous)
computation.

AnyPromiseobjectisinoneofthreemutuallyexclusivestates:fulilled,rejected,andpending:

Apromisepisfulilledifp.then(f,r)willimmediatelyenqueueaJobtocallthefunctionf.
Apromisepisrejectedifp.then(f,r)willimmediatelyenqueueaJobtocallthefunctionr.
Apromiseispendingifitisneitherfulillednorrejected.

Apromiseissaidtobesettledifitisnotpending,i.e.ifitiseitherfulilledorrejected.

Apromiseisresolvedifitissettledorifithasbeenlockedintomatchthestateofanotherpromise.Attemptingtoresolveor
rejectaresolvedpromisehasnoeffect.Apromiseisunresolvedifitisnotresolved.Anunresolvedpromiseisalwaysinthe
pendingstate.Aresolvedpromisemaybepending,fulilledorrejected.

25.4.1 PromiseAbstractOperations

25.4.1.1 PromiseCapabilityRecords

APromiseCapabilityisaRecordvalueusedtoencapsulateapromiseobjectalongwiththefunctionsthatarecapableof
resolvingorrejectingthatpromiseobject.PromiseCapabilityrecordsareproducedbytheNewPromiseCapabilityabstract
operation.

PromiseCapabilityRecordshavetheieldslistedinTable58.
Table58:PromiseCapabilityRecordFields
FieldName Value Meaning

[[Promise]] Anobject Anobjectthatisusableasapromise.

[[Resolve]] Afunctionobject Thefunctionthatisusedtoresolvethegivenpromiseobject.

[[Reject]] Afunctionobject Thefunctionthatisusedtorejectthegivenpromiseobject.

25.4.1.1.1 IfAbruptRejectPromise(value,capability)

IfAbruptRejectPromiseisashorthandforasequenceofalgorithmstepsthatuseaPromiseCapabilityrecord.Analgorithm
stepoftheform:

1.IfAbruptRejectPromise(value,capability).

meansthesamethingas:

1.Ifvalueisanabruptcompletion,then
a.Perform?Call(capability.[[Reject]],undeined,value.[[Value]]).
b.Returncapability.[[Promise]].
2.ElseifvalueisaCompletionRecord,letvaluebevalue.[[Value]].

25.4.1.2 PromiseReactionRecords

ThePromiseReactionisaRecordvalueusedtostoreinformationabouthowapromiseshouldreactwhenitbecomes
resolvedorrejectedwithagivenvalue.PromiseReactionrecordsarecreatedbythePerformPromiseThenabstractoperation,
andareusedbyaPromiseReactionJob.

PromiseReactionrecordshavetheieldslistedinTable59.

Table59:PromiseReactionRecordFields
FieldName Value Meaning

[[Capabilities]] A Thecapabilitiesofthepromiseforwhichthisrecordprovidesareactionhandler.
PromiseCapability
record

[[Handler]] Afunctionobject Thefunctionthatshouldbeappliedtotheincomingvalue,andwhosereturnvalue


oraString willgovernwhathappenstothederivedpromise.If[[Handler]]is"Identity"itis
equivalenttoafunctionthatsimplyreturnsitsirstargument.If[[Handler]]is
"Thrower"itisequivalenttoafunctionthatthrowsitsirstargumentasan
exception.

25.4.1.3 CreateResolvingFunctions(promise)

WhenCreateResolvingFunctionsisperformedwithargumentpromise,thefollowingstepsaretaken:

1.LetalreadyResolvedbeanewRecord{[[Value]]:false}.
2.LetresolvebeanewbuiltinfunctionobjectasdeinedinPromiseResolveFunctions(25.4.1.3.2).
3.Setthe[[Promise]]internalslotofresolvetopromise.
4.Setthe[[AlreadyResolved]]internalslotofresolvetoalreadyResolved.
5.LetrejectbeanewbuiltinfunctionobjectasdeinedinPromiseRejectFunctions(25.4.1.3.1).
6.Setthe[[Promise]]internalslotofrejecttopromise.
7.Setthe[[AlreadyResolved]]internalslotofrejecttoalreadyResolved.
8.ReturnanewRecord{[[Resolve]]:resolve,[[Reject]]:reject}.
25.4.1.3.1 PromiseRejectFunctions

Apromiserejectfunctionisananonymousbuiltinfunctionthathas[[Promise]]and[[AlreadyResolved]]internalslots.

WhenapromiserejectfunctionFiscalledwithargumentreason,thefollowingstepsaretaken:

1.Assert:Fhasa[[Promise]]internalslotwhosevalueisanObject.
2.LetpromisebethevalueofF's[[Promise]]internalslot.
3.LetalreadyResolvedbethevalueofF's[[AlreadyResolved]]internalslot.
4.IfalreadyResolved.[[Value]]istrue,returnundeined.
5.SetalreadyResolved.[[Value]]totrue.
6.ReturnRejectPromise(promise,reason).

Thelengthpropertyofapromiserejectfunctionis1.

25.4.1.3.2 PromiseResolveFunctions

Apromiseresolvefunctionisananonymousbuiltinfunctionthathas[[Promise]]and[[AlreadyResolved]]internalslots.

WhenapromiseresolvefunctionFiscalledwithargumentresolution,thefollowingstepsaretaken:

1.Assert:Fhasa[[Promise]]internalslotwhosevalueisanObject.
2.LetpromisebethevalueofF's[[Promise]]internalslot.
3.LetalreadyResolvedbethevalueofF's[[AlreadyResolved]]internalslot.
4.IfalreadyResolved.[[Value]]istrue,returnundeined.
5.SetalreadyResolved.[[Value]]totrue.
6.IfSameValue(resolution,promise)istrue,then
a.LetselfResolutionErrorbeanewlycreatedTypeErrorobject.
b.ReturnRejectPromise(promise,selfResolutionError).
7.IfType(resolution)isnotObject,then
a.ReturnFulillPromise(promise,resolution).
8.LetthenbeGet(resolution,"then").
9.Ifthenisanabruptcompletion,then
a.ReturnRejectPromise(promise,then.[[Value]]).
10.LetthenActionbethen.[[Value]].
11.IfIsCallable(thenAction)isfalse,then
a.ReturnFulillPromise(promise,resolution).
12.PerformEnqueueJob("PromiseJobs",PromiseResolveThenableJob,promise,resolution,thenAction).
13.Returnundeined.

Thelengthpropertyofapromiseresolvefunctionis1.

25.4.1.4 FulillPromise(promise,value)

WhentheFulillPromiseabstractoperationiscalledwithargumentspromiseandvalue,thefollowingstepsaretaken:

1.Assert:thevalueofpromise's[[PromiseState]]internalslotis"pending".
2.Letreactionsbethevalueofpromise's[[PromiseFulillReactions]]internalslot.
3.Setthevalueofpromise's[[PromiseResult]]internalslottovalue.
4.Setthevalueofpromise's[[PromiseFulillReactions]]internalslottoundeined.
5.Setthevalueofpromise's[[PromiseRejectReactions]]internalslottoundeined.
6.Setthevalueofpromise's[[PromiseState]]internalslotto"fulfilled".
7.ReturnTriggerPromiseReactions(reactions,value).

25.4.1.5 NewPromiseCapability(C)

TheabstractoperationNewPromiseCapabilitytakesaconstructorfunction,andattemptstousethatconstructorfunctionin
thefashionofthebuiltinPromiseconstructortocreateaPromiseobjectandextractitsresolveandrejectfunctions.The
promiseplustheresolveandrejectfunctionsareusedtoinitializeanewPromiseCapabilityrecordwhichisreturnedasthe
valueofthisabstractoperation.

1.IfIsConstructor(C)isfalse,throwaTypeErrorexception.
2.NOTECisassumedtobeaconstructorfunctionthatsupportstheparameterconventionsofthePromiseconstructor
(see25.4.3.1).
3.LetpromiseCapabilitybeanewPromiseCapability{[[Promise]]:undeined,[[Resolve]]:undeined,[[Reject]]:
undeined}.
4.LetexecutorbeanewbuiltinfunctionobjectasdeinedinGetCapabilitiesExecutorFunctions(25.4.1.5.1).
5.Setthe[[Capability]]internalslotofexecutortopromiseCapability.
6.Letpromisebe?Construct(C,executor).
7.IfIsCallable(promiseCapability.[[Resolve]])isfalse,throwaTypeErrorexception.
8.IfIsCallable(promiseCapability.[[Reject]])isfalse,throwaTypeErrorexception.
9.SetpromiseCapability.[[Promise]]topromise.
10.ReturnpromiseCapability.

NOTE ThisabstractoperationsupportsPromisesubclassing,asitisgenericonanyconstructorthatcallsapassed
executorfunctionargumentinthesamewayasthePromiseconstructor.Itisusedtogeneralizestaticmethods
ofthePromiseconstructortoanysubclass.

25.4.1.5.1 GetCapabilitiesExecutorFunctions

AGetCapabilitiesExecutorfunctionisananonymousbuiltinfunctionthathasa[[Capability]]internalslot.

WhenaGetCapabilitiesExecutorfunctionFiscalledwithargumentsresolveandreject,thefollowingstepsaretaken:

1.Assert:Fhasa[[Capability]]internalslotwhosevalueisaPromiseCapabilityRecord.
2.LetpromiseCapabilitybethevalueofF's[[Capability]]internalslot.
3.IfpromiseCapability.[[Resolve]]isnotundeined,throwaTypeErrorexception.
4.IfpromiseCapability.[[Reject]]isnotundeined,throwaTypeErrorexception.
5.SetpromiseCapability.[[Resolve]]toresolve.
6.SetpromiseCapability.[[Reject]]toreject.
7.Returnundeined.

ThelengthpropertyofaGetCapabilitiesExecutorfunctionis2.

25.4.1.6 IsPromise(x)

TheabstractoperationIsPromisechecksforthepromisebrandonanobject.

1.IfType(x)isnotObject,returnfalse.
2.Ifxdoesnothavea[[PromiseState]]internalslot,returnfalse.
3.Returntrue.

25.4.1.7 RejectPromise(promise,reason)

WhentheRejectPromiseabstractoperationiscalledwithargumentspromiseandreason,thefollowingstepsaretaken:

1.Assert:thevalueofpromise's[[PromiseState]]internalslotis"pending".
2.Letreactionsbethevalueofpromise's[[PromiseRejectReactions]]internalslot.
3.Setthevalueofpromise's[[PromiseResult]]internalslottoreason.
4.Setthevalueofpromise's[[PromiseFulillReactions]]internalslottoundeined.
5.Setthevalueofpromise's[[PromiseRejectReactions]]internalslottoundeined.
6.Setthevalueofpromise's[[PromiseState]]internalslotto"rejected".
7.Ifthevalueofpromise's[[PromiseIsHandled]]internalslotisfalse,performHostPromiseRejectionTracker(promise,
"reject").
8.ReturnTriggerPromiseReactions(reactions,reason).
25.4.1.8 TriggerPromiseReactions(reactions,argument)

TheabstractoperationTriggerPromiseReactionstakesacollectionofPromiseReactionRecordsandenqueuesanewJobfor
eachrecord.EachsuchJobprocessesthe[[Handler]]ofthePromiseReactionRecord,andifthe[[Handler]]isafunctioncalls
itpassingthegivenargument.

1.Repeatforeachreactioninreactions,inoriginalinsertionorder
a.PerformEnqueueJob("PromiseJobs",PromiseReactionJob,reaction,argument).
2.Returnundeined.

25.4.1.9 HostPromiseRejectionTracker(promise,operation)

HostPromiseRejectionTrackerisanimplementationdeinedabstractoperationthatallowshostenvironmentstotrack
promiserejections.

AnimplementationofHostPromiseRejectionTrackermustcompletenormallyinallcases.Thedefaultimplementationof
HostPromiseRejectionTrackeristodonothing.

NOTE1 HostPromiseRejectionTrackeriscalledintwoscenarios:

Whenapromiseisrejectedwithoutanyhandlers,itiscalledwithitsoperationargumentsetto
"reject".
Whenahandlerisaddedtoarejectedpromisefortheirsttime,itiscalledwithitsoperationargument
setto"handle".

AtypicalimplementationofHostPromiseRejectionTrackermighttrytonotifydevelopersofunhandled
rejections,whilealsobeingcarefultonotifythemifsuchpreviousnotiicationsarelaterinvalidatedbynew
handlersbeingattached.

NOTE2 Ifoperationis"handle",animplementationshouldnotholdareferencetopromiseinawaythatwould
interferewithgarbagecollection.Animplementationmayholdareferencetopromiseifoperationis
"reject",sinceitisexpectedthatrejectionswillberareandnotonhotcodepaths.

25.4.2 PromiseJobs

25.4.2.1 PromiseReactionJob(reaction,argument)

ThejobPromiseReactionJobwithparametersreactionandargumentappliestheappropriatehandlertotheincomingvalue,
andusesthehandler'sreturnvaluetoresolveorrejectthederivedpromiseassociatedwiththathandler.

1.Assert:reactionisaPromiseReactionRecord.
2.LetpromiseCapabilitybereaction.[[Capabilities]].
3.Lethandlerbereaction.[[Handler]].
4.Ifhandleris"Identity",lethandlerResultbeNormalCompletion(argument).
5.Elseifhandleris"Thrower",lethandlerResultbeCompletion{[[Type]]:throw,[[Value]]:argument,[[Target]]:empty}.
6.Else,lethandlerResultbeCall(handler,undeined,argument).
7.IfhandlerResultisanabruptcompletion,then
a.LetstatusbeCall(promiseCapability.[[Reject]],undeined,handlerResult.[[Value]]).
b.NextJobCompletion(status).
8.LetstatusbeCall(promiseCapability.[[Resolve]],undeined,handlerResult.[[Value]]).
9.NextJobCompletion(status).

25.4.2.2 PromiseResolveThenableJob(promiseToResolve,thenable,then)

ThejobPromiseResolveThenableJobwithparameterspromiseToResolve,thenable,andthenperformsthefollowingsteps:

1.LetresolvingFunctionsbeCreateResolvingFunctions(promiseToResolve).
2.LetthenCallResultbeCall(then,thenable,resolvingFunctions.[[Resolve]],resolvingFunctions.[[Reject]]).
3.IfthenCallResultisanabruptcompletion,then
a.LetstatusbeCall(resolvingFunctions.[[Reject]],undeined,thenCallResult.[[Value]]).
b.NextJobCompletion(status).
4.NextJobCompletion(thenCallResult).

NOTE ThisJobusesthesuppliedthenableanditsthenmethodtoresolvethegivenpromise.Thisprocessmusttake
placeasaJobtoensurethattheevaluationofthethenmethodoccursafterevaluationofanysurrounding
codehascompleted.

25.4.3 ThePromiseConstructor

ThePromiseconstructoristhe%Promise%intrinsicobjectandtheinitialvalueofthePromisepropertyoftheglobalobject.
WhencalledasaconstructoritcreatesandinitializesanewPromiseobject.Promiseisnotintendedtobecalledasa
functionandwillthrowanexceptionwhencalledinthatmanner.

ThePromiseconstructorisdesignedtobesubclassable.Itmaybeusedasthevalueinanextendsclauseofaclass
deinition.SubclassconstructorsthatintendtoinheritthespeciiedPromisebehaviourmustincludeasupercalltothe
PromiseconstructortocreateandinitializethesubclassinstancewiththeinternalstatenecessarytosupportthePromise
andPromise.prototypebuiltinmethods.

25.4.3.1 Promise(executor)

WhenthePromisefunctioniscalledwithargumentexecutor,thefollowingstepsaretaken:

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.IfIsCallable(executor)isfalse,throwaTypeErrorexception.
3.Letpromisebe?OrdinaryCreateFromConstructor(NewTarget,"%PromisePrototype%",[[PromiseState]],
[[PromiseResult]],[[PromiseFulillReactions]],[[PromiseRejectReactions]],[[PromiseIsHandled]]).
4.Setpromise's[[PromiseState]]internalslotto"pending".
5.Setpromise's[[PromiseFulillReactions]]internalslottoanewemptyList.
6.Setpromise's[[PromiseRejectReactions]]internalslottoanewemptyList.
7.Setpromise's[[PromiseIsHandled]]internalslottofalse.
8.LetresolvingFunctionsbeCreateResolvingFunctions(promise).
9.LetcompletionbeCall(executor,undeined,resolvingFunctions.[[Resolve]],resolvingFunctions.[[Reject]]).
10.Ifcompletionisanabruptcompletion,then
a.Perform?Call(resolvingFunctions.[[Reject]],undeined,completion.[[Value]]).
11.Returnpromise.

NOTE Theexecutorargumentmustbeafunctionobject.Itiscalledforinitiatingandreportingcompletionofthe
possiblydeferredactionrepresentedbythisPromiseobject.Theexecutoriscalledwithtwoarguments:resolve
andreject.Thesearefunctionsthatmaybeusedbytheexecutorfunctiontoreporteventualcompletionor
failureofthedeferredcomputation.Returningfromtheexecutorfunctiondoesnotmeanthatthedeferred
actionhasbeencompletedbutonlythattherequesttoeventuallyperformthedeferredactionhasbeen
accepted.

Theresolvefunctionthatispassedtoanexecutorfunctionacceptsasingleargument.Theexecutorcodemay
eventuallycalltheresolvefunctiontoindicatethatitwishestoresolvetheassociatedPromiseobject.The
argumentpassedtotheresolvefunctionrepresentstheeventualvalueofthedeferredactionandcanbeeither
theactualfulillmentvalueoranotherPromiseobjectwhichwillprovidethevalueifitisfulilled.

Therejectfunctionthatispassedtoanexecutorfunctionacceptsasingleargument.Theexecutorcodemay
eventuallycalltherejectfunctiontoindicatethattheassociatedPromiseisrejectedandwillneverbefulilled.
Theargumentpassedtotherejectfunctionisusedastherejectionvalueofthepromise.Typicallyitwillbean
Errorobject.

TheresolveandrejectfunctionspassedtoanexecutorfunctionbythePromiseconstructorhavethecapability
toactuallyresolveandrejecttheassociatedpromise.Subclassesmayhavedifferentconstructorbehaviourthat
passesincustomizedvaluesforresolveandreject.

25.4.4 PropertiesofthePromiseConstructor

Thevalueofthe[[Prototype]]internalslotofthePromiseconstructoristheintrinsicobject%FunctionPrototype%.

ThePromiseconstructorhasthefollowingproperties:

25.4.4.1 Promise.all(iterable)

Theallfunctionreturnsanewpromisewhichisfulilledwithanarrayoffulillmentvaluesforthepassedpromises,or
rejectswiththereasonoftheirstpassedpromisethatrejects.Itresolvesallelementsofthepassediterabletopromisesasit
runsthisalgorithm.

1.LetCbethethisvalue.
2.IfType(C)isnotObject,throwaTypeErrorexception.
3.LetpromiseCapabilitybe?NewPromiseCapability(C).
4.LetiteratorbeGetIterator(iterable).
5.IfAbruptRejectPromise(iterator,promiseCapability).
6.LetiteratorRecordbeRecord{[[Iterator]]:iterator,[[Done]]:false}.
7.LetresultbePerformPromiseAll(iteratorRecord,C,promiseCapability).
8.Ifresultisanabruptcompletion,then
a.IfiteratorRecord.[[Done]]isfalse,letresultbeIteratorClose(iterator,result).
b.IfAbruptRejectPromise(result,promiseCapability).
9.ReturnCompletion(result).

NOTE Theallfunctionrequiresitsthisvaluetobeaconstructorfunctionthatsupportstheparameterconventions
ofthePromiseconstructor.

25.4.4.1.1 RuntimeSemantics:PerformPromiseAll(iteratorRecord,constructor,resultCapability)

WhenthePerformPromiseAllabstractoperationiscalledwithargumentsiteratorRecord,constructor,andresultCapability,
thefollowingstepsaretaken:

1.Assert:constructorisaconstructorfunction.
2.Assert:resultCapabilityisaPromiseCapabilityrecord.
3.LetvaluesbeanewemptyList.
4.LetremainingElementsCountbeanewRecord{[[Value]]:1}.
5.Letindexbe0.
6.Repeat
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,then
i.SetiteratorRecord.[[Done]]totrue.
ii.SetremainingElementsCount.[[Value]]toremainingElementsCount.[[Value]]1.
iii.IfremainingElementsCount.[[Value]]is0,then
1.LetvaluesArraybeCreateArrayFromList(values).
2.Perform?Call(resultCapability.[[Resolve]],undeined,valuesArray).
iv.ReturnresultCapability.[[Promise]].
e.LetnextValuebeIteratorValue(next).
f.IfnextValueisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
g.ReturnIfAbrupt(nextValue).
h.Appendundeinedtovalues.
i.LetnextPromisebe?Invoke(constructor,"resolve",nextValue).
j.LetresolveElementbeanewbuiltinfunctionobjectasdeinedinPromise.allResolveElementFunctions.
k.Setthe[[AlreadyCalled]]internalslotofresolveElementtoanewRecord{[[Value]]:false}.
l.Setthe[[Index]]internalslotofresolveElementtoindex.
m.Setthe[[Values]]internalslotofresolveElementtovalues.
n.Setthe[[Capabilities]]internalslotofresolveElementtoresultCapability.
o.Setthe[[RemainingElements]]internalslotofresolveElementtoremainingElementsCount.
p.SetremainingElementsCount.[[Value]]toremainingElementsCount.[[Value]]+1.
q.Perform?Invoke(nextPromise,"then",resolveElement,resultCapability.[[Reject]]).
r.Setindextoindex+1.

25.4.4.1.2 Promise.allResolveElementFunctions

APromise.allresolveelementfunctionisananonymousbuiltinfunctionthatisusedtoresolveaspeciicPromise.all
element.EachPromise.allresolveelementfunctionhas[[Index]],[[Values]],[[Capabilities]],[[RemainingElements]],and
[[AlreadyCalled]]internalslots.

WhenaPromise.allresolveelementfunctionFiscalledwithargumentx,thefollowingstepsaretaken:

1.LetalreadyCalledbethevalueofF's[[AlreadyCalled]]internalslot.
2.IfalreadyCalled.[[Value]]istrue,returnundeined.
3.SetalreadyCalled.[[Value]]totrue.
4.LetindexbethevalueofF's[[Index]]internalslot.
5.LetvaluesbethevalueofF's[[Values]]internalslot.
6.LetpromiseCapabilitybethevalueofF's[[Capabilities]]internalslot.
7.LetremainingElementsCountbethevalueofF's[[RemainingElements]]internalslot.
8.Setvalues[index]tox.
9.SetremainingElementsCount.[[Value]]toremainingElementsCount.[[Value]]1.
10.IfremainingElementsCount.[[Value]]is0,then
a.LetvaluesArraybeCreateArrayFromList(values).
b.Return?Call(promiseCapability.[[Resolve]],undeined,valuesArray).
11.Returnundeined.

ThelengthpropertyofaPromise.allresolveelementfunctionis1.

25.4.4.2 Promise.prototype

TheinitialvalueofPromise.prototypeistheintrinsicobject%PromisePrototype%.

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:false}.

25.4.4.3 Promise.race(iterable)

Theracefunctionreturnsanewpromisewhichissettledinthesamewayastheirstpassedpromisetosettle.Itresolvesall
elementsofthepassediterabletopromisesasitrunsthisalgorithm.

1.LetCbethethisvalue.
2.IfType(C)isnotObject,throwaTypeErrorexception.
3.LetpromiseCapabilitybe?NewPromiseCapability(C).
4.LetiteratorbeGetIterator(iterable).
5.IfAbruptRejectPromise(iterator,promiseCapability).
6.LetiteratorRecordbeRecord{[[Iterator]]:iterator,[[Done]]:false}.
7.LetresultbePerformPromiseRace(iteratorRecord,promiseCapability,C).
8.Ifresultisanabruptcompletion,then
a.IfiteratorRecord.[[Done]]isfalse,letresultbeIteratorClose(iterator,result).
b.IfAbruptRejectPromise(result,promiseCapability).
9.ReturnCompletion(result).

NOTE1 Iftheiterableargumentisemptyorifnoneofthepromisesiniterableeversettlethenthependingpromise
returnedbythismethodwillneverbesettled.
NOTE2 Theracefunctionexpectsitsthisvaluetobeaconstructorfunctionthatsupportstheparameterconventions
ofthePromiseconstructor.Italsoexpectsthatitsthisvalueprovidesaresolvemethod.

25.4.4.3.1 RuntimeSemantics:PerformPromiseRace(iteratorRecord,promiseCapability,C)

WhenthePerformPromiseRaceabstractoperationiscalledwithargumentsiteratorRecord,promiseCapability,andC,the
followingstepsaretaken:

1.Repeat
a.LetnextbeIteratorStep(iteratorRecord.[[Iterator]]).
b.Ifnextisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
c.ReturnIfAbrupt(next).
d.Ifnextisfalse,then
i.SetiteratorRecord.[[Done]]totrue.
ii.ReturnpromiseCapability.[[Promise]].
e.LetnextValuebeIteratorValue(next).
f.IfnextValueisanabruptcompletion,setiteratorRecord.[[Done]]totrue.
g.ReturnIfAbrupt(nextValue).
h.LetnextPromisebe?Invoke(C,"resolve",nextValue).
i.Perform?Invoke(nextPromise,"then",promiseCapability.[[Resolve]],promiseCapability.[[Reject]]).

25.4.4.4 Promise.reject(r)

Therejectfunctionreturnsanewpromiserejectedwiththepassedargument.

1.LetCbethethisvalue.
2.IfType(C)isnotObject,throwaTypeErrorexception.
3.LetpromiseCapabilitybe?NewPromiseCapability(C).
4.Perform?Call(promiseCapability.[[Reject]],undeined,r).
5.ReturnpromiseCapability.[[Promise]].

NOTE Therejectfunctionexpectsitsthisvaluetobeaconstructorfunctionthatsupportstheparameter
conventionsofthePromiseconstructor.

25.4.4.5 Promise.resolve(x)

Theresolvefunctionreturnseitheranewpromiseresolvedwiththepassedargument,ortheargumentitselfifthe
argumentisapromiseproducedbythisconstructor.

1.LetCbethethisvalue.
2.IfType(C)isnotObject,throwaTypeErrorexception.
3.IfIsPromise(x)istrue,then
a.LetxConstructorbe?Get(x,"constructor").
b.IfSameValue(xConstructor,C)istrue,returnx.
4.LetpromiseCapabilitybe?NewPromiseCapability(C).
5.Perform?Call(promiseCapability.[[Resolve]],undeined,x).
6.ReturnpromiseCapability.[[Promise]].

NOTE Theresolvefunctionexpectsitsthisvaluetobeaconstructorfunctionthatsupportstheparameter
conventionsofthePromiseconstructor.

25.4.4.6 getPromise[@@species]

Promise[@@species]isanaccessorpropertywhosesetaccessorfunctionisundeined.Itsgetaccessorfunctionperforms
thefollowingsteps:

1.Returnthethisvalue.
Thevalueofthenamepropertyofthisfunctionis"get[Symbol.species]".

NOTE Promiseprototypemethodsnormallyusetheirthisobject'sconstructortocreateaderivedobject.However,a
subclassconstructormayoverridethatdefaultbehaviourbyredeiningits@@speciesproperty.

25.4.5 PropertiesofthePromisePrototypeObject

ThePromiseprototypeobjectistheintrinsicobject%PromisePrototype%.Thevalueofthe[[Prototype]]internalslotofthe
Promiseprototypeobjectistheintrinsicobject%ObjectPrototype%.ThePromiseprototypeobjectisanordinaryobject.It
doesnothavea[[PromiseState]]internalslotoranyoftheotherinternalslotsofPromiseinstances.

25.4.5.1 Promise.prototype.catch(onRejected)

WhenthecatchmethodiscalledwithargumentonRejected,thefollowingstepsaretaken:

1.Letpromisebethethisvalue.
2.Return?Invoke(promise,"then",undeined,onRejected).

25.4.5.2 Promise.prototype.constructor

TheinitialvalueofPromise.prototype.constructoristheintrinsicobject%Promise%.

25.4.5.3 Promise.prototype.then(onFulilled,onRejected)

WhenthethenmethodiscalledwithargumentsonFulilledandonRejected,thefollowingstepsaretaken:

1.Letpromisebethethisvalue.
2.IfIsPromise(promise)isfalse,throwaTypeErrorexception.
3.LetCbe?SpeciesConstructor(promise,%Promise%).
4.LetresultCapabilitybe?NewPromiseCapability(C).
5.ReturnPerformPromiseThen(promise,onFulilled,onRejected,resultCapability).

25.4.5.3.1 PerformPromiseThen(promise,onFulilled,onRejected,resultCapability)

TheabstractoperationPerformPromiseThenperformsthethenoperationonpromiseusingonFulilledandonRejectedas
itssettlementactions.TheresultisresultCapability'spromise.

1.Assert:IsPromise(promise)istrue.
2.Assert:resultCapabilityisaPromiseCapabilityrecord.
3.IfIsCallable(onFulilled)isfalse,then
a.LetonFulilledbe"Identity".
4.IfIsCallable(onRejected)isfalse,then
a.LetonRejectedbe"Thrower".
5.LetfulillReactionbethePromiseReaction{[[Capabilities]]:resultCapability,[[Handler]]:onFulilled}.
6.LetrejectReactionbethePromiseReaction{[[Capabilities]]:resultCapability,[[Handler]]:onRejected}.
7.Ifthevalueofpromise's[[PromiseState]]internalslotis"pending",then
a.AppendfulillReactionasthelastelementoftheListthatisthevalueofpromise's[[PromiseFulillReactions]]
internalslot.
b.AppendrejectReactionasthelastelementoftheListthatisthevalueofpromise's[[PromiseRejectReactions]]
internalslot.
8.Elseifthevalueofpromise's[[PromiseState]]internalslotis"fulfilled",then
a.Letvaluebethevalueofpromise's[[PromiseResult]]internalslot.
b.PerformEnqueueJob("PromiseJobs",PromiseReactionJob,fulillReaction,value).
9.Else,
a.Assert:Thevalueofpromise's[[PromiseState]]internalslotis"rejected".
b.Letreasonbethevalueofpromise's[[PromiseResult]]internalslot.
c.Ifthevalueofpromise's[[PromiseIsHandled]]internalslotisfalse,perform
HostPromiseRejectionTracker(promise,"handle").
d.PerformEnqueueJob("PromiseJobs",PromiseReactionJob,rejectReaction,reason).
10.Setpromise's[[PromiseIsHandled]]internalslottotrue.
11.ReturnresultCapability.[[Promise]].

25.4.5.4 Promise.prototype[@@toStringTag]

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"Promise".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

25.4.6 PropertiesofPromiseInstances

PromiseinstancesareordinaryobjectsthatinheritpropertiesfromthePromiseprototypeobject(theintrinsic,
%PromisePrototype%).PromiseinstancesareinitiallycreatedwiththeinternalslotsdescribedinTable60.

Table60:InternalSlotsofPromiseInstances
InternalSlot Description

[[PromiseState]] AStringvaluethatgovernshowapromisewillreacttoincomingcallstoitsthenmethod.
Thepossiblevaluesare:"pending","fulfilled",and"rejected".

[[PromiseResult]] Thevaluewithwhichthepromisehasbeenfulilledorrejected,ifany.Onlymeaningfulif
[[PromiseState]]isnot"pending".

[[PromiseFulillReactions]] AListofPromiseReactionrecordstobeprocessedwhen/ifthepromisetransitionsfromthe
"pending"statetothe"fulfilled"state.

[[PromiseRejectReactions]] AListofPromiseReactionrecordstobeprocessedwhen/ifthepromisetransitionsfromthe
"pending"statetothe"rejected"state.

[[PromiseIsHandled]] Abooleanindicatingwhetherthepromisehaseverhadafulillmentorrejectionhandler;
usedinunhandledrejectiontracking.

26 Relection
26.1 TheRelectObject
TheRelectobjectisthe%Relect%intrinsicobjectandtheinitialvalueoftheReflectpropertyoftheglobalobject.The
Relectobjectisanordinaryobject.

Thevalueofthe[[Prototype]]internalslotoftheRelectobjectistheintrinsicobject%ObjectPrototype%.

TheRelectobjectisnotafunctionobject.Itdoesnothavea[[Construct]]internalmethod;itisnotpossibletousethe
Relectobjectasaconstructorwiththenewoperator.TheRelectobjectalsodoesnothavea[[Call]]internalmethod;itisnot
possibletoinvoketheRelectobjectasafunction.

26.1.1 Relect.apply(target,thisArgument,argumentsList)

Whentheapplyfunctioniscalledwithargumentstarget,thisArgument,andargumentsList,thefollowingstepsaretaken:

1.IfIsCallable(target)isfalse,throwaTypeErrorexception.
2.Letargsbe?CreateListFromArrayLike(argumentsList).
3.PerformPrepareForTailCall().
4.Return?Call(target,thisArgument,args).

26.1.2 Relect.construct(target,argumentsList[,newTarget])
Whentheconstructfunctioniscalledwithargumentstarget,argumentsList,andnewTarget,thefollowingstepsaretaken:

1.IfIsConstructor(target)isfalse,throwaTypeErrorexception.
2.IfnewTargetisnotpresent,letnewTargetbetarget.
3.Else,ifIsConstructor(newTarget)isfalse,throwaTypeErrorexception.
4.Letargsbe?CreateListFromArrayLike(argumentsList).
5.Return?Construct(target,args,newTarget).

26.1.3 Relect.deineProperty(target,propertyKey,attributes)

WhenthedefinePropertyfunctioniscalledwithargumentstarget,propertyKey,andattributes,thefollowingstepsare
taken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Letkeybe?ToPropertyKey(propertyKey).
3.Letdescbe?ToPropertyDescriptor(attributes).
4.Return?target.[[DeineOwnProperty]](key,desc).

26.1.4 Relect.deleteProperty(target,propertyKey)

WhenthedeletePropertyfunctioniscalledwithargumentstargetandpropertyKey,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Letkeybe?ToPropertyKey(propertyKey).
3.Return?target.[[Delete]](key).

26.1.5 Relect.get(target,propertyKey[,receiver])

Whenthegetfunctioniscalledwithargumentstarget,propertyKey,andreceiver,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Letkeybe?ToPropertyKey(propertyKey).
3.Ifreceiverisnotpresent,then
a.Letreceiverbetarget.
4.Return?target.[[Get]](key,receiver).

26.1.6 Relect.getOwnPropertyDescriptor(target,propertyKey)

WhenthegetOwnPropertyDescriptorfunctioniscalledwithargumentstargetandpropertyKey,thefollowingstepsare
taken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Letkeybe?ToPropertyKey(propertyKey).
3.Letdescbe?target.[[GetOwnProperty]](key).
4.ReturnFromPropertyDescriptor(desc).

26.1.7 Relect.getPrototypeOf(target)

WhenthegetPrototypeOffunctioniscalledwithargumenttarget,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Return?target.[[GetPrototypeOf]]().

26.1.8 Relect.has(target,propertyKey)

WhenthehasfunctioniscalledwithargumentstargetandpropertyKey,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Letkeybe?ToPropertyKey(propertyKey).
3.Return?target.[[HasProperty]](key).

26.1.9 Relect.isExtensible(target)

WhentheisExtensiblefunctioniscalledwithargumenttarget,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Return?target.[[IsExtensible]]().

26.1.10 Relect.ownKeys(target)

WhentheownKeysfunctioniscalledwithargumenttarget,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Letkeysbe?target.[[OwnPropertyKeys]]().
3.ReturnCreateArrayFromList(keys).

26.1.11 Relect.preventExtensions(target)

WhenthepreventExtensionsfunctioniscalledwithargumenttarget,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Return?target.[[PreventExtensions]]().

26.1.12 Relect.set(target,propertyKey,V[,receiver])

Whenthesetfunctioniscalledwithargumentstarget,V,propertyKey,andreceiver,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.Letkeybe?ToPropertyKey(propertyKey).
3.Ifreceiverisnotpresent,then
a.Letreceiverbetarget.
4.Return?target.[[Set]](key,V,receiver).

26.1.13 Relect.setPrototypeOf(target,proto)

WhenthesetPrototypeOffunctioniscalledwithargumentstargetandproto,thefollowingstepsaretaken:

1.IfType(target)isnotObject,throwaTypeErrorexception.
2.IfType(proto)isnotObjectandprotoisnotnull,throwaTypeErrorexception.
3.Return?target.[[SetPrototypeOf]](proto).

26.2 ProxyObjects
26.2.1 TheProxyConstructor

TheProxyconstructoristhe%Proxy%intrinsicobjectandtheinitialvalueoftheProxypropertyoftheglobalobject.When
calledasaconstructoritcreatesandinitializesanewproxyexoticobject.Proxyisnotintendedtobecalledasafunctionand
willthrowanexceptionwhencalledinthatmanner.

26.2.1.1 Proxy(target,handler)

WhenProxyiscalledwithargumentstargetandhandlerperformsthefollowingsteps:

1.IfNewTargetisundeined,throwaTypeErrorexception.
2.Return?ProxyCreate(target,handler).

26.2.2 PropertiesoftheProxyConstructor
Thevalueofthe[[Prototype]]internalslotoftheProxyconstructoristheintrinsicobject%FunctionPrototype%.

TheProxyconstructordoesnothaveaprototypepropertybecauseproxyexoticobjectsdonothavea[[Prototype]]
internalslotthatrequiresinitialization.

TheProxyconstructorhasthefollowingproperties:

26.2.2.1 Proxy.revocable(target,handler)

TheProxy.revocablefunctionisusedtocreatearevocableProxyobject.WhenProxy.revocableiscalledwith
argumentstargetandhandler,thefollowingstepsaretaken:

1.Letpbe?ProxyCreate(target,handler).
2.Letrevokerbeanewbuiltinfunctionobjectasdeinedin26.2.2.1.1.
3.Setthe[[RevocableProxy]]internalslotofrevokertop.
4.LetresultbeObjectCreate(%ObjectPrototype%).
5.PerformCreateDataProperty(result,"proxy",p).
6.PerformCreateDataProperty(result,"revoke",revoker).
7.Returnresult.

26.2.2.1.1 ProxyRevocationFunctions

AProxyrevocationfunctionisananonymousfunctionthathastheabilitytoinvalidateaspeciicProxyobject.

EachProxyrevocationfunctionhasa[[RevocableProxy]]internalslot.

WhenaProxyrevocationfunction,F,iscalled,thefollowingstepsaretaken:

1.LetpbethevalueofF's[[RevocableProxy]]internalslot.
2.Ifpisnull,returnundeined.
3.SetthevalueofF's[[RevocableProxy]]internalslottonull.
4.Assert:pisaProxyobject.
5.Setthe[[ProxyTarget]]internalslotofptonull.
6.Setthe[[ProxyHandler]]internalslotofptonull.
7.Returnundeined.

ThelengthpropertyofaProxyrevocationfunctionis0.

26.3 ModuleNamespaceObjects
AModuleNamespaceObjectisamodulenamespaceexoticobjectthatprovidesruntimepropertybasedaccesstoamodule's
exportedbindings.ThereisnoconstructorfunctionforModuleNamespaceObjects.Instead,suchanobjectiscreatedfor
eachmodulethatisimportedbyanImportDeclarationthatincludesaNameSpaceImport.

Inadditiontothepropertiesspeciiedin9.4.6eachModuleNamespaceObjecthasthefollowingownproperties:

26.3.1 @@toStringTag

Theinitialvalueofthe@@toStringTagpropertyistheStringvalue"Module".

Thispropertyhastheattributes{[[Writable]]:false,[[Enumerable]]:false,[[Conigurable]]:true}.

26.3.2 [@@iterator]()

Whenthe@@iteratormethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetNbethethisvalue.
2.IfNisnotamodulenamespaceexoticobject,throwaTypeErrorexception.
3.LetexportsbethevalueofN's[[Exports]]internalslot.
4.Return!CreateListIterator(exports).

Thevalueofthenamepropertyofthisfunctionis"[Symbol.iterator]".
AnnexA
GrammarSummary
(informative)
A.1 LexicalGrammar
SourceCharacter ::
anyUnicodecodepoint

InputElementDiv ::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
RightBracePunctuator

InputElementRegExp ::
WhiteSpace
LineTerminator
Comment
CommonToken
RightBracePunctuator
RegularExpressionLiteral

InputElementRegExpOrTemplateTail ::
WhiteSpace
LineTerminator
Comment
CommonToken
RegularExpressionLiteral
TemplateSubstitutionTail

InputElementTemplateTail ::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
TemplateSubstitutionTail

WhiteSpace ::
<TAB>
<VT>
<FF>
<SP>
<NBSP>
<ZWNBSP>
<USP>

LineTerminator ::
<LF>
<CR>
<LS>
<PS>

LineTerminatorSequence ::
<LF>
<CR>[lookahead<LF>]
<LS>
<PS>
<CR><LF>

Comment ::
MultiLineComment
SingleLineComment

MultiLineComment ::
/* MultiLineCommentCharsopt */

MultiLineCommentChars ::
MultiLineNotAsteriskChar MultiLineCommentCharsopt
* PostAsteriskCommentCharsopt

PostAsteriskCommentChars ::
MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt
* PostAsteriskCommentCharsopt

MultiLineNotAsteriskChar ::
SourceCharacter butnot*

MultiLineNotForwardSlashOrAsteriskChar ::
SourceCharacter butnotoneof/ or*

SingleLineComment ::
// SingleLineCommentCharsopt

SingleLineCommentChars ::
SingleLineCommentChar SingleLineCommentCharsopt

SingleLineCommentChar ::
SourceCharacter butnotLineTerminator

CommonToken ::
IdentiierName
Punctuator
NumericLiteral
StringLiteral
Template

IdentiierName ::
IdentiierStart
IdentiierName IdentiierPart

IdentiierStart ::
UnicodeIDStart
$
_
\ UnicodeEscapeSequence
IdentiierPart ::
UnicodeIDContinue
$
_
\ UnicodeEscapeSequence
<ZWNJ>
<ZWJ>

UnicodeIDStart ::
anyUnicodecodepointwiththeUnicodepropertyID_Start

UnicodeIDContinue ::
anyUnicodecodepointwiththeUnicodepropertyID_Continue

ReservedWord ::
Keyword
FutureReservedWord
NullLiteral
BooleanLiteral

Keyword :: oneof
break do in typeof case else instanceof var catch export new void class extends return while
const finally super with continue for switch yield debugger function this default if
throw delete import try

FutureReservedWord ::
enum
await

awaitisonlytreatedasaFutureReservedWordwhenModuleisthegoalsymbolofthesyntacticgrammar.

ThefollowingtokensarealsoconsideredtobeFutureReservedWordswhenparsingstrictmodecode:

implementspackageprotected
interfaceprivatepublic

Punctuator :: oneof
{ ( ) [ ] . ... ; , < > <= >= == != === !== + * % ++ << >> >>> & | ^ ! ~ && || ? : = +=
= *= %= <<= >>= >>>= &= |= ^= => ** **=

DivPunctuator ::
/
/=

RightBracePunctuator ::
}

NullLiteral ::
null

BooleanLiteral ::
true
false

NumericLiteral ::
DecimalLiteral
BinaryIntegerLiteral
OctalIntegerLiteral
HexIntegerLiteral

DecimalLiteral ::
DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt
. DecimalDigits ExponentPartopt
DecimalIntegerLiteral ExponentPartopt

DecimalIntegerLiteral ::
0
NonZeroDigit DecimalDigitsopt

DecimalDigits ::
DecimalDigit
DecimalDigits DecimalDigit

DecimalDigit :: oneof
0 1 2 3 4 5 6 7 8 9

NonZeroDigit :: oneof
1 2 3 4 5 6 7 8 9

ExponentPart ::
ExponentIndicator SignedInteger

ExponentIndicator :: oneof
e E

SignedInteger ::
DecimalDigits
+ DecimalDigits
DecimalDigits

BinaryIntegerLiteral ::
0b BinaryDigits
0B BinaryDigits

BinaryDigits ::
BinaryDigit
BinaryDigits BinaryDigit

BinaryDigit :: oneof
0 1

OctalIntegerLiteral ::
0o OctalDigits
0O OctalDigits

OctalDigits ::
OctalDigit
OctalDigits OctalDigit

OctalDigit :: oneof
0 1 2 3 4 5 6 7

HexIntegerLiteral ::
0x HexDigits
0X HexDigits

HexDigits ::
HexDigit
HexDigits HexDigit

HexDigit :: oneof
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

StringLiteral ::
" DoubleStringCharactersopt "
' SingleStringCharactersopt '

DoubleStringCharacters ::
DoubleStringCharacter DoubleStringCharactersopt

SingleStringCharacters ::
SingleStringCharacter SingleStringCharactersopt

DoubleStringCharacter ::
SourceCharacter butnotoneof" or\ orLineTerminator
\ EscapeSequence
LineContinuation

SingleStringCharacter ::
SourceCharacter butnotoneof' or\ orLineTerminator
\ EscapeSequence
LineContinuation

LineContinuation ::
\ LineTerminatorSequence

EscapeSequence ::
CharacterEscapeSequence
0 [lookaheadDecimalDigit]
HexEscapeSequence
UnicodeEscapeSequence

CharacterEscapeSequence ::
SingleEscapeCharacter
NonEscapeCharacter

SingleEscapeCharacter :: oneof
' " \ b f n r t v

NonEscapeCharacter ::
SourceCharacter butnotoneofEscapeCharacter orLineTerminator

EscapeCharacter ::
SingleEscapeCharacter
DecimalDigit
x
u

HexEscapeSequence ::
x HexDigit HexDigit

UnicodeEscapeSequence ::
u Hex4Digits
u{ HexDigits }

Hex4Digits ::
HexDigit HexDigit HexDigit HexDigit

RegularExpressionLiteral ::
/ RegularExpressionBody / RegularExpressionFlags

RegularExpressionBody ::
RegularExpressionFirstChar RegularExpressionChars

RegularExpressionChars ::
[empty]
RegularExpressionChars RegularExpressionChar

RegularExpressionFirstChar ::
RegularExpressionNonTerminator butnotoneof* or\ or/ or[
RegularExpressionBackslashSequence
RegularExpressionClass

RegularExpressionChar ::
RegularExpressionNonTerminator butnotoneof\ or/ or[
RegularExpressionBackslashSequence
RegularExpressionClass

RegularExpressionBackslashSequence ::
\ RegularExpressionNonTerminator

RegularExpressionNonTerminator ::
SourceCharacter butnotLineTerminator

RegularExpressionClass ::
[ RegularExpressionClassChars ]

RegularExpressionClassChars ::
[empty]
RegularExpressionClassChars RegularExpressionClassChar

RegularExpressionClassChar ::
RegularExpressionNonTerminator butnotoneof] or\
RegularExpressionBackslashSequence

RegularExpressionFlags ::
[empty]
RegularExpressionFlags IdentiierPart

Template ::
NoSubstitutionTemplate
TemplateHead

NoSubstitutionTemplate ::
` TemplateCharactersopt `

TemplateHead ::
` TemplateCharactersopt ${

TemplateSubstitutionTail ::
TemplateMiddle
TemplateTail

TemplateMiddle ::
} TemplateCharactersopt ${

TemplateTail ::
} TemplateCharactersopt `

TemplateCharacters ::
TemplateCharacter TemplateCharactersopt

TemplateCharacter ::
$ [lookahead{]
\ EscapeSequence
LineContinuation
LineTerminatorSequence
SourceCharacter butnotoneof` or\ or$ orLineTerminator

A.2 Expressions
IdentiierReference[Yield] :
Identiier
[~Yield] yield

BindingIdentiier[Yield] :
Identiier
[~Yield] yield

Identiier :
IdentiierName butnotReservedWord

LabelIdentiier[Yield] :
Identiier
[~Yield] yield

PrimaryExpression[Yield] :
this
IdentiierReference[?Yield]
Literal
ArrayLiteral[?Yield]
ObjectLiteral[?Yield]
FunctionExpression
ClassExpression[?Yield]
GeneratorExpression
RegularExpressionLiteral
TemplateLiteral[?Yield]
CoverParenthesizedExpressionAndArrowParameterList[?Yield]

CoverParenthesizedExpressionAndArrowParameterList[Yield] :
( Expression[In,?Yield] )
( )
( ... BindingIdentiier[?Yield] )
( ... BindingPattern[?Yield] )
( Expression[In,?Yield] , ... BindingIdentiier[?Yield] )
( Expression[In,?Yield] , ... BindingPattern[?Yield] )

WhenprocessingtheproductionPrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList the


interpretationofCoverParenthesizedExpressionAndArrowParameterListisreinedusingthefollowinggrammar:

ParenthesizedExpression[Yield] :
( Expression[In,?Yield] )

Literal :
NullLiteral
BooleanLiteral
NumericLiteral
StringLiteral

ArrayLiteral[Yield] :
[ Elisionopt ]
[ ElementList[?Yield] ]
[ ElementList[?Yield] , Elisionopt ]

ElementList[Yield] :
Elisionopt AssignmentExpression[In,?Yield]
Elisionopt SpreadElement[?Yield]
ElementList[?Yield] , Elisionopt AssignmentExpression[In,?Yield]
ElementList[?Yield] , Elisionopt SpreadElement[?Yield]

Elision :
,
Elision ,

SpreadElement[Yield] :
... AssignmentExpression[In,?Yield]

ObjectLiteral[Yield] :
{ }
{ PropertyDeinitionList[?Yield] }
{ PropertyDeinitionList[?Yield] , }

PropertyDeinitionList[Yield] :
PropertyDeinition[?Yield]
PropertyDeinitionList[?Yield] , PropertyDeinition[?Yield]

PropertyDeinition[Yield] :
IdentiierReference[?Yield]
CoverInitializedName[?Yield]
PropertyName[?Yield] : AssignmentExpression[In,?Yield]
MethodDeinition[?Yield]

PropertyName[Yield] :
LiteralPropertyName
ComputedPropertyName[?Yield]

LiteralPropertyName :
IdentiierName
StringLiteral
NumericLiteral

ComputedPropertyName[Yield] :
[ AssignmentExpression[In,?Yield] ]

CoverInitializedName[Yield] :
IdentiierReference[?Yield] Initializer[In,?Yield]

Initializer[In,Yield] :
= AssignmentExpression[?In,?Yield]

TemplateLiteral[Yield] :
NoSubstitutionTemplate
TemplateHead Expression[In,?Yield] TemplateSpans[?Yield]

TemplateSpans[Yield] :
TemplateTail
TemplateMiddleList[?Yield] TemplateTail

TemplateMiddleList[Yield] :
TemplateMiddle Expression[In,?Yield]
TemplateMiddleList[?Yield] TemplateMiddle Expression[In,?Yield]

MemberExpression[Yield] :
PrimaryExpression[?Yield]
MemberExpression[?Yield] [ Expression[In,?Yield] ]
MemberExpression[?Yield] . IdentiierName
MemberExpression[?Yield] TemplateLiteral[?Yield]
SuperProperty[?Yield]
MetaProperty
new MemberExpression[?Yield] Arguments[?Yield]

SuperProperty[Yield] :
super [ Expression[In,?Yield] ]
super . IdentiierName

MetaProperty :
NewTarget

NewTarget :
new . target

NewExpression[Yield] :
MemberExpression[?Yield]
new NewExpression[?Yield]

CallExpression[Yield] :
MemberExpression[?Yield] Arguments[?Yield]
SuperCall[?Yield]
CallExpression[?Yield] Arguments[?Yield]
CallExpression[?Yield] [ Expression[In,?Yield] ]
CallExpression[?Yield] . IdentiierName
CallExpression[?Yield] TemplateLiteral[?Yield]
SuperCall[Yield] :
super Arguments[?Yield]

Arguments[Yield] :
( )
( ArgumentList[?Yield] )

ArgumentList[Yield] :
AssignmentExpression[In,?Yield]
... AssignmentExpression[In,?Yield]
ArgumentList[?Yield] , AssignmentExpression[In,?Yield]
ArgumentList[?Yield] , ... AssignmentExpression[In,?Yield]

LeftHandSideExpression[Yield] :
NewExpression[?Yield]
CallExpression[?Yield]

UpdateExpression[Yield] :
LeftHandSideExpression[?Yield]
LeftHandSideExpression[?Yield] [noLineTerminatorhere] ++
LeftHandSideExpression[?Yield] [noLineTerminatorhere]
++ UnaryExpression[?Yield]
UnaryExpression[?Yield]

UnaryExpression[Yield] :
UpdateExpression[?Yield]
delete UnaryExpression[?Yield]
void UnaryExpression[?Yield]
typeof UnaryExpression[?Yield]
+ UnaryExpression[?Yield]
UnaryExpression[?Yield]
~ UnaryExpression[?Yield]
! UnaryExpression[?Yield]

ExponentiationExpression[Yield] :
UnaryExpression[?Yield]
UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]

MultiplicativeExpression[Yield] :
ExponentiationExpression[?Yield]
MultiplicativeExpression[?Yield] MultiplicativeOperator ExponentiationExpression[?Yield]

MultiplicativeOperator : oneof
* / %

AdditiveExpression[Yield] :
MultiplicativeExpression[?Yield]
AdditiveExpression[?Yield] + MultiplicativeExpression[?Yield]
AdditiveExpression[?Yield] MultiplicativeExpression[?Yield]

ShiftExpression[Yield] :
AdditiveExpression[?Yield]
ShiftExpression[?Yield] << AdditiveExpression[?Yield]
ShiftExpression[?Yield] >> AdditiveExpression[?Yield]
ShiftExpression[?Yield] >>> AdditiveExpression[?Yield]

RelationalExpression[In,Yield] :
ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] < ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] > ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] <= ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] >= ShiftExpression[?Yield]
RelationalExpression[?In,?Yield] instanceof ShiftExpression[?Yield]
[+In] RelationalExpression[In,?Yield] in ShiftExpression[?Yield]

EqualityExpression[In,Yield] :
RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] == RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] != RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] === RelationalExpression[?In,?Yield]
EqualityExpression[?In,?Yield] !== RelationalExpression[?In,?Yield]

BitwiseANDExpression[In,Yield] :
EqualityExpression[?In,?Yield]
BitwiseANDExpression[?In,?Yield] & EqualityExpression[?In,?Yield]

BitwiseXORExpression[In,Yield] :
BitwiseANDExpression[?In,?Yield]
BitwiseXORExpression[?In,?Yield] ^ BitwiseANDExpression[?In,?Yield]

BitwiseORExpression[In,Yield] :
BitwiseXORExpression[?In,?Yield]
BitwiseORExpression[?In,?Yield] | BitwiseXORExpression[?In,?Yield]

LogicalANDExpression[In,Yield] :
BitwiseORExpression[?In,?Yield]
LogicalANDExpression[?In,?Yield] && BitwiseORExpression[?In,?Yield]

LogicalORExpression[In,Yield] :
LogicalANDExpression[?In,?Yield]
LogicalORExpression[?In,?Yield] || LogicalANDExpression[?In,?Yield]

ConditionalExpression[In,Yield] :
LogicalORExpression[?In,?Yield]
LogicalORExpression[?In,?Yield] ? AssignmentExpression[In,?Yield] : AssignmentExpression[?In,?Yield]

AssignmentExpression[In,Yield] :
ConditionalExpression[?In,?Yield]
[+Yield] YieldExpression[?In]
ArrowFunction[?In,?Yield]
LeftHandSideExpression[?Yield] = AssignmentExpression[?In,?Yield]
LeftHandSideExpression[?Yield] AssignmentOperator AssignmentExpression[?In,?Yield]

IncertaincircumstanceswhenprocessingtheproductionAssignmentExpression : LeftHandSideExpression =
AssignmentExpression thefollowinggrammarisusedtoreinetheinterpretationofLeftHandSideExpression:
AssignmentPattern[Yield] :
ObjectAssignmentPattern[?Yield]
ArrayAssignmentPattern[?Yield]

ObjectAssignmentPattern[Yield] :
{ }
{ AssignmentPropertyList[?Yield] }
{ AssignmentPropertyList[?Yield] , }

ArrayAssignmentPattern[Yield] :
[ Elisionopt AssignmentRestElement[?Yield] opt ]
[ AssignmentElementList[?Yield] ]
[ AssignmentElementList[?Yield] , Elisionopt AssignmentRestElement[?Yield] opt ]

AssignmentPropertyList[Yield] :
AssignmentProperty[?Yield]
AssignmentPropertyList[?Yield] , AssignmentProperty[?Yield]

AssignmentElementList[Yield] :
AssignmentElisionElement[?Yield]
AssignmentElementList[?Yield] , AssignmentElisionElement[?Yield]

AssignmentElisionElement[Yield] :
Elisionopt AssignmentElement[?Yield]

AssignmentProperty[Yield] :
IdentiierReference[?Yield] Initializer[In,?Yield] opt
PropertyName[?Yield] : AssignmentElement[?Yield]

AssignmentElement[Yield] :
DestructuringAssignmentTarget[?Yield] Initializer[In,?Yield] opt

AssignmentRestElement[Yield] :
... DestructuringAssignmentTarget[?Yield]

DestructuringAssignmentTarget[Yield] :
LeftHandSideExpression[?Yield]

AssignmentOperator : oneof
*= /= %= += = <<= >>= >>>= &= ^= |= **=

Expression[In,Yield] :
AssignmentExpression[?In,?Yield]
Expression[?In,?Yield] , AssignmentExpression[?In,?Yield]

A.3 Statements
Statement[Yield,Return] :
BlockStatement[?Yield,?Return]
VariableStatement[?Yield]
EmptyStatement
ExpressionStatement[?Yield]
IfStatement[?Yield,?Return]
BreakableStatement[?Yield,?Return]
ContinueStatement[?Yield]
BreakStatement[?Yield]
[+Return] ReturnStatement[?Yield]
WithStatement[?Yield,?Return]
LabelledStatement[?Yield,?Return]
ThrowStatement[?Yield]
TryStatement[?Yield,?Return]
DebuggerStatement

Declaration[Yield] :
HoistableDeclaration[?Yield]
ClassDeclaration[?Yield]
LexicalDeclaration[In,?Yield]

HoistableDeclaration[Yield,Default] :
FunctionDeclaration[?Yield,?Default]
GeneratorDeclaration[?Yield,?Default]

BreakableStatement[Yield,Return] :
IterationStatement[?Yield,?Return]
SwitchStatement[?Yield,?Return]

BlockStatement[Yield,Return] :
Block[?Yield,?Return]

Block :
{ StatementList }

StatementList[Yield,Return] :
StatementListItem[?Yield,?Return]
StatementList[?Yield,?Return] StatementListItem[?Yield,?Return]

StatementListItem[Yield,Return] :
Statement[?Yield,?Return]
Declaration[?Yield]

LexicalDeclaration[In,Yield] :
LetOrConst BindingList[?In,?Yield] ;

LetOrConst :
let
const

BindingList[In,Yield] :
LexicalBinding[?In,?Yield]
BindingList[?In,?Yield] , LexicalBinding[?In,?Yield]

LexicalBinding[In,Yield] :
BindingIdentiier[?Yield] Initializer[?In,?Yield] opt
BindingPattern[?Yield] Initializer[?In,?Yield]

VariableStatement[Yield] :
var VariableDeclarationList[In,?Yield] ;

VariableDeclarationList[In,Yield] :
VariableDeclaration[?In,?Yield]
VariableDeclarationList[?In,?Yield] , VariableDeclaration[?In,?Yield]

VariableDeclaration[In,Yield] :
BindingIdentiier[?Yield] Initializer[?In,?Yield] opt
BindingPattern[?Yield] Initializer[?In,?Yield]

BindingPattern[Yield] :
ObjectBindingPattern[?Yield]
ArrayBindingPattern[?Yield]

ObjectBindingPattern[Yield] :
{ }
{ BindingPropertyList[?Yield] }
{ BindingPropertyList[?Yield] , }

ArrayBindingPattern[Yield] :
[ Elisionopt BindingRestElement[?Yield] opt ]
[ BindingElementList[?Yield] ]
[ BindingElementList[?Yield] , Elisionopt BindingRestElement[?Yield] opt ]

BindingPropertyList[Yield] :
BindingProperty[?Yield]
BindingPropertyList[?Yield] , BindingProperty[?Yield]

BindingElementList[Yield] :
BindingElisionElement[?Yield]
BindingElementList[?Yield] , BindingElisionElement[?Yield]

BindingElisionElement[Yield] :
Elisionopt BindingElement[?Yield]

BindingProperty[Yield] :
SingleNameBinding[?Yield]
PropertyName[?Yield] : BindingElement[?Yield]

BindingElement[Yield] :
SingleNameBinding[?Yield]
BindingPattern[?Yield] Initializer[In,?Yield] opt

SingleNameBinding[Yield] :
BindingIdentiier[?Yield] Initializer[In,?Yield] opt

BindingRestElement[Yield] :
... BindingIdentiier[?Yield]
... BindingPattern[?Yield]

EmptyStatement :
;

ExpressionStatement[Yield] :
[lookahead{{ ,function ,class ,let[}] Expression[In,?Yield] ;

IfStatement[Yield,Return] :
if ( Expression[In,?Yield] ) Statement[?Yield,?Return] else Statement[?Yield,?Return]
if ( Expression[In,?Yield] ) Statement[?Yield,?Return]

IterationStatement[Yield,Return] :
do Statement[?Yield,?Return] while ( Expression[In,?Yield] ) ;
while ( Expression[In,?Yield] ) Statement[?Yield,?Return]
for ( [lookahead{let[}] Expression[?Yield] opt ; Expression[In,?Yield] opt ;
Expression[In,?Yield] opt ) Statement[?Yield,?Return]
for ( var VariableDeclarationList[?Yield] ; Expression[In,?Yield] opt ; Expression[In,?Yield] opt )
Statement[?Yield,?Return]
for ( LexicalDeclaration[?Yield] Expression[In,?Yield] opt ; Expression[In,?Yield] opt )
Statement[?Yield,?Return]
for ( [lookahead{let[}] LeftHandSideExpression[?Yield] in Expression[In,?Yield] )
Statement[?Yield,?Return]
for ( var ForBinding[?Yield] in Expression[In,?Yield] ) Statement[?Yield,?Return]
for ( ForDeclaration[?Yield] in Expression[In,?Yield] ) Statement[?Yield,?Return]
for ( [lookaheadlet] LeftHandSideExpression[?Yield] of AssignmentExpression[In,?Yield] )
Statement[?Yield,?Return]
for ( var ForBinding[?Yield] of AssignmentExpression[In,?Yield] ) Statement[?Yield,?Return]
for ( ForDeclaration[?Yield] of AssignmentExpression[In,?Yield] ) Statement[?Yield,?Return]

ForDeclaration[Yield] :
LetOrConst ForBinding[?Yield]

ForBinding[Yield] :
BindingIdentiier[?Yield]
BindingPattern[?Yield]

ContinueStatement[Yield] :
continue ;
continue [noLineTerminatorhere] LabelIdentiier[?Yield] ;

BreakStatement[Yield] :
break ;
break [noLineTerminatorhere] LabelIdentiier[?Yield] ;

ReturnStatement[Yield] :
return ;
return [noLineTerminatorhere] Expression[In,?Yield] ;

WithStatement[Yield,Return] :
with ( Expression[In,?Yield] ) Statement[?Yield,?Return]

SwitchStatement[Yield,Return] :
switch ( Expression[In,?Yield] ) CaseBlock[?Yield,?Return]

CaseBlock[Yield,Return] :
{ CaseClauses[?Yield,?Return] opt }
{ CaseClauses[?Yield,?Return] opt DefaultClause[?Yield,?Return] CaseClauses[?Yield,?Return] opt }
CaseClauses[Yield,Return] :
CaseClause[?Yield,?Return]
CaseClauses[?Yield,?Return] CaseClause[?Yield,?Return]

CaseClause[Yield,Return] :
case Expression[In,?Yield] : StatementList[?Yield,?Return] opt

DefaultClause[Yield,Return] :
default : StatementList[?Yield,?Return] opt

LabelledStatement[Yield,Return] :
LabelIdentiier[?Yield] : LabelledItem[?Yield,?Return]

LabelledItem[Yield,Return] :
Statement[?Yield,?Return]
FunctionDeclaration[?Yield]

ThrowStatement[Yield] :
throw [noLineTerminatorhere] Expression[In,?Yield] ;

TryStatement[Yield,Return] :
try Block[?Yield,?Return] Catch[?Yield,?Return]
try Block[?Yield,?Return] Finally[?Yield,?Return]
try Block[?Yield,?Return] Catch[?Yield,?Return] Finally[?Yield,?Return]

Catch[Yield,Return] :
catch ( CatchParameter[?Yield] ) Block[?Yield,?Return]

Finally[Yield,Return] :
finally Block[?Yield,?Return]

CatchParameter[Yield] :
BindingIdentiier[?Yield]
BindingPattern[?Yield]

DebuggerStatement :
debugger ;

A.4 FunctionsandClasses
FunctionDeclaration[Yield,Default] :
function BindingIdentiier[?Yield] ( FormalParameters ) { FunctionBody }
[+Default] function ( FormalParameters ) { FunctionBody }

FunctionExpression :
function BindingIdentiieropt ( FormalParameters ) { FunctionBody }

StrictFormalParameters[Yield] :
FormalParameters[?Yield]

FormalParameters[Yield] :
[empty]
FormalParameterList[?Yield]

FormalParameterList[Yield] :
FunctionRestParameter[?Yield]
FormalsList[?Yield]
FormalsList[?Yield] , FunctionRestParameter[?Yield]

FormalsList[Yield] :
FormalParameter[?Yield]
FormalsList[?Yield] , FormalParameter[?Yield]

FunctionRestParameter[Yield] :
BindingRestElement[?Yield]

FormalParameter[Yield] :
BindingElement[?Yield]

FunctionBody[Yield] :
FunctionStatementList[?Yield]

FunctionStatementList[Yield] :
StatementList[?Yield,Return] opt

ArrowFunction[In,Yield] :
ArrowParameters[?Yield] [noLineTerminatorhere] => ConciseBody[?In]

ArrowParameters[Yield] :
BindingIdentiier[?Yield]
CoverParenthesizedExpressionAndArrowParameterList[?Yield]

ConciseBody[In] :
[lookahead{] AssignmentExpression[?In]
{ FunctionBody }

WhentheproductionArrowParameters : CoverParenthesizedExpressionAndArrowParameterList isrecognizedthefollowing


grammarisusedtoreinetheinterpretationofCoverParenthesizedExpressionAndArrowParameterList:

ArrowFormalParameters[Yield] :
( StrictFormalParameters[?Yield] )

MethodDeinition[Yield] :
PropertyName[?Yield] ( StrictFormalParameters ) { FunctionBody }
GeneratorMethod[?Yield]
get PropertyName[?Yield] ( ) { FunctionBody }
set PropertyName[?Yield] ( PropertySetParameterList ) { FunctionBody }

PropertySetParameterList :
FormalParameter

GeneratorMethod[Yield] :
* PropertyName[?Yield] ( StrictFormalParameters[Yield] ) { GeneratorBody }

GeneratorDeclaration[Yield,Default] :
function * BindingIdentiier[?Yield] ( FormalParameters[Yield] ) { GeneratorBody }
[+Default] function * ( FormalParameters[Yield] ) { GeneratorBody }
GeneratorExpression :
function * BindingIdentiier[Yield] opt ( FormalParameters[Yield] ) { GeneratorBody }

GeneratorBody :
FunctionBody[Yield]

YieldExpression[In] :
yield
yield [noLineTerminatorhere] AssignmentExpression[?In,Yield]
yield [noLineTerminatorhere] * AssignmentExpression[?In,Yield]

ClassDeclaration[Yield,Default] :
class BindingIdentiier[?Yield] ClassTail[?Yield]
[+Default] class ClassTail[?Yield]

ClassExpression[Yield] :
class BindingIdentiier[?Yield] opt ClassTail[?Yield]

ClassTail[Yield] :
ClassHeritage[?Yield] opt { ClassBody[?Yield] opt }

ClassHeritage[Yield] :
extends LeftHandSideExpression[?Yield]

ClassBody[Yield] :
ClassElementList[?Yield]

ClassElementList[Yield] :
ClassElement[?Yield]
ClassElementList[?Yield] ClassElement[?Yield]

ClassElement[Yield] :
MethodDeinition[?Yield]
static MethodDeinition[?Yield]
;

A.5 ScriptsandModules
Script :
ScriptBodyopt

ScriptBody :
StatementList

Module :
ModuleBodyopt

ModuleBody :
ModuleItemList

ModuleItemList :
ModuleItem
ModuleItemList ModuleItem

ModuleItem :
ImportDeclaration
ExportDeclaration
StatementListItem

ImportDeclaration :
import ImportClause FromClause ;
import ModuleSpeciier ;

ImportClause :
ImportedDefaultBinding
NameSpaceImport
NamedImports
ImportedDefaultBinding , NameSpaceImport
ImportedDefaultBinding , NamedImports

ImportedDefaultBinding :
ImportedBinding

NameSpaceImport :
* as ImportedBinding

NamedImports :
{ }
{ ImportsList }
{ ImportsList , }

FromClause :
from ModuleSpeciier

ImportsList :
ImportSpeciier
ImportsList , ImportSpeciier

ImportSpeciier :
ImportedBinding
IdentiierName as ImportedBinding

ModuleSpeciier :
StringLiteral

ImportedBinding :
BindingIdentiier

ExportDeclaration :
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;
export VariableStatement
export Declaration
export default HoistableDeclaration[Default]
export default ClassDeclaration[Default]
export default [lookahead{function ,class}] AssignmentExpression[In] ;

ExportClause :
{ }
{ ExportsList }
{ ExportsList , }
ExportsList :
ExportSpeciier
ExportsList , ExportSpeciier

ExportSpeciier :
IdentiierName
IdentiierName as IdentiierName

A.6 NumberConversions
StringNumericLiteral :::
StrWhiteSpaceopt
StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt

StrWhiteSpace :::
StrWhiteSpaceChar StrWhiteSpaceopt

StrWhiteSpaceChar :::
WhiteSpace
LineTerminator

StrNumericLiteral :::
StrDecimalLiteral
BinaryIntegerLiteral
OctalIntegerLiteral
HexIntegerLiteral

StrDecimalLiteral :::
StrUnsignedDecimalLiteral
+ StrUnsignedDecimalLiteral
StrUnsignedDecimalLiteral

StrUnsignedDecimalLiteral :::
Infinity
DecimalDigits . DecimalDigitsopt ExponentPartopt
. DecimalDigits ExponentPartopt
DecimalDigits ExponentPartopt

DecimalDigits ::
DecimalDigit
DecimalDigits DecimalDigit

DecimalDigit :: oneof
0 1 2 3 4 5 6 7 8 9

ExponentPart ::
ExponentIndicator SignedInteger

ExponentIndicator :: oneof
e E

SignedInteger ::
DecimalDigits
+ DecimalDigits
DecimalDigits

HexIntegerLiteral ::
0x HexDigits
0X HexDigits

HexDigit :: oneof
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

AllgrammarsymbolsnotexplicitlydeinedbytheStringNumericLiteralgrammarhavethedeinitionsusedintheLexical
Grammarfornumericliterals.

A.7 UniversalResourceIdentiierCharacterClasses
uri :::
uriCharactersopt

uriCharacters :::
uriCharacter uriCharactersopt

uriCharacter :::
uriReserved
uriUnescaped
uriEscaped

uriReserved ::: oneof


; / ? : @ & = + $ ,

uriUnescaped :::
uriAlpha
DecimalDigit
uriMark

uriEscaped :::
% HexDigit HexDigit

uriAlpha ::: oneof


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

uriMark ::: oneof


_ . ! ~ * ' ( )

A.8 RegularExpressions
Pattern[U] ::
Disjunction[?U]

Disjunction[U] ::
Alternative[?U]
Alternative[?U] | Disjunction[?U]

Alternative[U] ::
[empty]
Alternative[?U] Term[?U]

Term[U] ::
Assertion[?U]
Atom[?U]
Atom[?U] Quantiier

Assertion[U] ::
^
$
\ b
\ B
( ? = Disjunction[?U] )
( ? ! Disjunction[?U] )

Quantiier ::
QuantiierPreix
QuantiierPreix ?

QuantiierPreix ::
*
+
?
{ DecimalDigits }
{ DecimalDigits , }
{ DecimalDigits , DecimalDigits }

Atom[U] ::
PatternCharacter
.
\ AtomEscape[?U]
CharacterClass[?U]
( Disjunction[?U] )
( ? : Disjunction[?U] )

SyntaxCharacter :: oneof
^ $ \ . * + ? ( ) [ ] { } |

PatternCharacter ::
SourceCharacter butnotSyntaxCharacter

AtomEscape[U] ::
DecimalEscape
CharacterEscape[?U]
CharacterClassEscape

CharacterEscape[U] ::
ControlEscape
c ControlLetter
HexEscapeSequence
RegExpUnicodeEscapeSequence[?U]
IdentityEscape[?U]

ControlEscape :: oneof
f n r t v

ControlLetter :: oneof
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
RegExpUnicodeEscapeSequence[U] ::
[+U] u LeadSurrogate \u TrailSurrogate
[+U] u LeadSurrogate
[+U] u TrailSurrogate
[+U] u NonSurrogate
[~U] u Hex4Digits
[+U] u{ HexDigits }

Each\uTrailSurrogateforwhichthechoiceofassociateduLeadSurrogateisambiguousshallbeassociatedwiththenearest
possibleuLeadSurrogatethatwouldotherwisehavenocorresponding\uTrailSurrogate.

LeadSurrogate ::
Hex4Digits butonlyiftheSVofHex4Digits isintheinclusiverange0xD800to0xDBFF

TrailSurrogate ::
Hex4Digits butonlyiftheSVofHex4Digits isintheinclusiverange0xDC00to0xDFFF

NonSurrogate ::
Hex4Digits butonlyiftheSVofHex4Digits isnotintheinclusiverange0xD800to0xDFFF

IdentityEscape[U] ::
[+U] SyntaxCharacter
[+U] /
[~U] SourceCharacter butnotUnicodeIDContinue

DecimalEscape ::
DecimalIntegerLiteral [lookaheadDecimalDigit]

CharacterClassEscape :: oneof
d D s S w W

CharacterClass[U] ::
[ [lookahead{^}] ClassRanges[?U] ]
[ ^ ClassRanges[?U] ]

ClassRanges[U] ::
[empty]
NonemptyClassRanges[?U]

NonemptyClassRanges[U] ::
ClassAtom[?U]
ClassAtom[?U] NonemptyClassRangesNoDash[?U]
ClassAtom[?U] ClassAtom[?U] ClassRanges[?U]

NonemptyClassRangesNoDash[U] ::
ClassAtom[?U]
ClassAtomNoDash[?U] NonemptyClassRangesNoDash[?U]
ClassAtomNoDash[?U] ClassAtom[?U] ClassRanges[?U]

ClassAtom[U] ::

ClassAtomNoDash[?U]

ClassAtomNoDash[U] ::
SourceCharacter butnotoneof\ or] or
\ ClassEscape[?U]

ClassEscape[U] ::
DecimalEscape
b
[+U]
CharacterEscape[?U]
CharacterClassEscape
AnnexB
AdditionalECMAScriptFeaturesforWebBrowsers
(normative)
TheECMAScriptlanguagesyntaxandsemanticsdeinedinthisannexarerequiredwhentheECMAScripthostisaweb
browser.ThecontentofthisannexisnormativebutoptionaliftheECMAScripthostisnotawebbrowser.

NOTE ThisannexdescribesvariouslegacyfeaturesandothercharacteristicsofwebbrowserbasedECMAScript
implementations.Allofthelanguagefeaturesandbehavioursspeciiedinthisannexhaveoneormore
undesirablecharacteristicsandintheabsenceoflegacyusagewouldberemovedfromthisspeciication.
However,theusageofthesefeaturesbylargenumbersofexistingwebpagesmeansthatwebbrowsersmust
continuetosupportthem.Thespeciicationsinthisannexdeinetherequirementsforinteroperable
implementationsoftheselegacyfeatures.

ThesefeaturesarenotconsideredpartofthecoreECMAScriptlanguage.Programmersshouldnotuseor
assumetheexistenceofthesefeaturesandbehaviourswhenwritingnewECMAScriptcode.ECMAScript
implementationsarediscouragedfromimplementingthesefeaturesunlesstheimplementationispartofa
webbrowserorisrequiredtorunthesamelegacyECMAScriptcodethatwebbrowsersencounter.

B.1 AdditionalSyntax
B.1.1 NumericLiterals

Thesyntaxandsemanticsof11.8.3isextendedasfollowsexceptthatthisextensionisnotallowedforstrictmodecode:

Syntax

NumericLiteral ::
DecimalLiteral
BinaryIntegerLiteral
OctalIntegerLiteral
HexIntegerLiteral
LegacyOctalIntegerLiteral

LegacyOctalIntegerLiteral ::
0 OctalDigit
LegacyOctalIntegerLiteral OctalDigit

DecimalIntegerLiteral ::
0
NonZeroDigit DecimalDigitsopt
NonOctalDecimalIntegerLiteral

NonOctalDecimalIntegerLiteral ::
0 NonOctalDigit
LegacyOctalLikeDecimalIntegerLiteral NonOctalDigit
NonOctalDecimalIntegerLiteral DecimalDigit

LegacyOctalLikeDecimalIntegerLiteral ::
0 OctalDigit
LegacyOctalLikeDecimalIntegerLiteral OctalDigit

NonOctalDigit :: oneof
8 9

B.1.1.1 StaticSemantics

TheMVofLegacyOctalIntegerLiteral :: 0 OctalDigit istheMVofOctalDigit.


TheMVofLegacyOctalIntegerLiteral :: LegacyOctalIntegerLiteral OctalDigit is(theMVofLegacyOctalIntegerLiteral
times8)plustheMVofOctalDigit.
TheMVofDecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral istheMVofNonOctalDecimalIntegerLiteral.
TheMVofNonOctalDecimalIntegerLiteral :: 0 NonOctalDigit istheMVofNonOctalDigit.
TheMVofNonOctalDecimalIntegerLiteral :: LegacyOctalLikeDecimalIntegerLiteral NonOctalDigit is(theMVof
LegacyOctalLikeDecimalIntegerLiteraltimes10)plustheMVofNonOctalDigit.
TheMVofNonOctalDecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral DecimalDigit is(theMVof
NonOctalDecimalIntegerLiteraltimes10)plustheMVofDecimalDigit.
TheMVofLegacyOctalLikeDecimalIntegerLiteral :: 0 OctalDigit istheMVofOctalDigit.
TheMVofLegacyOctalLikeDecimalIntegerLiteral :: LegacyOctalLikeDecimalIntegerLiteral OctalDigit is(theMVof
LegacyOctalLikeDecimalIntegerLiteraltimes10)plustheMVofOctalDigit.
TheMVofNonOctalDigit :: 8 is8.
TheMVofNonOctalDigit :: 9 is9.

B.1.2 StringLiterals

Thesyntaxandsemanticsof11.8.4isextendedasfollowsexceptthatthisextensionisnotallowedforstrictmodecode:

Syntax

EscapeSequence ::
CharacterEscapeSequence
LegacyOctalEscapeSequence
HexEscapeSequence
UnicodeEscapeSequence

LegacyOctalEscapeSequence ::
OctalDigit [lookaheadOctalDigit]
ZeroToThree OctalDigit [lookaheadOctalDigit]
FourToSeven OctalDigit
ZeroToThree OctalDigit OctalDigit

ZeroToThree :: oneof
0 1 2 3

FourToSeven :: oneof
4 5 6 7

ThisdeinitionofEscapeSequenceisnotusedinstrictmodeorwhenparsingTemplateCharacter.

B.1.2.1 StaticSemantics

TheSVofEscapeSequence :: LegacyOctalEscapeSequence istheSVoftheLegacyOctalEscapeSequence.


TheSVofLegacyOctalEscapeSequence :: OctalDigit isthecodeunitwhosevalueistheMVoftheOctalDigit.
TheSVofLegacyOctalEscapeSequence :: ZeroToThree OctalDigit isthecodeunitwhosevalueis(8timestheMVofthe
ZeroToThree)plustheMVoftheOctalDigit.
TheSVofLegacyOctalEscapeSequence :: FourToSeven OctalDigit isthecodeunitwhosevalueis(8timestheMVofthe
FourToSeven)plustheMVoftheOctalDigit.
TheSVofLegacyOctalEscapeSequence :: ZeroToThree OctalDigit OctalDigit isthecodeunitwhosevalueis(64(that
is,82)timestheMVoftheZeroToThree)plus(8timestheMVoftheirstOctalDigit)plustheMVofthesecondOctalDigit
.
TheMVofZeroToThree :: 0 is0.
TheMVofZeroToThree :: 1 is1.
TheMVofZeroToThree :: 2 is2.
TheMVofZeroToThree :: 3 is3.
TheMVofFourToSeven :: 4 is4.
TheMVofFourToSeven :: 5 is5.
TheMVofFourToSeven :: 6 is6.
TheMVofFourToSeven :: 7 is7.

B.1.3 HTMLlikeComments

Thesyntaxandsemanticsof11.4isextendedasfollowsexceptthatthisextensionisnotallowedwhenparsingsourcecode
usingthegoalsymbolModule:

Syntax

Comment ::
MultiLineComment
SingleLineComment
SingleLineHTMLOpenComment
SingleLineHTMLCloseComment
SingleLineDelimitedComment

MultiLineComment ::
/* FirstCommentLineopt LineTerminator MultiLineCommentCharsopt */ HTMLCloseCommentopt

FirstCommentLine ::
SingleLineDelimitedCommentChars

SingleLineHTMLOpenComment ::
<! SingleLineCommentCharsopt

SingleLineHTMLCloseComment ::
LineTerminatorSequence HTMLCloseComment

SingleLineDelimitedComment ::
/* SingleLineDelimitedCommentCharsopt */

HTMLCloseComment ::
WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt > SingleLineCommentCharsopt

SingleLineDelimitedCommentChars ::
SingleLineNotAsteriskChar SingleLineDelimitedCommentCharsopt
* SingleLinePostAsteriskCommentCharsopt

SingleLineNotAsteriskChar ::
SourceCharacter butnotoneof* orLineTerminator

SingleLinePostAsteriskCommentChars ::
SingleLineNotForwardSlashOrAsteriskChar SingleLineDelimitedCommentCharsopt
* SingleLinePostAsteriskCommentCharsopt

SingleLineNotForwardSlashOrAsteriskChar ::
SourceCharacter butnotoneof/ or* orLineTerminator

WhiteSpaceSequence ::
WhiteSpace WhiteSpaceSequenceopt

SingleLineDelimitedCommentSequence ::
SingleLineDelimitedComment WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt

SimilartoaMultiLineCommentthatcontainsalineterminatorcodepoint,aSingleLineHTMLCloseCommentisconsideredto
beaLineTerminatorforpurposesofparsingbythesyntacticgrammar.

B.1.4 RegularExpressionsPatterns

Thesyntaxof21.2.1ismodiiedandextendedasfollows.Thesechangesintroduceambiguitiesthatarebrokenbythe
orderingofgrammarproductionsandbycontextualinformation.Whenparsingusingthefollowinggrammar,each
alternativeisconsideredonlyifpreviousproductionalternativesdonotmatch.

ThisalternativepatterngrammarandsemanticsonlychangesthesyntaxandsemanticsofBMPpatterns.Thefollowing
grammarextensionsincludeproductionsparameterizedwiththe[U]parameter.However,noneoftheseextensionschange
thesyntaxofUnicodepatternsrecognizedwhenparsingwiththe[U]parameterpresentonthegoalsymbol.

Syntax

Term[U] ::
[+U] Assertion[U]
[+U] Atom[U]
[+U] Atom[U] Quantiier
[~U] QuantiiableAssertion Quantiier
[~U] Assertion
[~U] ExtendedAtom Quantiier
[~U] ExtendedAtom

Assertion[U] ::
^
$
\ b
\ B
[+U] ( ? = Disjunction[U] )
[+U] ( ? ! Disjunction[U] )
[~U] QuantiiableAssertion

QuantiiableAssertion ::
( ? = Disjunction )
( ? ! Disjunction )

ExtendedAtom ::
.
\ AtomEscape
CharacterClass
( Disjunction )
( ? : Disjunction )
InvalidBracedQuantiier
ExtendedPatternCharacter

InvalidBracedQuantiier ::
{ DecimalDigits }
{ DecimalDigits , }
{ DecimalDigits , DecimalDigits }

ExtendedPatternCharacter ::
SourceCharacter butnotoneof^ $ . * + ? ( ) [ |
AtomEscape[U] ::
[+U] DecimalEscape
[+U] CharacterEscape[U]
[+U] CharacterClassEscape
[~U] DecimalEscape butonlyiftheintegervalueofDecimalEscape is<=_NcapturingParens_
[~U] CharacterClassEscape
[~U] CharacterEscape

CharacterEscape[U] ::
ControlEscape
c ControlLetter
HexEscapeSequence
RegExpUnicodeEscapeSequence[?U]
[~U]LegacyOctalEscapeSequence
IdentityEscape[?U]

IdentityEscape[U] ::
[+U] SyntaxCharacter
[+U] /
[~U] SourceCharacter butnotc

NonemptyClassRanges[U] ::
ClassAtom[?U]
ClassAtom[?U] NonemptyClassRangesNoDash[?U]
[+U] ClassAtom[U] ClassAtom[U] ClassRanges[U]
[~U] ClassAtomInRange ClassAtomInRange ClassRanges

NonemptyClassRangesNoDash[U] ::
ClassAtom[?U]
ClassAtomNoDash[?U] NonemptyClassRangesNoDash[?U]
[+U] ClassAtomNoDash[U] ClassAtom[U] ClassRanges[U]
[~U] ClassAtomNoDashInRange ClassAtomInRange ClassRanges

ClassAtom[U] ::

ClassAtomNoDash[?U]

ClassAtomNoDash[U] ::
\ ClassEscape[?U]
SourceCharacter butnotoneof] or

ClassAtomInRange ::

ClassAtomNoDashInRange

ClassAtomNoDashInRange ::
\ ClassEscape
SourceCharacter butnotoneof] or

ClassEscape[U] ::
b
[+U] DecimalEscape
[+U] CharacterEscape[U]
[+U] CharacterClassEscape
[+U]
[~U] DecimalEscape butonlyiftheintegervalueofDecimalEscape is0
[~U] CharacterClassEscape
[~U] c ClassControlLetter
[~U] CharacterEscape

ClassControlLetter ::
DecimalDigit
_

NOTE Whenthesamelefthandsidesoccurswithboth[+U]and[~U]guardsitistocontrolthedisambiguation
priority.

B.1.4.1 PatternSemantics

Thesemanticsof21.2.2isextendedasfollows:

Within21.2.2.5referencetoAtom :: ( Disjunction ) aretobeinterpretedasmeaningAtom :: ( Disjunction ) or


ExtendedAtom :: ( Disjunction ) .

Term(21.2.2.5)includesthefollowingadditionalevaluationrules:

TheproductionTerm :: QuantiiableAssertion Quantiier evaluatesthesameastheproductionTerm :: Atom Quantiier


butwithQuantiiableAssertionsubstitutedforAtom.

TheproductionTerm :: ExtendedAtom Quantiier evaluatesthesameastheproductionTerm :: Atom Quantiier butwith


ExtendedAtomsubstitutedforAtom.

TheproductionTerm :: ExtendedAtom evaluatesthesameastheproductionTerm :: Atom butwithExtendedAtom


substitutedforAtom.

Assertion(21.2.2.6)includesthefollowingadditionalevaluationrule:

TheproductionAssertion :: QuantiiableAssertion evaluatesbyevaluatingQuantiiableAssertiontoobtainaMatcherand


returningthatMatcher.

Assertion(21.2.2.6)evaluationrulesfortheAssertion :: ( ? = Disjunction ) andAssertion :: ( ? ! Disjunction )


productionsarealsousedfortheQuantiiableAssertionproductions,butwithQuantiiableAssertionsubstitutedforAssertion.

Atom(21.2.2.8)evaluationrulesfortheAtomproductionsexceptforAtom :: PatternCharacter arealsousedforthe


ExtendedAtomproductions,butwithExtendedAtomsubstitutedforAtom.Thefollowingevaluationrulesarealsoadded:

TheproductionExtendedAtom :: InvalidBracedQuantiier evaluatesasfollows:

1.ThrowaSyntaxErrorexception.

TheproductionExtendedAtom :: ExtendedPatternCharacter evaluatesasfollows:

1.LetchbethecharacterrepresentedbyExtendedPatternCharacter.
2.LetAbeaoneelementCharSetcontainingthecharacterch.
3.CallCharacterSetMatcher(A,false)andreturnitsMatcherresult.

CharacterEscape(21.2.2.10)includesthefollowingadditionalevaluationrule:

TheproductionCharacterEscape :: LegacyOctalEscapeSequence evaluatesbyevaluatingtheSVofthe


LegacyOctalEscapeSequence(seeB.1.2)andreturningitscharacterresult.

NonemptyClassRanges(21.2.2.15)includesthefollowingadditionalevaluationrule:

TheproductionNonemptyClassRanges :: ClassAtomInRange ClassAtomInRange ClassRanges evaluatesasfollows:


1.EvaluatetheirstClassAtomInRangetoobtainaCharSetA.
2.EvaluatethesecondClassAtomInRangetoobtainaCharSetB.
3.EvaluateClassRangestoobtainaCharSetC.
4.CallCharacterRangeOrUnion(A,B)andletDbetheresultingCharSet.
5.ReturntheunionofCharSetsDandC.

NonemptyClassRangesNoDash(21.2.2.16)includesthefollowingadditionalevaluationrule:

TheproductionNonemptyClassRangesNoDash :: ClassAtomNoDashInRange ClassAtomInRange ClassRanges evaluatesas


follows:

1.EvaluateClassAtomNoDashInRangetoobtainaCharSetA.
2.EvaluateClassAtomInRangetoobtainaCharSetB.
3.EvaluateClassRangestoobtainaCharSetC.
4.CallCharacterRangeOrUnion(A,B)andletDbetheresultingCharSet.
5.ReturntheunionofCharSetsDandC.

ClassAtom(21.2.2.17)includesthefollowingadditionalevaluationrules:

TheproductionClassAtomInRange :: evaluatesbyreturningtheCharSetcontainingtheonecharacter.

TheproductionClassAtomInRange :: ClassAtomNoDashInRange evaluatesbyevaluatingClassAtomNoDashInRangetoobtain


aCharSetandreturningthatCharSet.

ClassAtomNoDash(21.2.2.18)includesthefollowingadditionalevaluationrules:

TheproductionClassAtomNoDash :: SourceCharacter butnotoneof] or evaluatesbyreturningaoneelementCharSet


containingthecharacterrepresentedbySourceCharacter.

TheproductionClassAtomNoDashInRange :: \ ClassEscape evaluatesbyevaluatingClassEscapetoobtainaCharSetand


returningthatCharSet.

TheproductionClassAtomNoDashInRange :: SourceCharacter butnotoneof] or evaluatesbyreturningaoneelement


CharSetcontainingthecharacterrepresentedbySourceCharacter.

ClassEscape(21.2.2.19)includesthefollowingadditionalevaluationrules:

TheproductionClassEscape :: DecimalEscape butonlyifevaluatesasfollows:

1.EvaluateDecimalEscapetoobtainanEscapeValueE.
2.Assert:Eisacharacter.
3.LetchbeE'scharacter.
4.ReturntheoneelementCharSetcontainingthecharacterch.

TheproductionClassEscape :: c ClassControlLetter evaluatesasfollows:

1.LetchbethecharactermatchedbyClassControlLetter.
2.Letibech'scharactervalue.
3.Letjbetheremainderofdividingiby32.
4.Returnthecharacterwhosecharactervalueisj.

B.1.4.1.1 RuntimeSemantics:CharacterRangeOrUnionAbstractOperation

TheabstractoperationCharacterRangeOrUniontakestwoCharSetparametersAandBandperformsthefollowingsteps:

1.IfAdoesnotcontainexactlyonecharacterorBdoesnotcontainexactlyonecharacter,then
a.LetCbetheCharSetcontainingthesinglecharacterU+002D(HYPHENMINUS).
b.ReturntheunionofCharSetsA,BandC.
2.ReturnCharacterRange(A,B).
B.2 AdditionalBuiltinProperties
WhentheECMAScripthostisawebbrowserthefollowingadditionalpropertiesofthestandardbuiltinobjectsaredeined.

B.2.1 AdditionalPropertiesoftheGlobalObject

TheentriesinTable61areaddedtoTable7.

Table61:AdditionalWellknownIntrinsicObjects
IntrinsicName GlobalName ECMAScriptLanguageAssociation

%escape% escape Theescapefunction(B.2.1.1)

%unescape% unescape Theunescapefunction(B.2.1.2)

B.2.1.1 escape(string)

Theescapefunctionisapropertyoftheglobalobject.ItcomputesanewversionofaStringvalueinwhichcertaincode
unitshavebeenreplacedbyahexadecimalescapesequence.

Forthosecodeunitsbeingreplacedwhosevalueis0x00FForless,atwodigitescapesequenceoftheform%xxisused.For
thosecharactersbeingreplacedwhosecodeunitvalueisgreaterthan0x00FF,afourdigitescapesequenceoftheform
%uxxxxisused.

Theescapefunctionisthe%escape%intrinsicobject.Whentheescapefunctioniscalledwithoneargumentstring,the
followingstepsaretaken:

1.Letstringbe?ToString(string).
2.Letlengthbethenumberofcodeunitsinstring.
3.LetRbetheemptystring.
4.Letkbe0.
5.Repeat,whilek<length,
a.Letcharbethecodeunit(representedasa16bitunsignedinteger)atindexkwithinstring.
b.Ifcharisoneofthecodeunitsin
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+./",then
i.LetSbeaStringcontainingthesinglecodeunitchar.
c.Elseifchar256,then
i.LetSbeaStringcontainingsixcodeunits"%uwxyz"wherewxyzarethecodeunitsofthefourhexadecimal
digitsencodingthevalueofchar.
d.Else,char<256
i.LetSbeaStringcontainingthreecodeunits"%xy"wherexyarethecodeunitsoftwohexadecimaldigits
encodingthevalueofchar.
e.LetRbeanewStringvaluecomputedbyconcatenatingthepreviousvalueofRandS.
f.Increasekby1.
6.ReturnR.

NOTE TheencodingispartlybasedontheencodingdescribedinRFC1738,buttheentireencodingspeciiedinthis
standardisdescribedabovewithoutregardtothecontentsofRFC1738.Thisencodingdoesnotrelect
changestoRFC1738madebyRFC3986.

B.2.1.2 unescape(string)

Theunescapefunctionisapropertyoftheglobalobject.ItcomputesanewversionofaStringvalueinwhicheachescape
sequenceofthesortthatmightbeintroducedbytheescapefunctionisreplacedwiththecodeunitthatitrepresents.
Theunescapefunctionisthe%unescape%intrinsicobject.Whentheunescapefunctioniscalledwithoneargumentstring,
thefollowingstepsaretaken:

1.Letstringbe?ToString(string).
2.Letlengthbethenumberofcodeunitsinstring.
3.LetRbetheemptyString.
4.Letkbe0.
5.Repeat,whileklength
a.Letcbethecodeunitatindexkwithinstring.
b.Ifcis%,then
i.Ifklength6andthecodeunitatindexk+1withinstringisuandthefourcodeunitsatindicesk+2,k+3,
k+4,andk+5withinstringareallhexadecimaldigits,then
1.Letcbethecodeunitwhosevalueistheintegerrepresentedbythefourhexadecimaldigitsatindices
k+2,k+3,k+4,andk+5withinstring.
2.Increasekby5.
ii.Elseifklength3andthetwocodeunitsatindicesk+1andk+2withinstringarebothhexadecimaldigits,
then
1.Letcbethecodeunitwhosevalueistheintegerrepresentedbytwozeroesplusthetwohexadecimal
digitsatindicesk+1andk+2withinstring.
2.Increasekby2.
c.LetRbeanewStringvaluecomputedbyconcatenatingthepreviousvalueofRandc.
d.Increasekby1.
6.ReturnR.

B.2.2 AdditionalPropertiesoftheObject.prototypeObject

B.2.2.1 Object.prototype.__proto__

Object.prototype.__proto__isanaccessorpropertywithattributes{[[Enumerable]]:false,[[Conigurable]]:true}.The
[[Get]]and[[Set]]attributesaredeinedasfollows:

B.2.2.1.1 getObject.prototype.__proto__

Thevalueofthe[[Get]]attributeisabuiltinfunctionthatrequiresnoarguments.Itperformsthefollowingsteps:

1.LetObe?ToObject(thisvalue).
2.Return?O.[[GetPrototypeOf]]().

B.2.2.1.2 setObject.prototype.__proto__

Thevalueofthe[[Set]]attributeisabuiltinfunctionthattakesanargumentproto.Itperformsthefollowingsteps:

1.LetObe?RequireObjectCoercible(thisvalue).
2.IfType(proto)isneitherObjectnorNull,returnundeined.
3.IfType(O)isnotObject,returnundeined.
4.Letstatusbe?O.[[SetPrototypeOf]](proto).
5.Ifstatusisfalse,throwaTypeErrorexception.
6.Returnundeined.

B.2.3 AdditionalPropertiesoftheString.prototypeObject

B.2.3.1 String.prototype.substr(start,length)

Thesubstrmethodtakestwoarguments,startandlength,andreturnsasubstringoftheresultofconvertingthethisobject
toaString,startingfromindexstartandrunningforlengthcodeunits(orthroughtheendoftheStringiflengthis
undeined).Ifstartisnegative,itistreatedassourceLength+startwheresourceLengthisthelengthoftheString.Theresult
isaStringvalue,notaStringobject.Thefollowingstepsaretaken:
1.LetObe?RequireObjectCoercible(thisvalue).
2.LetSbe?ToString(O).
3.LetintStartbe?ToInteger(start).
4.Iflengthisundeined,letendbe+;otherwiseletendbe?ToInteger(length).
5.LetsizebethenumberofcodeunitsinS.
6.IfintStart<0,letintStartbemax(size+intStart,0).
7.LetresultLengthbemin(max(end,0),sizeintStart).
8.IfresultLength0,returntheemptyString"".
9.ReturnaStringcontainingresultLengthconsecutivecodeunitsfromSbeginningwiththecodeunitatindexintStart.

NOTE Thesubstrfunctionisintentionallygeneric;itdoesnotrequirethatitsthisvaluebeaStringobject.Therefore
itcanbetransferredtootherkindsofobjectsforuseasamethod.

B.2.3.2 String.prototype.anchor(name)

Whentheanchormethodiscalledwithargumentname,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"a","name",name).

B.2.3.2.1 RuntimeSemantics:CreateHTML(string,tag,attribute,value)

TheabstractoperationCreateHTMLiscalledwithargumentsstring,tag,attribute,andvalue.Theargumentstagand
attributemustbeStringvalues.Thefollowingstepsaretaken:

1.Letstrbe?RequireObjectCoercible(string).
2.LetSbe?ToString(str).
3.Letp1betheStringvaluethatistheconcatenationof"<"andtag.
4.IfattributeisnottheemptyString,then
a.LetVbe?ToString(value).
b.LetescapedVbetheStringvaluethatisthesameasVexceptthateachoccurrenceofthecodeunit0x0022
(QUOTATIONMARK)inVhasbeenreplacedwiththesixcodeunitsequence"&quot;".
c.Letp1betheStringvaluethatistheconcatenationofthefollowingStringvalues:
TheStringvalueofp1
Codeunit0x0020(SPACE)
TheStringvalueofattribute
Codeunit0x003D(EQUALSSIGN)
Codeunit0x0022(QUOTATIONMARK)
TheStringvalueofescapedV
Codeunit0x0022(QUOTATIONMARK)
5.Letp2betheStringvaluethatistheconcatenationofp1and">".
6.Letp3betheStringvaluethatistheconcatenationofp2andS.
7.Letp4betheStringvaluethatistheconcatenationofp3,"</",tag,and">".
8.Returnp4.

B.2.3.3 String.prototype.big()

Whenthebigmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"big","","").

B.2.3.4 String.prototype.blink()

Whentheblinkmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"blink","","").
B.2.3.5 String.prototype.bold()

Whentheboldmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"b","","").

B.2.3.6 String.prototype.ixed()

Whenthefixedmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"tt","","").

B.2.3.7 String.prototype.fontcolor(color)

Whenthefontcolormethodiscalledwithargumentcolor,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"font","color",color).

B.2.3.8 String.prototype.fontsize(size)

Whenthefontsizemethodiscalledwithargumentsize,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"font","size",size).

B.2.3.9 String.prototype.italics()

Whentheitalicsmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"i","","").

B.2.3.10 String.prototype.link(url)

Whenthelinkmethodiscalledwithargumenturl,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"a","href",url).

B.2.3.11 String.prototype.small()

Whenthesmallmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"small","","").

B.2.3.12 String.prototype.strike()

Whenthestrikemethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"strike","","").

B.2.3.13 String.prototype.sub()

Whenthesubmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"sub","","").

B.2.3.14 String.prototype.sup()

Whenthesupmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.LetSbethethisvalue.
2.Return?CreateHTML(S,"sup","","").

B.2.4 AdditionalPropertiesoftheDate.prototypeObject

B.2.4.1 Date.prototype.getYear()

NOTE ThegetFullYearmethodispreferredfornearlyallpurposes,becauseitavoidstheyear2000problem.

WhenthegetYearmethodiscalledwithnoarguments,thefollowingstepsaretaken:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,returnNaN.
3.ReturnYearFromTime(LocalTime(t))1900.

B.2.4.2 Date.prototype.setYear(year)

NOTE ThesetFullYearmethodispreferredfornearlyallpurposes,becauseitavoidstheyear2000problem.

WhenthesetYearmethodiscalledwithoneargumentyear,thefollowingstepsaretaken:

1.Lettbe?thisTimeValue(thisvalue).
2.IftisNaN,lettbe+0;otherwise,lettbeLocalTime(t).
3.Letybe?ToNumber(year).
4.IfyisNaN,setthe[[DateValue]]internalslotofthisDateobjecttoNaNandreturnNaN.
5.IfyisnotNaNand0ToInteger(y)99,letyyyybeToInteger(y)+1900.
6.Else,letyyyybey.
7.LetdbeMakeDay(yyyy,MonthFromTime(t),DateFromTime(t)).
8.LetdatebeUTC(MakeDate(d,TimeWithinDay(t))).
9.Setthe[[DateValue]]internalslotofthisDateobjecttoTimeClip(date).
10.Returnthevalueofthe[[DateValue]]internalslotofthisDateobject.

B.2.4.3 Date.prototype.toGMTString()

NOTE ThepropertytoUTCStringispreferred.ThetoGMTStringpropertyisprovidedprincipallyforcompatibility
witholdcode.ItisrecommendedthatthetoUTCStringpropertybeusedinnewECMAScriptcode.

ThefunctionobjectthatistheinitialvalueofDate.prototype.toGMTStringisthesamefunctionobjectthatistheinitial
valueofDate.prototype.toUTCString.

B.2.5 AdditionalPropertiesoftheRegExp.prototypeObject

B.2.5.1 RegExp.prototype.compile(pattern,lags)

Whenthecompilemethodiscalledwithargumentspatternandlags,thefollowingstepsaretaken:

1.LetObethethisvalue.
2.IfType(O)isnotObjectorType(O)isObjectandOdoesnothavea[[RegExpMatcher]]internalslot,then
a.ThrowaTypeErrorexception.
3.IfType(pattern)isObjectandpatternhasa[[RegExpMatcher]]internalslot,then
a.Iflagsisnotundeined,throwaTypeErrorexception.
b.LetPbethevalueofpattern's[[OriginalSource]]internalslot.
c.LetFbethevalueofpattern's[[OriginalFlags]]internalslot.
4.Else,
a.LetPbepattern.
b.LetFbelags.
5.Return?RegExpInitialize(O,P,F).

NOTE ThecompilemethodcompletelyreinitializesthethisobjectRegExpwithanewpatternandlags.An
implementationmayinterpretuseofthismethodasanassertionthattheresultingRegExpobjectwillbeused
multipletimesandhenceisacandidateforextraoptimization.

B.3 OtherAdditionalFeatures
B.3.1 __proto__PropertyNamesinObjectInitializers

ThefollowingEarlyErrorruleisaddedtothosein12.2.6.1.WhenObjectLiteralappearsinacontextwhere
ObjectAssignmentPatternisrequiredtheEarlyErrorruleisnotapplied.Inaddition,itisnotappliedwheninitiallyparsinga
CoverParenthesizedExpressionAndArrowParameterList.

ObjectLiteral : { PropertyDeinitionList }
ObjectLiteral : { PropertyDeinitionList , }

ItisaSyntaxErrorifPropertyNameListofPropertyDeinitionListcontainsanyduplicateentriesfor"__proto__"andat
leasttwoofthoseentrieswereobtainedfromproductionsoftheformPropertyDeinition : PropertyName :
AssignmentExpression .

NOTE TheListreturnedbyPropertyNameListdoesnotincludestringliteralpropertynamesdeinedasusinga
ComputedPropertyName.

In12.2.6.9thePropertyDeinitionEvaluationalgorithmfortheproduction
PropertyDeinition : PropertyName : AssignmentExpression
isreplacedwiththefollowingdeinition:

PropertyDeinition : PropertyName : AssignmentExpression

1.LetpropKeybetheresultofevaluatingPropertyName.
2.ReturnIfAbrupt(propKey).
3.LetexprValueRefbetheresultofevaluatingAssignmentExpression.
4.LetpropValuebe?GetValue(exprValueRef).
5.IfpropKeyistheStringvalue"__proto__"andifIsComputedPropertyKey(propKey)isfalse,then
a.IfType(propValue)iseitherObjectorNull,then
i.Returnobject.[[SetPrototypeOf]](propValue).
b.ReturnNormalCompletion(empty).
6.IfIsAnonymousFunctionDeinition(AssignmentExpression)istrue,then
a.LethasNamePropertybe?HasOwnProperty(propValue,"name").
b.IfhasNamePropertyisfalse,performSetFunctionName(propValue,propKey).
7.Assert:enumerableistrue.
8.ReturnCreateDataPropertyOrThrow(object,propKey,propValue).

B.3.2 LabelledFunctionDeclarations

PriortoECMAScript2015,thespeciicationofLabelledStatementdidnotallowfortheassociationofastatementlabelwitha
FunctionDeclaration.However,alabelledFunctionDeclarationwasanallowableextensionfornonstrictcodeandmost
browserhostedECMAScriptimplementationssupportedthatextension.InECMAScript2015,thegrammarproductionsfor
LabelledStatementpermitsuseofFunctionDeclarationasaLabelledItembut13.13.1includesanEarlyErrorrulethat
producesaSyntaxErrorifthatoccurs.Forwebbrowsercompatibility,thatruleismodiiedwiththeadditionofthe
highlightedtext:

LabelledItem : FunctionDeclaration
ItisaSyntaxErrorifanystrictmodesourcecodematchesthisrule.

B.3.3 BlockLevelFunctionDeclarationsWebLegacyCompatibilitySemantics

PriortoECMAScript2015,theECMAScriptspeciicationdidnotdeinetheoccurrenceofaFunctionDeclarationasanelement
ofaBlockstatement'sStatementList.However,supportforthatformofFunctionDeclarationwasanallowableextensionand
mostbrowserhostedECMAScriptimplementationspermittedthem.Unfortunately,thesemanticsofsuchdeclarationsdiffer
amongthoseimplementations.Becauseofthesesemanticdifferences,existingwebECMAScriptcodethatusesBlocklevel
functiondeclarationsisonlyportableamongbrowserimplementationiftheusageonlydependsuponthesemantic
intersectionofallofthebrowserimplementationsforsuchdeclarations.Thefollowingaretheusecasesthatfallwithinthat
intersectionsemantics:

1.Afunctionisdeclaredandonlyreferencedwithinasingleblock

AFunctionDeclarationwhoseBindingIdentiieristhenamefoccursexactlyoncewithinthefunctioncodeofan
enclosingfunctiongandthatdeclarationisnestedwithinaBlock.
Nootherdeclarationoffthatisnotavardeclarationoccurswithinthefunctioncodeofg
AlloccurrencesoffasanIdentiierReferencearewithintheStatementListoftheBlockcontainingthedeclarationof
f.

2.AfunctionisdeclaredandpossiblyusedwithinasingleBlockbutalsoreferencedbyaninnerfunctiondeinitionthatis
notcontainedwithinthatsameBlock.

AFunctionDeclarationwhoseBindingIdentiieristhenamefoccursexactlyoncewithinthefunctioncodeofan
enclosingfunctiongandthatdeclarationisnestedwithinaBlock.
Nootherdeclarationoffthatisnotavardeclarationoccurswithinthefunctioncodeofg
TheremaybeoccurrencesoffasanIdentiierReferencewithintheStatementListoftheBlockcontainingthe
declarationoff.
ThereisatleastoneoccurrenceoffasanIdentiierReferencewithinanotherfunctionhthatisnestedwithingand
nootherdeclarationoffshadowsthereferencestoffromwithinh.
Allinvocationsofhoccurafterthedeclarationoffhasbeenevaluated.

3.Afunctionisdeclaredandpossiblyusedwithinasingleblockbutalsoreferencedwithinsubsequentblocks.

AFunctionDeclarationwhoseBindingIdentiieristhenamefoccursexactlyoncewithinthefunctioncodeofan
enclosingfunctiongandthatdeclarationisnestedwithinaBlock.
Nootherdeclarationoffthatisnotavardeclarationoccurswithinthefunctioncodeofg
TheremaybeoccurrencesoffasanIdentiierReferencewithintheStatementListoftheBlockcontainingthe
declarationoff.
ThereisatleastoneoccurrenceoffasanIdentiierReferencewithinthefunctioncodeofgthatlexicallyfollowsthe
Blockcontainingthedeclarationoff.

TheirstusecaseisinteroperablewiththesemanticsofBlocklevelfunctiondeclarationsprovidedbyECMAScript2015.Any
preexistingECMAScriptcodethatemploysthatusecasewilloperateusingtheBlocklevelfunctiondeclarationssemantics
deinedbyclauses9,13,and14ofthisspeciication.

ECMAScript2015interoperabilityforthesecondandthirdusecasesrequiresthefollowingextensionstotheclause9,clause
14,clause18.2.1andclause15.1.11semantics.

IfanECMAScriptimplementationhasamechanismforreportingdiagnosticwarningmessages,awarningshouldbe
producedwhencodecontainsaFunctionDeclarationforwhichthesecompatibilitysemanticsareappliedandintroduce
observabledifferencesfromnoncompatibilitysemantics.Forexample,ifavarbindingisnotintroducedbecauseits
introductionwouldcreateanearlyerror,awarningmessageshouldnotbeproduced.

B.3.3.1 ChangestoFunctionDeclarationInstantiation

DuringFunctionDeclarationInstantiationthefollowingstepsareperformedinplaceofstep29:
1.Ifstrictisfalse,then
a.ForeachFunctionDeclarationfthatisdirectlycontainedintheStatementListofaBlock,CaseClause,or
DefaultClause,
i.LetFbeStringValueoftheBindingIdentiierofFunctionDeclarationf.
ii.IfreplacingtheFunctionDeclarationfwithaVariableStatementthathasFasaBindingIdentiierwouldnot
produceanyEarlyErrorsforfuncandFisnotanelementofBoundNamesofargumentsList,then
1.NOTEAvarbindingforFisonlyinstantiatedhereifitisneitheraVarDeclaredName,thenameofa
formalparameter,oranotherFunctionDeclaration.
2.IfinstantiatedVarNamesdoesnotcontainF,then
a.Perform!varEnvRec.CreateMutableBinding(F,false).
b.PerformvarEnvRec.InitializeBinding(F,undeined).
c.AppendFtoinstantiatedVarNames.
3.WhentheFunctionDeclarationfisevaluated,performthefollowingstepsinplaceofthe
FunctionDeclarationEvaluationalgorithmprovidedin14.1.21:
a.Letfenvbetherunningexecutioncontext'sVariableEnvironment.
b.LetfenvRecbefenv'sEnvironmentRecord.
c.Letbenvbetherunningexecutioncontext'sLexicalEnvironment.
d.LetbenvRecbebenv'sEnvironmentRecord.
e.Letfobjbe!benvRec.GetBindingValue(F,false).
f.Perform!fenvRec.SetMutableBinding(F,fobj,false).
g.ReturnNormalCompletion(empty).

B.3.3.2 ChangestoGlobalDeclarationInstantiation

DuringGlobalDeclarationInstantiationthefollowingstepsareperformedinplaceofstep14:

1.LetstrictbeIsStrictofscript
2.Ifstrictisfalse,then
a.LetdeclaredFunctionOrVarNamesbeanewemptyList.
b.AppendtodeclaredFunctionOrVarNamestheelementsofdeclaredFunctionNames.
c.AppendtodeclaredFunctionOrVarNamestheelementsofdeclaredVarNames.
d.ForeachFunctionDeclarationfthatisdirectlycontainedintheStatementListofaBlock,CaseClause,or
DefaultClauseContainedwithinscript,
i.LetFbeStringValueoftheBindingIdentiierofFunctionDeclarationf.
ii.IfreplacingtheFunctionDeclarationfwithaVariableStatementthathasFasaBindingIdentiierwouldnot
produceanyEarlyErrorsforscript,then
1.IfenvRec.HasLexicalDeclaration(F)isfalse,then
a.LetfnDeinablebe?envRec.CanDeclareGlobalFunction(F).
b.IffnDeinableistrue,then
i.NOTEAvarbindingforFisonlyinstantiatedhereifitisneitheraVarDeclaredNamenorthe
nameofanotherFunctionDeclaration.
ii.IfdeclaredFunctionOrVarNamesdoesnotcontainF,then
i.Perform?envRec.CreateGlobalFunctionBinding(F,undeined,false).
ii.AppendFtodeclaredFunctionOrVarNames.
iii.WhentheFunctionDeclarationfisevaluated,performthefollowingstepsinplaceofthe
FunctionDeclarationEvaluationalgorithmprovidedin14.1.21:
i.Letgenvbetherunningexecutioncontext'sVariableEnvironment.
ii.LetgenvRecbegenv'sEnvironmentRecord.
iii.Letbenvbetherunningexecutioncontext'sLexicalEnvironment.
iv.LetbenvRecbebenv'sEnvironmentRecord.
v.Letfobjbe!benvRec.GetBindingValue(F,false).
vi.Perform?genvRec.SetMutableBinding(F,fobj,false).
vii.ReturnNormalCompletion(empty).

B.3.3.3 ChangestoEvalDeclarationInstantiation
DuringEvalDeclarationInstantiationthefollowingstepsareperformedinplaceofstep9:

1.Ifstrictisfalse,then
a.LetdeclaredFunctionOrVarNamesbeanewemptyList.
b.AppendtodeclaredFunctionOrVarNamestheelementsofdeclaredFunctionNames.
c.AppendtodeclaredFunctionOrVarNamestheelementsofdeclaredVarNames.
d.ForeachFunctionDeclarationfthatisdirectlycontainedintheStatementListofaBlock,CaseClause,or
DefaultClauseContainedwithinbody,
i.LetFbeStringValueoftheBindingIdentiierofFunctionDeclarationf.
ii.IfreplacingtheFunctionDeclarationfwithaVariableStatementthathasFasaBindingIdentiierwouldnot
produceanyEarlyErrorsforbody,then
1.LetbindingExistsbefalse.
2.LetthisLexbelexEnv.
3.Assert:thefollowingloopwillterminate.
4.RepeatwhilethisLexisnotthesameasvarEnv,
a.LetthisEnvRecbethisLex'sEnvironmentRecord.
b.IfthisEnvRecisnotanobjectEnvironmentRecord,then
i.IfthisEnvRec.HasBinding(F)istrue,then
i.LetbindingExistsbetrue.
c.LetthisLexbethisLex'souterenvironmentreference.
5.IfbindingExistsisfalseandvarEnvRecisaglobalEnvironmentRecord,then
a.IfvarEnvRec.HasLexicalDeclaration(F)isfalse,then
i.LetfnDeinablebe?varEnvRec.CanDeclareGlobalFunction(F).
b.Else,
i.LetfnDeinablebefalse.
6.Else,
a.LetfnDeinablebetrue.
7.IfbindingExistsisfalseandfnDeinableistrue,then
a.IfdeclaredFunctionOrVarNamesdoesnotcontainF,then
i.IfvarEnvRecisaglobalEnvironmentRecord,then
i.Perform?varEnvRec.CreateGlobalFunctionBinding(F,undeined,true).
ii.Else,
i.LetbindingExistsbevarEnvRec.HasBinding(F).
ii.IfbindingExistsisfalse,then
i.Perform!varEnvRec.CreateMutableBinding(F,true).
ii.Perform!varEnvRec.InitializeBinding(F,undeined).
iii.AppendFtodeclaredFunctionOrVarNames.
b.WhentheFunctionDeclarationfisevaluated,performthefollowingstepsinplaceofthe
FunctionDeclarationEvaluationalgorithmprovidedin14.1.21:
i.Letgenvbetherunningexecutioncontext'sVariableEnvironment.
ii.LetgenvRecbegenv'sEnvironmentRecord.
iii.Letbenvbetherunningexecutioncontext'sLexicalEnvironment.
iv.LetbenvRecbebenv'sEnvironmentRecord.
v.Letfobjbe!benvRec.GetBindingValue(F,false).
vi.Perform?genvRec.SetMutableBinding(F,fobj,false).
vii.ReturnNormalCompletion(empty).

B.3.4 FunctionDeclarationsinIfStatementStatementClauses

ThefollowingrulesforIfStatementaugmentthosein13.6:

IfStatement[Yield,Return] :
if ( Expression[In,?Yield] ) FunctionDeclaration[?Yield] else Statement[?Yield,?Return]
if ( Expression[In,?Yield] ) Statement[?Yield,?Return] else FunctionDeclaration[?Yield]
if ( Expression[In,?Yield] ) FunctionDeclaration[?Yield] else FunctionDeclaration[?Yield]
if ( Expression[In,?Yield] ) FunctionDeclaration[?Yield]

Theaboverulesareonlyappliedwhenparsingcodethatisnotstrictmodecode.Ifanysuchcodeismatchbyoneofthese
rulessubsequentprocessingofthatcodetakesplacesasifeachmatchingoccurrenceofFunctionDeclaration[?Yield] was
thesoleStatementListItemofaBlockStatementoccupyingthatpositioninthesourcecode.Thesemanticsofsuchasynthetic
BlockStatementincludestheweblegacycompatibilitysemanticsspeciiedinB.3.3.

B.3.5 VariableStatementsinCatchBlocks

Thecontentofsubclause13.15.1isreplacedwiththefollowing:

Catch : catch ( CatchParameter ) Block

ItisaSyntaxErrorifBoundNamesofCatchParametercontainsanyduplicateelements.
ItisaSyntaxErrorifanyelementoftheBoundNamesofCatchParameteralsooccursintheLexicallyDeclaredNamesof
Block.
ItisaSyntaxErrorifanyelementoftheBoundNamesofCatchParameteralsooccursintheVarDeclaredNamesofBlock
unlessCatchParameterisCatchParameter : BindingIdentiier andthatelementisonlyboundbyaVariableStatement,
theVariableDeclarationListofaforstatement,ortheForBindingofaforinstatement.

NOTE TheBlockofaCatchclausemaycontainvardeclarationsthatbindanamethatisalsoboundbythe
CatchParameter.Atruntime,suchbindingsareinstantiatedintheVariableDeclarationEnvironment.Theydo
notshadowthesamenamedbindingsintroducedbytheCatchParameterandhencetheInitializerforsuchvar
declarationswillassigntothecorrespondingcatchparameterratherthanthevarbinding.Therelaxationof
thenormalstaticsemanticruledoesnotapplytonamesonlyboundbyforofstatements.

Thismodiiedbehaviouralsoappliestovarandfunctiondeclarationsintroducedbydirectevalcallscontainedwithinthe
BlockofaCatchclause.Thischangeisaccomplishedbymodifythealgorithmof18.2.1.2asfollows:

Step5.d.ii.2.a.iisreplacedby:

1.IfthisEnvRecisnottheEnvironmentRecordforaCatchclause,throwaSyntaxErrorexception.
2.IfnameisboundbyanysyntacticformotherthanaFunctionDeclaration,aVariableStatement,the
VariableDeclarationListofaforstatement,ortheForBindingofaforinstatement,throwaSyntaxErrorexception.

Step9.d.ii.4.b.i.iisreplacedby:

1.IfthisEnvRecisnottheEnvironmentRecordforaCatchclause,letbindingExistsbetrue.
AnnexC
TheStrictModeofECMAScript
(informative)
Thestrictmoderestrictionandexceptions

implements,interface,let,package,private,protected,public,static,andyieldarereservedwordswithin
strictmodecode.(11.6.2).
Aconformingimplementation,whenprocessingstrictmodecode,mustnotextend,asdescribedinB.1.1,thesyntaxof
NumericLiteraltoincludeLegacyOctalIntegerLiteral,norextendthesyntaxofDecimalIntegerLiteraltoinclude
NonOctalDecimalIntegerLiteral.
Aconformingimplementation,whenprocessingstrictmodecode,maynotextendthesyntaxofEscapeSequenceto
includeLegacyOctalEscapeSequenceasdescribedinB.1.2.
Assignmenttoanundeclaredidentiierorotherwiseunresolvablereferencedoesnotcreateapropertyintheglobal
object.Whenasimpleassignmentoccurswithinstrictmodecode,itsLeftHandSideExpressionmustnotevaluatetoan
unresolvableReference.IfitdoesaReferenceErrorexceptionisthrown(6.2.3.2).TheLeftHandSideExpressionalsomay
notbeareferencetoadatapropertywiththeattributevalue{[[Writable]]:false},toanaccessorpropertywiththe
attributevalue{[[Set]]:undeined},nortoanonexistentpropertyofanobjectwhose[[Extensible]]internalslothas
thevaluefalse.InthesecasesaTypeErrorexceptionisthrown(12.15).
TheidentiierevalorargumentsmaynotappearastheLeftHandSideExpressionofanAssignmentoperator(12.15)or
ofaUpdateExpression(12.4)orastheUnaryExpressionoperateduponbyaPreixIncrement(12.4.6)oraPreix
Decrement(12.4.7)operator.
Argumentsobjectsforstrictmodefunctionsdeinenonconigurableaccessorpropertiesnamed"caller"and
"callee"whichthrowaTypeErrorexceptiononaccess(9.2.7).
Argumentsobjectsforstrictmodefunctionsdonotdynamicallysharetheirarrayindexedpropertyvalueswiththe
correspondingformalparameterbindingsoftheirfunctions.(9.4.4).
Forstrictmodefunctions,ifanargumentsobjectiscreatedthebindingofthelocalidentiierargumentstothe
argumentsobjectisimmutableandhencemaynotbethetargetofanassignmentexpression.(9.2.12).
ItisaSyntaxErroriftheIdentiierNameevalortheIdentiierNameargumentsoccursasaBindingIdentiierwithin
strictmodecode(12.1.1).
Strictmodeevalcodecannotinstantiatevariablesorfunctionsinthevariableenvironmentofthecallertoeval.Instead,
anewvariableenvironmentiscreatedandthatenvironmentisusedfordeclarationbindinginstantiationfortheeval
code(18.2.1).
Ifthisisevaluatedwithinstrictmodecode,thenthethisvalueisnotcoercedtoanobject.Athisvalueofnullor
undeinedisnotconvertedtotheglobalobjectandprimitivevaluesarenotconvertedtowrapperobjects.Thethis
valuepassedviaafunctioncall(includingcallsmadeusingFunction.prototype.applyand
Function.prototype.call)donotcoercethepassedthisvaluetoanobject(9.2.1.2,19.2.3.1,19.2.3.3).
Whenadeleteoperatoroccurswithinstrictmodecode,aSyntaxErroristhrownifitsUnaryExpressionisadirect
referencetoavariable,functionargument,orfunctionname(12.5.3.1).
Whenadeleteoperatoroccurswithinstrictmodecode,aTypeErroristhrownifthepropertytobedeletedhasthe
attribute{[[Conigurable]]:false}(12.5.3.2).
StrictmodecodemaynotincludeaWithStatement.TheoccurrenceofaWithStatementinsuchacontextisa
SyntaxError(13.11.1).
ItisaSyntaxErrorifaTryStatementwithaCatchoccurswithinstrictmodecodeandtheIdentiieroftheCatch
productionisevalorarguments(13.15.1).
ItisaSyntaxErrorifthesameBindingIdentiierappearsmorethanonceintheFormalParametersofastrictmode
function.AnattempttocreatesuchafunctionusingaFunctionorGeneratorconstructorisaSyntaxError(14.1.2,
19.2.1.1.1).
Animplementationmaynotextend,beyondthatdeinedinthisspeciication,themeaningswithinstrictmodefunctions
ofpropertiesnamedcallerorargumentsoffunctioninstances.ECMAScriptcodemaynotcreateormodifyproperties
withthesenamesonfunctionobjectsthatcorrespondtostrictmodefunctions(16.2).
AnnexD
CorrectionsandClariicationsinECMAScript2015with
PossibleCompatibilityImpact
(informative)
8.1.1.4.158.1.1.4.18Edition5and5.1usedapropertyexistencetesttodeterminewhetheraglobalobjectproperty
correspondingtoanewglobaldeclarationalreadyexisted.ECMAScript2015usesanownpropertyexistencetest.This
correspondstowhathasbeenmostcommonlyimplementedbywebbrowsers.

9.4.2.1:The5thEditionmovedthecaptureofthecurrentarraylengthpriortotheintegerconversionofthearrayindexor
newlengthvalue.However,thecapturedlengthvaluecouldbecomeinvalidiftheconversionprocesshasthesideeffectof
changingthearraylength.ECMAScript2015speciiesthatthecurrentarraylengthmustbecapturedafterthepossible
occurrenceofsuchsideeffects.

20.3.1.15:PreviouseditionspermittedtheTimeClipabstractoperationtoreturneither+0or0astherepresentationofa0
timevalue.ECMAScript2015speciiesthat+0alwaysreturned.ThismeansthatforECMAScript2015thetimevalueofa
Dateobjectisneverobservably0andmethodsthatreturntimevaluesneverreturn0.

20.3.1.16:Ifatimezoneoffsetisnotpresent,thelocaltimezoneisused.Edition5.1incorrectlystatedthatamissingtime
zoneshouldbeinterpretedas"z".

20.3.4.36:IftheyearcannotberepresentedusingtheDateTimeStringFormatspeciiedin20.3.1.16aRangeErrorexception
isthrown.Previouseditionsdidnotspecifythebehaviourforthatcase.

20.3.4.41:PreviouseditionsdidnotspecifythevaluereturnedbyDate.prototype.toStringwhenthistimevalueisNaN.
ECMAScript2015speciiestheresulttobetheStringvalueis"InvalidDate".

21.2.3.1,21.2.3.2.4:AnyLineTerminatorcodepointsinthevalueofthesourcepropertyofanRegExpinstancemustbe
expressedusinganescapesequence.Edition5.1onlyrequiredtheescapingof"/".

21.2.5.6,21.2.5.8:Inpreviouseditions,thespeciicationsforString.prototype.matchandString.prototype.replace
wasincorrectforcaseswherethepatternargumentwasaRegExpvaluewhoseglobalislagset.Theprevious
speciicationsstatedthatforeachattempttomatchthepattern,iflastIndexdidnotchangeitshouldbeincrementedby1.
ThecorrectbehaviouristhatlastIndexshouldbeincrementedbyoneonlyifthepatternmatchedtheemptystring.

22.1.3.25,22.1.3.25.1:PreviouseditionsdidnotspecifyhowaNaNvaluereturnedbyacomparefnwasinterpretedby
Array.prototype.sort.ECMAScript2015speciiesthatsuchasvalueistreatedasif+0wasreturnedfromthecomparefn.
ECMAScript2015alsospeciiesthatToNumberisappliedtotheresultreturnedbyacomparefn.Inpreviouseditions,the
effectofacomparefnresultthatisnotaNumbervaluewasimplementationdependent.Inpractice,implementationscall
ToNumber.
AnnexE
AdditionsandChangesThatIntroduceIncompatibilities
withPriorEditions
(informative)
7.1.3.1:InECMAScript2015,ToNumberappliedtoaStringvaluenowrecognizesandconvertsBinaryIntegerLiteraland
OctalIntegerLiteralnumericstrings.InpreviouseditionssuchstringswereconvertedtoNaN.

6.2.3:InECMAScript2015,FunctioncallsarenotallowedtoreturnaReferencevalue.

11.6:InECMAScript2015,thevalidcodepointsforanIdentiierNamearespeciiedintermsoftheUnicodeproperties
ID_StartandID_Continue.Inpreviouseditions,thevalidIdentiierNameorIdentiiercodepointswerespeciiedby
enumeratingvariousUnicodecodepointcategories.

11.9.1:InECMAScript2015,AutomaticSemicolonInsertionaddsasemicolonattheendofadowhilestatementifthe
semicolonismissing.Thischangealignsthespeciicationwiththeactualbehaviourofmostexistingimplementations.

12.2.6.1:InECMAScript2015,itisnolongeranearlyerrortohaveduplicatepropertynamesinObjectInitializers.

12.15.1:InECMAScript2015,strictmodecodecontaininganassignmenttoanimmutablebindingsuchasthefunctionname
ofaFunctionExpressiondoesnotproduceanearlyerror.Insteaditproducesaruntimeerror.

13.2:InECMAScript2015,aStatementListbeginningwiththetokenletfollowedbytheinputelementsLineTerminatorthen
IdentiieristhestartofaLexicalDeclaration.Inpreviouseditions,automaticsemicoloninsertionwouldalwaysinserta
semicolonbeforetheIdentiierinputelement.

13.5:InECMAScript2015,aStatementListItembeginningwiththetokenletfollowedbythetoken[isthestartofa
LexicalDeclaration.InpreviouseditionssuchasequencewouldbethestartofanExpressionStatement.

13.6.7:InECMAScript2015,thenormalcompletionvalueofanIfStatementisneverthevalueempty.IfnoStatementpartis
evaluatedoriftheevaluatedStatementpartproducesanormalcompletionwhosevalueisempty,thecompletionvalueofthe
IfStatementisundeined.

13.7:InECMAScript2015,ifthe(tokenofaforstatementisimmediatelyfollowedbythetokensequencelet[thenthe
letistreatedasthestartofaLexicalDeclaration.Inpreviouseditionssuchatokensequencewouldbethestartofan
Expression.

13.7:InECMAScript2015,ifthe(tokenofaforinstatementisimmediatelyfollowedbythetokensequencelet[thenthe
letistreatedasthestartofaForDeclaration.Inpreviouseditionssuchatokensequencewouldbethestartofan
LeftHandSideExpression.

13.7:PriortoECMAScript2015,aninitializationexpressioncouldappearaspartoftheVariableDeclarationthatprecedesthe
inkeyword.Thevalueofthatexpressionwasalwaysdiscarded.InECMAScript2015,theForBindinginthatsameposition
doesnotallowtheoccurrenceofsuchaninitializer.

13.7:InECMAScript2015,thecompletionvalueofanIterationStatementisneverthevalueempty.IftheStatementpartofan
IterationStatementisnotevaluatedoriftheinalevaluationoftheStatementpartproducesacompletionwhosevalueis
empty,thecompletionvalueoftheIterationStatementisundeined.

13.11.7:InECMAScript2015,thenormalcompletionvalueofaWithStatementisneverthevalueempty.Ifevaluationofthe
StatementpartofaWithStatementproducesanormalcompletionwhosevalueisempty,thecompletionvalueofthe
WithStatementisundeined.
13.12.11:InECMAScript2015,thecompletionvalueofaSwitchStatementisneverthevalueempty.IftheCaseBlockpartofa
SwitchStatementproducesacompletionwhosevalueisempty,thecompletionvalueoftheSwitchStatementisundeined.

13.15:InECMAScript2015,itisanearlyerrorforaCatchclausetocontainavardeclarationforthesameIdentiierthat
appearsastheCatchclauseparameter.Inpreviouseditions,suchavariabledeclarationwouldbeinstantiatedinthe
enclosingvariableenvironmentbutthedeclaration'sInitializervaluewouldbeassignedtotheCatchparameter.

13.15,18.2.1.2:InECMAScript2015,aruntimeSyntaxErroristhrownifaCatchclauseevaluatesanonstrictdirecteval
whoseevalcodeincludesavarorFunctionDeclarationdeclarationthatbindsthesameIdentiierthatappearsasthe
Catchclauseparameter.

13.15.8:InECMAScript2015,thecompletionvalueofaTryStatementisneverthevalueempty.IftheBlockpartofa
TryStatementevaluatestoanormalcompletionwhosevalueisempty,thecompletionvalueoftheTryStatementis
undeined.IftheBlockpartofaTryStatementevaluatestoathrowcompletionandithasaCatchpartthatevaluatestoa
normalcompletionwhosevalueisempty,thecompletionvalueoftheTryStatementisundeinedifthereisnoFinallyclause
orifitsFinallyclauseevalulatestoanemptynormalcompletion.

14.3.9InECMAScript2015,thefunctionobjectsthatarecreatedasthevaluesofthe[[Get]]or[[Set]]attributeofaccessor
propertiesinanObjectLiteralarenotconstructorfunctionsandtheydonothaveaprototypeownproperty.Intheprevious
edition,theywereconstructorsandhadaprototypeproperty.

19.1.2.5:InECMAScript2015,iftheargumenttoObject.freezeisnotanobjectitistreatedasifitwasanonextensible
ordinaryobjectwithnoownproperties.Inthepreviousedition,anonobjectargumentalwayscausesaTypeErrortobe
thrown.

19.1.2.6:InECMAScript2015,iftheargumenttoObject.getOwnPropertyDescriptorisnotanobjectanattemptismade
tocoercetheargumentusingToObject.Ifthecoercionissuccessfultheresultisusedinplaceoftheoriginalargumentvalue.
Inthepreviousedition,anonobjectargumentalwayscausesaTypeErrortobethrown.

19.1.2.7:InECMAScript2015,iftheargumenttoObject.getOwnPropertyNamesisnotanobjectanattemptismadeto
coercetheargumentusingToObject.Ifthecoercionissuccessfultheresultisusedinplaceoftheoriginalargumentvalue.In
thepreviousedition,anonobjectargumentalwayscausesaTypeErrortobethrown.

19.1.2.9:InECMAScript2015,iftheargumenttoObject.getPrototypeOfisnotanobjectanattemptismadetocoercethe
argumentusingToObject.Ifthecoercionissuccessfultheresultisusedinplaceoftheoriginalargumentvalue.Inthe
previousedition,anonobjectargumentalwayscausesaTypeErrortobethrown.

19.1.2.11:InECMAScript2015,iftheargumenttoObject.isExtensibleisnotanobjectitistreatedasifitwasanon
extensibleordinaryobjectwithnoownproperties.Inthepreviousedition,anonobjectargumentalwayscausesa
TypeErrortobethrown.

19.1.2.12:InECMAScript2015,iftheargumenttoObject.isFrozenisnotanobjectitistreatedasifitwasanon
extensibleordinaryobjectwithnoownproperties.Inthepreviousedition,anonobjectargumentalwayscausesa
TypeErrortobethrown.

19.1.2.13:InECMAScript2015,iftheargumenttoObject.isSealedisnotanobjectitistreatedasifitwasanon
extensibleordinaryobjectwithnoownproperties.Inthepreviousedition,anonobjectargumentalwayscausesa
TypeErrortobethrown.

19.1.2.14:InECMAScript2015,iftheargumenttoObject.keysisnotanobjectanattemptismadetocoercetheargument
usingToObject.Ifthecoercionissuccessfultheresultisusedinplaceoftheoriginalargumentvalue.Inthepreviousedition,
anonobjectargumentalwayscausesaTypeErrortobethrown.

19.1.2.15:InECMAScript2015,iftheargumenttoObject.preventExtensionsisnotanobjectitistreatedasifitwasa
nonextensibleordinaryobjectwithnoownproperties.Inthepreviousedition,anonobjectargumentalwayscausesa
TypeErrortobethrown.
19.1.2.17:InECMAScript2015,iftheargumenttoObject.sealisnotanobjectitistreatedasifitwasanonextensible
ordinaryobjectwithnoownproperties.Inthepreviousedition,anonobjectargumentalwayscausesaTypeErrortobe
thrown.

19.2.3.2:InECMAScript2015,the[[Prototype]]internalslotofaboundfunctionissettothe[[GetPrototypeOf]]valueofits
targetfunction.Inthepreviousedition,[[Prototype]]wasalwayssetto%FunctionPrototype%.

19.2.4.1:InECMAScript2015,thelengthpropertyoffunctioninstancesisconigurable.Inpreviouseditionsitwasnon
conigurable.

19.5.6.2:InECMAScript2015,the[[Prototype]]internalslotofaNativeErrorconstructoristheErrorconstructor.Inprevious
editionsitwastheFunctionprototypeobject.

20.3.4InECMAScript2015,theDateprototypeobjectisnotaDateinstance.InpreviouseditionsitwasaDateinstance
whoseTimeValuewasNaN.

21.1.3.10InECMAScript2015,theString.prototype.localeComparefunctionmusttreatStringsthatarecanonically
equivalentaccordingtotheUnicodestandardasbeingidentical.Inpreviouseditionsimplementationswerepermittedto
ignorecanonicalequivalenceandcouldinsteaduseabitwisecomparison.

21.1.3.22and21.1.3.24InECMAScript2015,lowercase/upperconversionprocessingoperatesoncodepoints.Inprevious
editionssuchtheconversionprocessingwasonlyappliedtoindividualcodeunits.Theonlyaffectedcodepointsarethosein
theDeseretblockofUnicode

21.1.3.25InECMAScript2015,theString.prototype.trimmethodisdeinedtorecognizewhitespacecodepointsthat
mayexistsoutsideoftheUnicodeBMP.However,asofUnicode7nosuchcodepointsaredeined.Inpreviouseditionssuch
codepointswouldnothavebeenrecognizedaswhitespace.

21.2.3.1InECMAScript2015,IfthepatternargumentisaRegExpinstanceandthelagsargumentisnotundeined,anew
RegExpinstanceiscreatedjustlikepatternexceptthatpattern'slagsarereplacedbytheargumentlags.Inprevious
editionsaTypeErrorexceptionwasthrownwhenpatternwasaRegExpinstanceandlagswasnotundeined.

21.2.5InECMAScript2015,theRegExpprototypeobjectisnotaRegExpinstance.InpreviouseditionsitwasaRegExp
instancewhosepatternistheemptystring.

21.2.5InECMAScript2015,source,global,ignoreCase,andmultilineareaccessorpropertiesdeinedontheRegExp
prototypeobject.InpreviouseditionstheyweredatapropertiesdeinedonRegExpinstances
AnnexF
Bibliography
(informative)
1.IEEEStd7542008:IEEEStandardforFloatingPointArithmetic.InstituteofElectricalandElectronicEngineers,New
York(2008)
2.TheUnicodeStandard,Version8.0.0orsuccessor.
<http://www.unicode.org/versions/latest>
3.UnicodeStandardAnnex#15,UnicodeNormalizationForms,versionUnicode8.0.0,orsuccessor.
<http://www.unicode.org/reports/tr15/>
4.UnicodeStandardAnnex#31,UnicodeIdentiiersandPatternSyntax,versionUnicode8.0.0,orsuccessor.
<http://www.unicode.org/reports/tr31/>
5.UnicodeTechnicalNote#5:CanonicalEquivalenceinApplications,availableat<http://www.unicode.org/notes/tn5/>
6.UnicodeTechnicalStandard#10:UnicodeCollationAlgorithmversion8.0.0,orsuccessor,availableat
<http://www.unicode.org/reports/tr10/>
7.IANATimeZoneDatabaseat<http://www.iana.org/timezones>
8.ISO8601:2004(E)DataelementsandinterchangeformatsInformationinterchangeRepresentationofdatesand
times
9.RFC1738UniformResourceLocators(URL),availableat<http://tools.ietf.org/html/rfc1738>
10.RFC2396UniformResourceIdentiiers(URI):GenericSyntax,availableat<http://tools.ietf.org/html/rfc2396>
11.RFC3629UTF8,atransformationformatofISO10646,availableat<http://tools.ietf.org/html/rfc3629>
AnnexG
Copyright&SoftwareLicense
(informative)
EcmaInternational

RueduRhone114

CH1204Geneva

Tel:+41228496000

Fax:+41228496001

Web:http://www.ecmainternational.org

CopyrightNotice
2016EcmaInternational

Thisdraftdocumentmaybecopiedandfurnishedtoothers,andderivativeworksthatcommentonorotherwiseexplainitor
assistinitsimplementationmaybeprepared,copied,published,anddistributed,inwholeorinpart,withoutrestrictionof
anykind,providedthattheabovecopyrightnoticeandthissectionareincludedonallsuchcopiesandderivativeworks.
However,thisdocumentitselfmaynotbemodiiedinanyway,includingbyremovingthecopyrightnoticeorreferencesto
EcmaInternational,exceptasneededforthepurposeofdevelopinganydocumentordeliverableproducedbyEcma
International.

Thisdisclaimerisvalidonlypriortoinalversionofthisdocument.Afterapprovalallrightsonthestandardarereservedby
EcmaInternational.

ThelimitedpermissionsaregrantedthroughthestandardizationphaseandwillnotberevokedbyEcmaInternationalorits
successorsorassignsduringthistime.

Thisdocumentandtheinformationcontainedhereinisprovidedonan"ASIS"basisandECMAINTERNATIONALDISCLAIMS
ALLWARRANTIES,EXPRESSORIMPLIED,INCLUDINGBUTNOTLIMITEDTOANYWARRANTYTHATTHEUSEOFTHE
INFORMATIONHEREINWILLNOTINFRINGEANYOWNERSHIPRIGHTSORANYIMPLIEDWARRANTIESOF
MERCHANTABILITYORFITNESSFORAPARTICULARPURPOSE.

SoftwareLicense
AllSoftwarecontainedinthisdocument("Software")isprotectedbycopyrightandisbeingmadeavailableunderthe"BSD
License",includedbelow.ThisSoftwaremaybesubjecttothirdpartyrights(rightsfrompartiesotherthanEcma
International),includingpatentrights,andnolicensesundersuchthirdpartyrightsaregrantedunderthislicenseevenifthe
thirdpartyconcernedisamemberofEcmaInternational.SEETHEECMACODEOFCONDUCTINPATENTMATTERS
AVAILABLEAThttp://www.ecmainternational.org/memento/codeofconduct.htmFORINFORMATIONREGARDINGTHE
LICENSINGOFPATENTCLAIMSTHATAREREQUIREDTOIMPLEMENTECMAINTERNATIONALSTANDARDS.

Redistributionanduseinsourceandbinaryforms,withorwithoutmodiication,arepermittedprovidedthatthefollowing
conditionsaremet:

1.Redistributionsofsourcecodemustretaintheabovecopyrightnotice,thislistofconditionsandthefollowing
disclaimer.
2.Redistributionsinbinaryformmustreproducetheabovecopyrightnotice,thislistofconditionsandthefollowing
disclaimerinthedocumentationand/orothermaterialsprovidedwiththedistribution.
3.NeitherthenameoftheauthorsnorEcmaInternationalmaybeusedtoendorseorpromoteproductsderivedfromthis
softwarewithoutspeciicpriorwrittenpermission.

THISSOFTWAREISPROVIDEDBYTHEECMAINTERNATIONAL"ASIS"ANDANYEXPRESSORIMPLIEDWARRANTIES,
INCLUDING,BUTNOTLIMITEDTO,THEIMPLIEDWARRANTIESOFMERCHANTABILITYANDFITNESSFORAPARTICULAR
PURPOSEAREDISCLAIMED.INNOEVENTSHALLECMAINTERNATIONALBELIABLEFORANYDIRECT,INDIRECT,
INCIDENTAL,SPECIAL,EXEMPLARY,ORCONSEQUENTIALDAMAGES(INCLUDING,BUTNOTLIMITEDTO,PROCUREMENT
OFSUBSTITUTEGOODSORSERVICES;LOSSOFUSE,DATA,ORPROFITS;ORBUSINESSINTERRUPTION)HOWEVERCAUSED
ANDONANYTHEORYOFLIABILITY,WHETHERINCONTRACT,STRICTLIABILITY,ORTORT(INCLUDINGNEGLIGENCEOR
OTHERWISE)ARISINGINANYWAYOUTOFTHEUSEOFTHISSOFTWARE,EVENIFADVISEDOFTHEPOSSIBILITYOFSUCH
DAMAGE.

You might also like