该规范是 ECMAScript 规范的中文翻译。当前版本对应 0d37f42 版本,我们的愿景是对该规范中文版本提供长期维护。目前翻译进度到第七章,有大量的 Pull Requests 需要校对,也希望有兴趣各路大神可参与该翻译的校对和审校工作。以下是一些参与贡献的渠道。
此标准定义了 ECMAScript 2018 语言,是 ECMAScript 语言规范的第九版。自从 1997 年第一版发布以来,ECMAScript 已经成为世界上应用最广泛的编程语言之一。他最为认知的是作为嵌入在 Web 浏览器中的语言,但也被广泛应用于服务器和嵌入式应用程序。
ECMAScript 基于几种始发技术,最著名的是 Netscape 的 JavaScript 以及 Microsoft 的 JScript。该语言由 Netscape 的 Brendan Eich 发明,并首次出现在该公司的 Navigator2.0 浏览器中。它已经出现在 Netscape 的所有后续浏览器以及 Microsoft 自 Internet Explorer3.0 开始的所有浏览器中。
ECMAScript 语言规范的制定始于 1996 年 11 月。第一版的Ecma标准在 1997 年 6 月通过 Ecma 联合大会。
该(第一版) Ecma 标准为了采用快速通道通过,被提交给 ISO/IEC JIC 1,于 1998 年 4 月被批准为国际标准 ISO/IEC16262。在 1998 年 Ecma 联合大会通过了第二版 ECMA-262,以保证完全符合 ISO/IEC 16262。第一版和第二版的变化是编辑层面的。
第三版标准引入了强大的正则表达式,更好的字符串处理,新的控制语句,try/catch 异常处理,更严格的错误定义,数字输出的格式化以及预期未来语言发展的微小变化。第三版 ECMAScript 标准于1999年12月被 Ecma 联合大会采纳,于 2002 年 6 月作为 ISO/IEC 16262:2002 发布。
在第三版发布后,ECMAScript 在万维网上被大量使用,它成为所有Web浏览器支持的编程语言。为了开发第四版 ECMAScript,做了大量有意义的工作,然而这项工作未能完成,也没能作为第四版 ECMAScript 发布,不过其中一些被纳入第六版开发(工作)中。
第五版 ECMAScript(以 ECMA-262 5th 版本发布)为那些已经被浏览器广泛实现的语言规范编纂了实质的解释,同时增加了对第三版发布以来出现的新功能的支持。 这些功能包括
第五版为了采用快速通道通过,被提交给 ISO/IEC JIC 1,被批准为国际标准 ISO/IEC 16262:2011。第 5.1 版 ECMAScript 标准包含较少的更正,并与 ISO/IEC 16262:2011 保持一致。于2011年6月 Ecma 联合大会被采纳。
第六版于 2009 年开始作为重点开发,当时第五版正在准备出版。然而,这之前的重点实验以及语言增强设计工作可以追溯到 1999 年第三版发布。实际上,第六版的完成是十五年努力的结果。 这个版本中增加了包括对大型应用程序,库创建, 以及以 ECMAScript 作为其他语言的编译目标提供更好的支持。其中主要的增强功能包括模块化,类声明,词法块作用域,迭代器以及生成器,异步编程的promise,解构模式,以及正确的尾部调用。 ECMAScript内置库扩展支持了额外的数据抽象,包括Map,Set,二进制值的数组, 同时也支持Unicode补充字符在字符串及正则表达式中使用。内置库也通过子类进行了扩展。第六版为正则,渐进式语言以及库增强提供了基础。第六版于 2015 年 6 月被Ecma联合大会采纳。
ECMAScript2016使用 Ecma TC39 委员会新的年度发布策略以及公开开发流程的首个 ECMAScript 版本。从 ECMAScript2015 源文档作为基础构建一个纯文本的源文档,以支持完全在 GitHub 上进一步开发。在这个标准的发展的这一年,数百个pull requests和issues被提交,代表着成千上万的错误修复,编辑修复和其他改进。另外,许多软件工具被开发用来帮助这一工作,包括Ecmarkup,Ecmarkdown和Grammarkdown。ES2016还包括支持一个新的求幂运算符,以及为 Array.prototype 添加了一个名为include的新方法。
ECMAScript 2017 的规范引入了Async函数,共享内存, 以及更小语言和库增强的原子,错误修复,编辑更新。Async函数通过提供promise-returning函数语法来提高异步编程体验。共享内存和原子引入了一种新的内存模型,允许多个代理程序使用原子操作进行通信,以确保即便在并行 CPU 上程序也能有明确定义的执行顺序。此规范还包括 Object 新的静态方法:Object.values,Object.entries和Object.getOwnPropertyDescriptors。
本规范,第 9 版本通过引入异步迭代器协议和异步生成器支持异步迭代。该规范还包括四个新的正则表达式特性:dotAll 标志、命名的捕获组、Unicode 属性转义和后视断言。还包括REST参数和扩展运算符支持对象属性。也有许多小的更新,编辑和规范,贡献来自我们的社区。
许多个人和组织在 Ecma TC39 为当前版本以及以前的版本做出了非常重要的贡献。此外,有了一个充满活力的社区支持 TC39 为 ECMAScript 所做的努力。这个社区审查了许多草案,提交了大量的错误报告,执行实施实验,提供测试套件,全世界的 ECMAScript 的开发者都可以从中受益。然而遗憾的是,不能一一鸣谢为此做出贡献的每个人和组织。
Allen Wirfs-Brock
ECMA-262, 6th版本 项目编辑
Brian Terlson
ECMA-262, 7th版本 项目编辑
本标准定义了ECMAScript 2018通用编程语言。
一个符合ECMAScript标准的实现应该符合以下提议:
必须提供和支持本规范中描述的所有的类型,值,对象,属性,函数以及程序语法及语义。
解释源文本的输入必须与最新版本的Unicode标准和ISO/IEC 10646标准保持一致。
提供的应用程序接口的程序,需要适应使用不同自然语言的国家的语言和文化习惯,且最新版本的ECMA-402的实现必须与本规范的接口兼容。
应该提供那些超出该规范描述的额外类型,值,对象,属性以及方法。尤其对于该文档有提到但没描述其属性的那些对象,应该提供那些属性以及属性对应的值。
应该支持一些没有在规范中提及的程序或者正则表达式语法。尤其应该实现在
绝对不能实现在
为了实现符合本规范的应用程序,下列引用文档是不可或缺的。对于标注了日期的文档,仅适用标注的那个版本。 对于未标注日期的文档,以文档的最新版为准(包括任何修订版)。
ISO/IEC 10646:2003: 信息技术 –通用多八位编码字符集(UCS)以及修订 1:2005, 修订 2:2006, 修订 3:2008, 和修订 4:2008, 以及其他修订,更正,后继标准
ECMA-402, ECMAScript 2015 国际化API规范.
http://www.ecma-international.org/publications/standards/Ecma-402.htm
ECMA-404, JSON 数据交换格式化.
http://www.ecma-international.org/publications/standards/Ecma-404.htm
本节包含对 ECMAScript 语言非规范性的概述。
ECMAScript 是一门在宿主环境执行计算以及操作可计算对象的面向对象编程语言。这里定义的ECMAScript并不打算有自给自足的计算;事实上,该规范并没有规定外部数据的输入或者计算结果的输出。相反,我们期望 ECMAScript 程序的计算环境不仅提供本规范中描述的对象和能力,还包括特定的环境对象,本规范除了说明这些对象应该提供可被 ECMAScript 程序访问的某些属性,调用的某些方法外,关于它的其他描述和行为不在本规范涉及的范围。
ECMAScript 最初被设计为一门脚本语言,但是现在已经作为一门通用的编程语言被广泛应用。脚本语言是指一种用于操作,定制,自动化现有系统能力的编程语言。在这样的系统中,通过用户界面已经可以使用有用的功能,而脚本语言是将这些功能暴露给程序控制的机制。 通过这种方式,现有的系统被称为提供对象和能力的宿主环境,从而完成了脚本语言的功能。 脚本语言是供专业和非专业程序员使用的。
ECMAScript 最初被设计为 Web 脚本语言,提供了一种让网页更加富有生机的机制,并能够进行部分基于Web B/S架构的服务器端计算。ECMAScript 现在被用于在多种宿主中提供核心脚本能力。因此该文档描述的是除特定宿主环境外的语言核心。
ECMAScript 用法已经远超出了简单脚本,现在被用于很多不同的环境和规模的全方位编程任务。随着 ECMAScript 使用范围的扩大使,其功能和能力也得到了扩展。ECMAScript 现在成为了一个功能齐全的通用编程语言。
ECMAScript 的一些能力类似于其他编程语言中,特别是 C, Java™, Self, 如以及下所述的 Scheme:
ISO/IEC 9899:1996, Programming Languages – C.
Gosling, James, Bill Joy and Guy Steele. The Java™ Language Specification. Addison Wesley Publishing Co., 1996.
Ungar, David, and Smith, Randall B. Self: The Power of Simplicity. OOPSLA '87 Conference Proceedings, pp. 227-241,Orlando, FL, October 1987.
IEEE Standard for the Scheme Programming Language. IEEE Std 1178-1990.
web 浏览器提供用于客户端计算的 ECMAScript 宿主环境,包括如代表窗口,菜单,弹出窗口,对话框,文本域,锚点,框架,历史记录,cookies以及输入/输出的实例对象。此外,宿主环境还提供了脚本代码处理如焦点改变、页面和图片的加载、卸载、错误和中断,选择,表单提交和鼠标交互等等事件的能力。通过 HTML 中的脚本代码组合用户接口元素,固定及计算文本,图片来显示页面。脚本代码不需要一个主程序即可对用户交互进行响应。
WEB 服务器提供一个不同于客户端的如代表请求,客户端,文件等的对象,以及数据锁定和分享的机制。为基于 Web 的应用程序提供一个定制的用户界面,通过浏览器端脚本及服务端脚本的配合使用,可以在客户端和服务端之间进行分布式计算。
支持 ECMAScript 的 WEB 浏览器和服务器都将它们自身的宿主环境作为 ECMAScript 的补充,以使得 ECMAScript 的执行环境变得完整。
以下是 ECMAScript— 的非正式概述 —— 描述的只是该语言的一部分。这个概述不是标准的一部分。
ECMAScript 是基于对象的:基础语言以及主要能力都是通过对象提供,一个 ECMAScript 程序是一组可通信对象。在 ECMAScript 中,一个对象是零个或多个属性的的集合。每个属性都有确定其如何被使用的特性, 如当一个属性的 Writable 特性设置为
ECMAScript 定义了一组内置对象,从而勾勒出 ECMAScript 实体的定义。这些内置对象包括全局对象;基本的语言Object, Function, Boolean, Symbol,各种 Error 对象;代表和操作的数值对象,包括 Math, Number, Date;文本处理对象,String,RegExp;索引值集合的 Array 对象,以及九种值具有特定数字数据表示的 Typed Array 对象;泛型对象 Map, Set;支持结构化数据的 JSON, ArrayBuffer, SharedArrayBuffer,DataView 等对象;支持控制抽象的 generator 函数,Promise 对象;以及反射对象 Proxy,Reflect。
ECMAScript 还定义了一组内置运算符。ECMAScript 运算符包括各种一元运算,乘法运算符,加法运算符,位移运算符,关系运算符,等式运算符,二进制运算符,二进制逻辑运算符,赋值运算符和逗号运算符。
大型 ECMAScript 程序通过模块被支持,其允许程序可以被分化为多个语句和定义序列。每个模块明确地标识它所使用的其他模块提供的声明,哪些声明可供其他模块使用。
ECMAScript 语法有意地类似于 Java 语法。ECMAScript 语法是松散的,使其能够成为易于使用的脚本语言。例如,一个变量不需要声明其具体类型,也不需要与声明相关联属性类型,在调用定义的函数之前也不需要以文本方式显示的声明。
尽管 ECMAScript 包含了定义类的语法,但是 ECMAScript 对象从根本上来说并不是像 C++,Smalltalk,Java 那样基于类的。相反,对象可以通过各种方式创建,包括字面符号,或通过"prototype" 的属性的函数,此属性用于实现基于原型的继承 和共享属性。new Date(2009, 11) 创建一个新 Date 对象。不使用new调用一个Date()产生一个表示当前日期时间的字符串,而不是一个对象。
每个由"prototype" 属性值。再者,一个原型可能有一个非空隐式引用链接到它的原型,以此类推,这叫做原型链。当向对象的一个属性提出引用时,引用会指向原型链中包含此属性名的第一个对象的属性。换句话说,首先检查直接提及的对象的同名属性,如果对象包含同名的属性,引用即指向此属性,如果该对象不包含同名的属性,则下一步检查对象的原型;以此类推。
一般情况下基于类的面向对象语言的实例拥有状态,类拥有方法,并且只能继承结构和行为。在 ECMAScript 中,对象拥有状态和方法,并且结构,行为,状态全都可继承。
所有不直接包含特定属性的对象会共享他们原型中包含的此属性及属性值。图 1 说明了这一点:
CF 是一个new 表达式创建: cf1, cf2, cf3, cf4, cf5。每个对象都有名为 q1 和 q2 的属性。虚线表示隐式原型关系;例如:cf3 的原型是 CFp。P1 和 P2 的两个属性, 这对 CFp,cf1, cf2, cf3, cf4, cf5 是不可见的。CFp 的名为 CFP1 的属性共享给 cf1, cf2,cf3, cf4, 以及 cf5 ( 没有CF), 以及在 CFp 的隐式原型链中找不到任何名为 q1, q2,或 CFP1 的属性。请注意,CF 和 CFp 之间没有隐式原型链接。
不同于基于类的对象语言,属性可以通过赋值的方式动态添加给对象。也就是说,
尽管 ECMAScript 对象本质上不是基于类,但是基于构造函数,原型对象和方法通用模式来实现类似于类的抽象是很方便的。ECMAScript 内置对象本身即遵循这样的类模式。从 ECMAScript 2015 开始,ECMAScript 语言包含了类定义语法,允许程序员像内置对象那样简洁的定义对象。
ECMAScript 语言认识到有的开发者可能希望限制使用语言中的新特性。他们这样做可能是为了安全考虑,避免他们认为是容易出错的功能,获得增强的错误检查,或其他原因。因此,ECMAScript 中定义了语言的严格变体。语言的严格变体,排除了 ECMAScript 语言的某些特定的语法和语义特征,还修改了某些功能的详细语义。严格变体还指定了必须抛出错误异常报告的额外错误条件,即使在非严格的语言形式下这些条件不属于错误。
ECMAScript 的严格变体通常被称为语言的严格模式。严格模式选择和使用明确地适用于独特 ECMAScript 代码单元级别的,ECMAScript 严格模式语法和语义。由于语法代码单元级别的严格模式被选择,严格模式仅在这个代码单元内施加有局部效果的限制。严格模式不限制或修改任何层面的 ECMAScript 语义,必须一致地操作跨多个代码单元。一个 ECMAScript 程序可同时包含严格模式和非严格模式的代码单元。在这种情况下,严格的模式只适用于严格模式代码单元内实际执行的代码。
要符合这一规范,ECMAScript 的实现必须同时实现未限制的 ECMAScript 语言和按照这个规范定义的 ECMAScript 的严格模式变体。此外,实现还必须支持未限制的和严格模式代码单元的在同一个程序中混用。
本文档将使用下列术语和定义。
在本规范
指在
一个原始值直接代表语言实现的最低层次的数据
Object 类型的成员
对象是属性的集合,并且具有单个原型对象。原型可能是空值。
创建和初始化对象的
prototype 属性值是用来实现继承和共享的一个原型对象。
为其他对象提供共享属性的对象
默认行为拥有如那些所有对象都必须支持的内部方法的对象
默认行为缺少一个或多个必要内部方法的对象
任何对象不是
其语义由本规范定义的对象
ECMAScript 实现指定和提供的对象
一个在变量没有被赋值时就被使用的原始值
值只有
表示故意缺省任何对象值的原始值
值只有
Boolean 类型的成员
只有两个值,
由原始值
标准内置构造函数
通过使用 new 表达式,以一个 Boolean 值作为参数调用 Boolean
由零个或多个16位无符号整数组成的有限有序序列原始值
一个 String 值是 String 类型的成员。通常序列中的每个整数值代表 UTF-16 文本的单个 16 位单元。然而,对于其值,ECMAScript 只要求必须是 16 位无符号整数,除此之外没有任何限制或要求。
所有可能的 String 值的集合
标准内置String 实例,Object 类型成员之一
IEEE 754-2008 格式的 64 位双精度二进制的原始值
一个数字值是数字类型的成员,直接代表一个数字。
所有可能的 Number 值的集合,包括特殊 “Not-a-Number” (NaN) 值, 正无穷, 负无穷
标准内置Number 的一个实例,Object 类型成员之一
正无穷数值
值 IEEE 754-2008 “Not-a-Number” 的数值
表示一个唯一的,非字符串的属性键对象的原始值
所有可能的 Symbol 值集合
标准内置Symbol 的一个实例,Object 类型成员之一
可作为子程序调用的 Object 类型成员之一
函数除了其属性,还包含可执行代码、状态,用来确定被调用时的行为。函数的代码不限于 ECMAScript。
作为函数的内置对象
如 parseInt 和 Math.exp 就是内置函数。一个实现可以提供本规范没有描述的依赖于实现的内置函数。
将一个键(一个 String 值或 Symbor 值)和值相关联的对象的一部分
属性可能根据属性值的不同表现为直接的数据值(原始值,对象,或一个
作为属性值的函数
当一个函数被作为一个对象的方法调用,此对象将作为
作为内置函数的方法
标准内置方法由本规范定义,ECMAScript 实现可指定,提供其他额外的内置方法。
定义一个属性的一些特性的内部值
对象直接拥有的属性
不是对象的自身属性,但是是对象原型的属性(原型的自身属性或继承属性)
本规范的剩余部分章节组织如下:
第 5 章定义了在本规范中使用的一些符号或者语法的约定。
第 6-9 章定义了 ECMAScript 程序操作包含的执行环境。
第 10-16 章定义了实际的 ECMAScript 语言,包括它的语法编码以及语言特性的执行语义。
第 17-26 章定义了 ECMAScript 标准库。它们包括所有当 ECMAScript 程序执行时可用的标准对象的定义。
第 27 章描述了访问备用数组缓冲区内存和原子对象的内存一致性模型。
上下文无关文法由多个产生式组成。每个产生式左侧有一个称为非终结符的抽象符号的左值,右侧有一个或多个非终结符和终结符号组成的序列的右值。任何文法,它的终结符都来自指定的字母集。
一个产生式链是一个只含有一个非终结符以及 0 个或多个终结符作为其右值的产生式。
句子中单一可区分的非终结符——目标符,给定一个语言上下文无关文法。换句话说,重复用产生式右值替换序列中任何左值为非终结符所组成的终结符序列集合(可能是无限个)。
ECMAScript 词法文法在
空白和注释之外的输入元素构成 ECMAScript 语法文法的终结符,它们被称为 ECMAScript tokens。这些 tokens 是,ECMAScript 语言的保留字,标识符,字面量,标点符号。此外,行结束符虽然不被视为 tokens,但会成为输入元素流的一部分,用于引导处理自动插入分号(/*…*/ 的注释,不管是否跨越多行)不包含行结束符也会直接地丢弃,但如果一个
两个冒号 "::" 作为分隔符分割词法和正则的文法产生式。词法和正则的文法共享某些产生式。
用于转换字符串为数字值的一种文法。此文法与数字字面量词法文法的一部分类似,并且有终结符
三个冒号 ":::" 作为分隔符分割数字字符串文法的产生式。
第 11,12,13,14,15 章给出了 ECMAScript 的语法文法。词法文法定义的 ECMAScript tokens 是此文法的终结符(
当一个码点流解析成一个 ECMAScript 的
当一个解析成功的时候,它会构造一颗解析树,一颗根树结构是它的每个节点都是一个 Parse Node。每个 Parse Node 都是文法中的一个符号的一个实例。它代表了从这样的符号中派生出来的源代码文本的一个跨度。解析树的根节点代表着整个的源代码文本,是解析的
新的 Parse Nodes 在每次调用解析器时都会被重新实例化,也就是说解析相同源文本也永远不会重用。当且仅当它们表示相同的源文本范围,是相同语法符号的实例,并且是由调用相同的解析器产生的解析节点时被认为是相同的 Parse Node
多次解析同一字符串会得到不同的 Parse Nodes,例如:
eval(str); eval(str);
只用一个冒号 “:” 作为分隔符分割语法词法的产生式。
语法文法在条款 12,13,14,15 中提出。但是对于哪些 token 序列是正确被 ECMAScript
在某些情况下,为了避免歧义,语法文法使用广义的产生式,允许 token 序列形成一个不合法的 ECMAScript
不管是在文法的产生式,还是在本规范中,词法文法,正则文法以及数字字符串文法的终结符都用等宽字体展示。这些将以的脚本形式出现。所有通过这种方式指定的终结符码点都被当作合适的基本拉丁语 Unicode 码点理解,而不是来自其他任何类似 Unicode 范围的码点。
非终结符以斜体显示。非终结符(也叫产生式)的定义由非终结符名称和其后定义的一个或多个冒号给出。(冒号的数量表示产生式所属的文法。)非终结符的一个或多个替代右值紧跟在下一行。例如,语法定义:
表示这个非终结符 while token,其后跟左括号 token,其后跟 token,其后跟
表示这个
终结符或非终结符可能会出现后缀下标 “opt”,表示它是可选符号。包含可选符号实际指定了包含两个右值,一个是省略可选元素的,另一个是包含可选元素的。这意味着:
是以下的一种简便的缩写:
以及:
是以下的一种简便的缩写:
也是下面的一种缩写:
所以在这个例子中,非终结符
产生式可以通过形如 “[parameters]” 这样的下标注释被参数化,会以后缀的形式出现在产生式定义的非终结符中。“parameters” 可以是单独的名称,也可以是一个逗号分隔的名称列表。被参数化的产生式是一系列定义参数名称以下划线开头,追加到参数化的非终结符后面的所有组合的产生式的缩写。这就意味着:
是下面的缩写:
以及:
是下面的缩写:
多个参数产生数个产生式的组合,在一个完整语法中不必引用所有。
对生产式的非终结符右值的引用也可以被参数化,例如:
是下面的缩写:
又如:
是下面的缩写:
非终结符引用可能同时具有参数列表和一个 “opt” 后缀。例如:
是下面的缩写:
在右侧非终结符引用参数名称前置以 “?”,使该参数值取决于当前产生式的左侧符号引用的参数名称是否出现。例如:
是下面的缩写:
如果右值选择是以 “[+parameter]” 作为前缀,则表示选择只有命名参数用于引用产生式的非终结符时可用。如果右值选择是以 “[~parameter]” 作为前缀,则表示选择只有命名参数不是用于引用产生式的非终结符时可用。这意味着:
是下面的缩写:
另外一个例子:
是下面的缩写:
在文法定义中当单词 “one of” 跟随一个或多个分号后的时候,表示随后的一行或多行的终结符是一个可选的定义。例如,ECMAScript的词法文法包含下列的产生式:
它仅仅是下面的缩写:
如果 “[empty]” 出现在一个产生式的右值,它暗示着这个产生式的右值不包含终结符或者非终结符。
如果 “[lookahead ∉ set]” 出现在一个产生式的右值,它暗示着如果随后立即的输入的token序列是给出的集合(set)的成员,那么这个产生式也许不会被使用。这个集合可以用一个逗号分割的由一到两个被花括号包裹的元素终结序列的列表表示。为了方便,这个集合也可以用非终结符表示,在这种情况下,它代表所有能由非终结符展开得到的终结符的集合。如果这个集合包含一个单独的终结符,那么短语 “[lookahead ≠ terminal]” 也许会被使用。
例如,给出定义:
则定义:
能匹配字母 n 后跟随由偶数起始的一个或多个十进制数字,或一个十进制数字后面跟随一个非十进制数字。
类似的,如果产生式的右值出现 “[lookahead ∈ set]”,则表示产生式只有在随后立即的输入的token序列是给出的集合(set)的成员才能使用。如果集合只包含一个单一的终结符,则可以使用 “[lookahead == terminal]”。
如果产生式的右侧出现 “[no
如果一个 throw token 和
除非通过一个受限的产生式禁止一个
当一个词法文法或者数字字符串文法的产生式中可选部分出现多码点的 token 时,意味着码点序列将会组成一个 token。
一个产生式的右值也许会通过 “but not” 指定某些不被允许的扩展,然后暗示这个扩展将是被排除在外的。例如,产生式:
意味着非终结符
最后,一些非终结符通过 sans-serif 字体书写的描述性的短语来描述, 在这样的案例中,列出所有的可选部分是不切实际的。
此规范通常使用带编号的列表来指定算法的步骤。这些算法是用来精确地指定 ECMAScript 语言结构所需的语义。该算法无意暗示任何具体实现使用的技术。在实践中,也许可用更有效的算法实现一个给定功能。
算法可能被显式参数化,在这种情况下,参数名和用法必须作为算法定义的一部分提供。
算法步骤可以细分为多个连续的子步骤。子步骤需要用缩进表示,可以进一步被划分成缩进的子步骤。大纲编号约定用作标识子步骤,第一级子步骤使用小写字母字符标记,第二级小步骤用小写罗马数字标记。如果步骤超过三级,那么这些规则从第四级开始从数字重复进行标记。例如:
一个步骤或者子步骤也许会使用 “if” 去断言它的子步骤的条件。在这样的案例中,这些子步骤只能适用于 “if” 断言为真的情况。如果一个步骤或者子步骤以 “else” 开始,那么表示这是之前的 “if” 断言的同一级的否定断言。
一个步骤也许会指定它的子步骤的迭代程序。
一个以 “Assert:” 开头的步骤断言一个它的算法里不变的条件。这样的断言被用作使算法不变量显式地展示,否则它将是隐式的。这样的断言不增加额外的语义需求,因此实现不必检查。它们被使用只是为了使算法更清晰。
对于任意形如 “Let x be someValue” 的值,算法步骤也许会声明命名别名。这些别名都是类似类型的,即 x 和 someValue 指向同样的基础数据,对它们的修改是互相可见的。那些想避免这样的类似引用的算法步骤需要显式地复制一份右值:即 “Let_x_ be a copy of someValue” 创建了一个 someValue 的浅复制。
一旦声明完毕,别名可以在任何后续步骤中引用,而不能在别名声明前的步骤中使用。别名也许会通过形如 “Set x to someOtherValue” 这样的形式被修改。
为了便于它们在本规范的多个地方使用,一些算法,我们称之为抽象操作,以参数化函数形式命名和书写,以便它们能够在其它算法中通过名称来引用。抽象操作通常使用函数应用风格被引用,如 OperationName(arg1, arg2)。一些抽象操作被当作像类规范里抽象的多态发送一样。这样的类似类的方法抽象操作通常通过一个方法应用风格被引用,如 someValue.OperationName(arg1, arg2)。
一个语法导向操作是一个具名操作,它的定义包含了一系列算法,每个算法与一个或者多个 ECMAScript 文法的产生式相关联。一个有多个可选定义的产生式通常对于每个可选部分都有一个独立的算法。当一个算法与一个文法产生式相关联的时候,它也许会引用这个产生式可选部分的终结符或者非终结符,就好像它们是这个算法的参数一样。当出现这种情况时,非终结符指向实际的源代码中与之匹配的可选部分的定义。
当一个算法与一个产生式的可选部分关联的时候,这个可选部分通常不会带上 “[ ]” 文法注释。这样的注释只应该影响可选部分的语法识别,不应该对相关的可选部分的语义有影响。
语法导向操作同一个解析节点一起被调用,还可以在以下算法步骤 1,3,4 中使用这个约定的其它参数:
"value" as the argument.除非另有明确说明,否则,所有相关联的产生式对于每个也许会被应用到这个产生式左值的非终结符的操作都有一个隐式的定义。如果存在的话,这个隐式的定义简单地再次对同样的参数运用这个相同的定义,对于这些相关联的产生式唯一的右值非终结符,随后返回处理结果。例如,假设一些算法有如下形式的步骤: “Return the result of evaluating
但是解析操作并没有关联这个产生式的算法。那么在这样的案例中,解析操作隐式地包含了下面形式的关联:
必须在运行时被调用的指定语义的算法就叫运行时语义。 运行时语义通过
本规范的算法常常隐式地返回一个 [[Type]] 值为
"Infinity".与下面的是同一个含义:
"Infinity").然而,如果一个 “return” 语句的值表达式是一个
一个在算法步骤中没有值的 “return” 语句与下面的是同样的意思:
undefined).对于任意的在一个上下文中没有显示地需要一个完整的
描述抛出一个异常的算法步骤,例如:
TypeError exception.与下面的是同一个含义:
算法步骤说明或者等同于:
意思就是:
算法步骤说明或者等同于:
与下面的是同一个含义:
这里的 hygienicTemp 是临时的,并且只在 ReturnIfAbrupt 有关的步骤中中可见。
算法步骤说明或者等同于:
与下面的是同一个含义:
对? 为前缀的指定语法操作的调用暗示着
等价于下面的步骤:
相似的,对于程序方法的风格,步骤:
等价于:
相似的,前缀 ! 被用作暗示下列的对于抽象或者指定语法操作的调用将不会返回一个打断的完成值, 并且作为结果的
等价于下面的步骤:
对于! 或者 ? 来利用这个缩写。
上下文无关文法不能足够好的去表达所有定义的规则,不管是一个输入元素的流形成的一个合法的将被解析的 ECMAScript
静态语义规则拥有名称,并且通常用一个算法来定义。具有名称的静态语义规则与文法产生式相关联,对于每个可采用的具有名称的静态语义规则, 一个包含多个可选部分定义的产生式通常会对每个可选部分定义一个独有的算法。
除非在本规范中其它指定的文法产生式可选部分隐式地包含一个叫做 Contains 的接收一个值为包含相关产生式的文法的终结符或者非终结符的 symbol 参数静态语义规则的定义。 默认的包含定义为:
上面的定义是显式地重写了规范的产生式。
一个特殊的静态语义规则是早期(提前)错误规则。早期错误规则定了早期错误条件(见
除非其它地方特别注明不包括无限并且不包括负 0(为了与正 0 区分),数学操作,例如加,减,否定(逻辑非),乘,除以及随后在条款中定义的数学函数应总是被当作是对于数学中所有真实数字计算出来的准确的结果。本规范算法中的浮点运算包含显式地的步骤,它们对于处理无穷,有符号的0,以及舍入是必要的。如果一个数学操作或者函数被应用在一个浮点数上,那么它必须被当作应用到用浮点数表示的具体的数学值;这样的浮点数必须是有限的,并且如果它是
数学函数
数学函数
符号 “
��学函数
本规范中算法控制每个具有相关类型的值。可能的值类型直接定义在本章节中。这些类型进一步分为 ECMAScript 语言类型与规范类型。
在本规范中,“Type(x)”表示法是“the type of x”的简写, 其中“type”指的是在本章节中定义的 ECMAScript 语言类型与规范类型。当一个值使用术语“empty”命名值时,它相当于说“没有任何类型的值”。
一个 ECMAScript 语言类型对应那些 ECMAScript 程序员在 ECMAScript 语言中直接使用的值。 ECMAScript 语言类型有 Undefined, Null, Boolean, String,Symbol, Number, Object。 一个ECMAScript 语言值是指拥有一个 ECMAScript 语言类型特点的值。
Undefined 类型仅仅只有一个值,undefined。 任何尚未分配值的变量值都为 undefined。
Null 类型只有一个值, null.
Boolean 类型表示具有 true 和 false 两个值的一个逻辑实体。
String 类型是零个或多个 16 位无符号整数值(“元素”)的所有有序序列的集合,最大长度为 253-1 个元素。字符串类型通常用于表示正在运行的 ECMAScript 程序中的文本数据,在这种情况下,String中的每个元素都被视为一个 UTF-16 码元。 每个元素被认为占据该序列内的一个位置。 这些位置用非负整数索引。 第一个元素(如果有)在索引 0 处,下一个元素(如果有的话)在索引 1 处,以此类推。 String 的长度是序列中的元素个数(例如,十六位值)。空字符串的长度为零,因此不包含元素。
ECMAScript 操作符不应用不同的语义解释字符串内容。操作符把字符串的每个元素视为单个 UTF-16 代码单元进行解释。但是,ECMAScript 并不约束这些代码单元的值或这些代码单元之间的关系,因此进一步将字符串内容解释为 UTF-16 中编码的 Unicode 代码点序列的操作必须考虑格式不对的子序列。此类操作使用如下规则对每个代码单元特殊处理,使其数值范围在 0xD800 到 0xDBFF(Unicode 标准定义为 首代理,或者更正式的 高代理码元)或范围 0xDC00 到 0xDFFF(定义为尾代理,或者更正式的低代理码元):
函数 String.prototype.normalize (see String.prototype.localeCompare (see
这种设计背后的理由是尽可能的保持 String 的实现简单和高效。 如果 ECMAScript 源文本符合 Normalized Form C,只要它们不包含任何 Unicode 转义序列,则字符串字面量保证也是标准化的。
在本规范中,短语"the string-concatenation of A,B,..."表示字符串代码单元的序列是每个参数的代码单元的连接。
Symbol 类型是所有可以用于作为 Object 属性 key 值的非字符串值的集合。(
每个可能的 Symbol 值都是唯一的和不可变的。
每个 Symbol 值永远地保持一个与之关联的叫做 [[Description]] 的值(它要么是
总所周知的 Symbol 是那些被本规范中算法明确引用的内置 Symbol 值。它们通常被用作属性的 key,这些 key 的值作为规范的算法扩展点。除非另有说明,总所周知的 Symbol 的值被所有域(
在本规范内,一个总所周知的 Symbol 值通过形如 @@name 的形式被引用,这里的 “name” 是表
| 规范名称 | [[Description]] | 值和目的 |
|---|---|---|
| @@asyncIterator |
"Symbol.asyncIterator"
|
返回对象的默认 AsyncIterator 的方法。 由 for-await-of 语句的语义调用。
|
| @@hasInstance |
"Symbol.hasInstance"
|
确定构造instanceof 运算符语义来调用。
|
| @@isConcatSpreadable |
"Symbol.isConcatSpreadable"
|
一个 Boolean 值,如果为 true, 表示一个对象应该被 Array.prototype.concat |
| @@iterator |
"Symbol.iterator"
|
返回一个对象的默认 Iterator 的方法。由 for-of 声明的语义来调用。 |
| @@match |
"Symbol.match"
|
将字符串与正则表达式匹配的正则表达式方法。 由 String.prototype.match |
| @@replace |
"Symbol.replace"
|
替换匹配字符串子串的正则表达式方法。 由 String.prototype.replace |
| @@search |
"Symbol.search"
|
一个正则表达式方法,它返回正则表达式匹配到的内容在字符串中的索引。 由String.prototype.search |
| @@species |
"Symbol.species"
|
作为构造函数的函数值属性,用来创建派生对象。 |
| @@split |
"Symbol.split"
|
一个正则表达式方法,它在正则表达式匹配的索引位置拆分字符串。 由 String.prototype.split |
| @@toPrimitive |
"Symbol.toPrimitive"
|
将一个对象转换为相应原始值的方法。由 |
| @@toStringTag |
"Symbol.toStringTag"
|
用于创建对象的默认字符串描述的 String 值属性。通过内置方法 Object.prototype.toString |
| @@unscopables |
"Symbol.unscopables"
|
一个对象值属性,其自身和继承的属性名是从相关对象的 with 环境绑定中排除的属性名。 |
Number 类型有 18437736874454810627 (即,
还有另外两个特殊的值,叫做
其他 18437736874454810624(即,
注意其中有一个
18437736874454810622(即
其中 18428729675200069632 (即
其中 s 为 +1 或 -1,m 是一个小于 253 但大于等于 252 的整数,e 是从 -1074 到 971 的整数。
其余 9007199254740990 (即
其中 s 是 +1 或 -1 ,m 是小于 2 的 52 次方的正整数,e 是 -1074。
注意,大小不大于 253 的所有正整数和负整数可以在 Number 类型中表示(实际上,整数 0 具有两个表示,
如果一个有限的数值非零且用来表达它(上文两种形式之一)的整数 m 是奇数,则该数值有奇数意义。否则,它有偶数意义。
在本规范中,当 x 表示一个精确的非零实数数学量(甚至可以是无理数,比如π)时,“the
某些 ECMAScript 运算符仅处理闭区间
对象在逻辑上是属性的集合。每个属性都是一个数据属性或一个访问器属性:
属性使用 key 值来标识。一个属性的 key 值是 ECMAScript String 值或 Symbol 值。所有 String 值(包括空字符串) 和 Symbol 值作为属性的 key 都是有效的。属性名称是指属性的 key,其值为字符串。
一个值为 +0 或者一个 ≤ 253-1 的整数作为属性 key 字符串值的数字索引是一个以典型的数字 String(见
属性的 key 用来访问属性以及其值。属性有两种访问方式:get 和 set ,分别对应值的检索和赋值。通过 get 和 set 可访问的属性既包括直接属于的自身属性,也包括通过继承关系由其它相关对象提供的继承属性。继承属性也可能是另一个对象的自身属性或者继承属性。对象的每个自身属性必须有一个与对象的其他自身属性 key 值不同 key 值。
所有的对象都是逻辑上的属性集合,但是在用于访问和操纵它们的属性的语义中存在多种形式的对象。普通对象是对象的最常见形式,拥有默认的对象语义。奇异对象是指其属性语义与默认语义的各个方面都有区别的对象。
在本规范中特性用来定义和解释对象属性的状态。
| 特性名称 | 值域 | 描述 |
|---|---|---|
| [[Value]] | 任何 ECMAScript 语言类型 | get 访问检索到的属性值 |
| [[Writable]] | Boolean |
如果为 |
| [[Enumerable]] | Boolean |
如果为 |
| [[Configurable]] | Boolean |
如果为 |
| 特性名称 | 值域 | 描述 |
|---|---|---|
| [[Get]] | Object | Undefined |
如果这个值是一个对象,那么它必须是一个 |
| [[Set]] | Object | Undefined |
如果这个值是一个对象,那么它必须是一个 |
| [[Enumerable]] | Boolean |
如果为 |
| [[Configurable]] | Boolean |
如果为 |
如果一个属性的特性的初始值没有被本规范显式地指定的,那么使用在表
| 特性名 | 默认值 |
|---|---|
| [[Value]] |
|
| [[Get]] |
|
| [[Set]] |
|
| [[Writable]] |
|
| [[Enumerable]] |
|
| [[Configurable]] |
|
在 ECMAScript 中,对象的实际语义是通过算法来调用内部方法指定的。在 ECMAScript 引擎中的每个对象都与一系列的定义它的运行时行为的内部方法相关联。这些内部方法不属于 ECMAScript 语言的一部分。本规范定义它们纯粹是为了说明目的。但是,在 ECMAScript 具体实现中的每个对象必须表现得与其相关关联的内部方法一致。其中确切的方式由实现者来决定。
内部方法名称是多态的。这意味着当一个通用内部方法被调用的时候,不同的对象值可能会执行不同的算法。调用内部方法实际的对象是这个调用 “target”。如果在运行时,实现的算法尝试使用一个对象不支持的内部方法,抛出一个TypeError异常。
内部槽对应于相关对象的内部状态,用于各种 ECMAScript 规范算法。内部槽不是对象的属性,也不会被继承。根据具体的内部槽规范,内部状态可能由任意 ECMAScript 语言类型的值或者指定的 ECMAScript 规范类型的值组成。除非另有指定,否则分配内部槽应作为创建一个对象的过程的部分,并且不应该动态地添加到对象上。除非另有指定,否则一个内部槽的初始值是
本规范内的内部方法和内部槽使用闭合的双方括号 [[]] 来标识。
表
表
| Internal Method | Signature | Description |
|---|---|---|
| [[GetPrototypeOf]] | ( ) → Object | Null |
确定为对象提供继承属性的对象。 |
| [[SetPrototypeOf]] | (Object | Null) → Boolean |
关联这个对象与提供继承属性的对象。传递 |
| [[IsExtensible]] | ( ) → Boolean | 决定是否允许添加额外的属性到这个对象上。 |
| [[PreventExtensions]] | ( ) → Boolean | 控制一个新的属性是否能加到这个对象上。返回 true 表示操作成功,返回 false 表示操作失败。 |
| [[GetOwnProperty]] |
(propertyKey) → Undefined | |
返回对象自身属性中 key 值为 propertyKey 的属性的属性描述符,如果没有这个属性返回undefined。
|
| [[DefineOwnProperty]] | (propertyKey, PropertyDescriptor) → Boolean | 创建或者改变 key 值为 propertyKey 的自身属性状态为 PropertyDescriptor。返回 true 表示属性被成功创建/更新,返回 false 表示属性不能被创建/更新。 |
| [[HasProperty]] | (propertyKey) → Boolean | 返回一个 Boolean 值,代表这个对象自身或者继承了一个 key 值为 propertyKey 的属性。 |
| [[Get]] | (propertyKey, Receiver) → any |
返回这个对象里 key 值为 propertyKey 的属性的值。如果必须运行一些的 ECMAScript 代码来检索这个属性值,Receiver 就会作为解析代码时的 |
| [[Set]] | (propertyKey, value, Receiver) → Boolean |
设置这个对象 key 值为 propertyKey 的属性的值为 value。如果必须运行一些的 ECMAScript 代码来检索这个属性值,Receiver 就会作为解析代码时的 |
| [[Delete]] | (propertyKey) → Boolean |
移除这个对象 key 值为 propertyKey 的自身属性。 如果这个属性没有被移除,仍然存在,则返回 |
| [[OwnPropertyKeys]] |
( ) → |
返回一个包含所有自身属性 key 值的 |
表
| Internal Method | Signature | Description |
|---|---|---|
| [[Call]] |
(any, a |
执行这个对象相关联的代码。通过一个函数表达式来调用。通过调用表达式,传递给内部函数的 arguments 为一个 |
| [[Construct]] |
(a |
创建一个对象。通过 new 或者 super 操作符调用。这个内部方法的第一个参数是一个包含操作符的参数的列表。第二个参数是 new 操作符初始化时应用的对象。实现这个内部方法的对象被称为构造函数。一个 |
这些
ECMAScript 引擎中的内部方法必须符合以下指定的不变量列表。普通 ECMAScript 对象以及该规范中的标准怪异对象应保持这些不变量。ECMAScript Proxy 对象通过运行时检查 [[ProxyHandler]] 对象的陷阱调用结果的手段来保持这些不变量。
任何实现提供的怪异对象必须也保持这些不变量。违反这些不变量可能会导致 ECMAScript 代码出现不可预料的行为以及安全问题。然而,对于造成内存安全的违反不变量行为的实现决不能妥协。
实现不允许通过任何方式规避这些不变量。比如,通过提供替代接口来实现基本内部方法的功能而不强制执行他们的不变量。
作为第三个不变量的推论,如果一个属性被描述为一个
如果 P 预先已经作为 target 的一个不可配置的自身属性被观察,那么 [[DefineOwnProperty]] 必须返回 false,除非满足一下条件之一:
总所周知的内联函数是在该规范中通过算法明确引用的内置对象,这些内置对象通常有特定域的不变量。除非特别指出,每个内部对象在每个领域通常对应一系列相似对象的集合。
在本规范中像 %name% 这样的引用意味着关联到相应的 name 域的内部对象。决定当前域以及他的内联函数在
| 内在名称 | 全局名称 | ECMAScript 语言关联 |
|---|---|---|
|
|
Array
|
Array 构造函数 ( |
|
|
ArrayBuffer
|
ArrayBuffer 构造函数 ( |
|
|
ArrayBuffer.prototype
|
prototype |
|
|
数组迭代器对象的原型 ( |
|
|
|
Array.prototype
|
prototype |
|
|
Array.prototype.entries
|
entries |
|
|
Array.prototype.forEach
|
forEach |
|
|
Array.prototype.keys
|
keys |
|
|
Array.prototype.values
|
values |
|
|
The prototype of async-from-sync iterator objects ( |
|
|
|
async |
|
|
|
prototype |
|
|
|
The initial value of the prototype property of |
|
|
|
The |
|
|
|
The initial value of the prototype property of |
|
|
|
An object that all standard built-in async iterator objects indirectly inherit from | |
|
|
Atomics
|
Atomics 对象 ( |
|
|
Boolean
|
Boolean 构造函数 ( |
|
|
Boolean.prototype
|
prototype |
|
|
DataView
|
DataView 构造函数 ( |
|
|
DataView.prototype
|
prototype |
|
|
Date
|
Date 构造函数 ( |
|
|
Date.prototype
|
prototype |
|
|
decodeURI
|
decodeURI 函数 ( |
|
|
decodeURIComponent
|
decodeURIComponent 函数 ( |
|
|
encodeURI
|
encodeURI 函数 ( |
|
|
encodeURIComponent
|
encodeURIComponent 函数 ( |
|
|
Error
|
Error 构造函数 ( |
|
|
Error.prototype
|
prototype |
|
|
eval
|
eval 函数 ( |
| %EvalError% |
EvalError
|
EvalError 构造函数 ( |
| %EvalErrorPrototype% |
EvalError.prototype
|
%EvalError% prototype 属性的初始值
|
| %Float32Array% |
Float32Array
|
Float32Array 构造函数 ( |
| %Float32ArrayPrototype% |
Float32Array.prototype
|
%Float32Array% prototype |
| %Float64Array% |
Float64Array
|
Float64Array 构造函数 ( |
| %Float64ArrayPrototype% |
Float64Array.prototype
|
%Float64Array% prototype |
|
|
Function
|
Function 构造函数 ( |
|
|
Function.prototype
|
prototype |
|
|
prototype 属性的初始值
|
|
|
|
generator 对象的构造函数 ( |
|
|
|
prototype 属性的初始值
|
|
| %Int8Array% |
Int8Array
|
Int8Array 构造函数 ( |
| %Int8ArrayPrototype% |
Int8Array.prototype
|
%Int8Array% prototype |
| %Int16Array% |
Int16Array
|
Int16Array 构造函数 ( |
| %Int16ArrayPrototype% |
Int16Array.prototype
|
%Int16Array% prototype |
| %Int32Array% |
Int32Array
|
Int32Array 构造函数 ( |
| %Int32ArrayPrototype% |
Int32Array.prototype
|
%Int32Array% prototype |
|
|
isFinite
|
isFinite 函数 ( |
|
|
isNaN
|
isNaN 函数 ( |
|
|
所有标准内置迭代对象间接继承的对象 | |
|
|
JSON
|
JSON 对象 ( |
|
|
JSON.parse
|
parse |
|
|
Map
|
Map 构造函数 ( |
|
|
Map 迭代器对象的原型 ( |
|
|
|
Map.prototype
|
prototype |
|
|
Math
|
Math 对象 ( |
|
|
Number
|
Number 构造函数 ( |
|
|
Number.prototype
|
prototype 属性的初始值
|
|
|
Object
|
Object 构造函数 ( |
|
|
Object.prototype
|
prototype |
|
|
Object.prototype.toString
|
toString |
|
|
Object.prototype.valueOf
|
valueOf |
|
|
parseFloat
|
parseFloat 函数 ( |
|
|
parseInt
|
parseInt 函数 ( |
|
|
Promise
|
Promise 构造函数 ( |
|
|
Promise.prototype
|
prototype |
|
|
Promise.prototype.then
|
The initial value of the then |
|
|
Promise.all
|
The initial value of the all |
|
|
Promise.reject
|
The initial value of the reject |
|
|
Promise.resolve
|
The initial value of the resolve |
|
|
Proxy
|
Proxy 构造函数 ( |
| %RangeError% |
RangeError
|
RangeError 构造函数 ( |
| %RangeErrorPrototype% |
RangeError.prototype
|
%RangeError% prototype 属性的初始值
|
| %ReferenceError% |
ReferenceError
|
ReferenceError 构造函数 ( |
| %ReferenceErrorPrototype% |
ReferenceError.prototype
|
%ReferenceError% prototype 属性的初始值
|
|
|
Reflect
|
Reflect 对象 ( |
|
|
RegExp
|
RegExp 构造函数 ( |
|
|
RegExp.prototype
|
prototype |
|
|
Set
|
Set 构造函数 ( |
|
|
Set 迭代器对象的原型 ( |
|
|
|
Set.prototype
|
prototype |
|
|
SharedArrayBuffer
|
SharedArrayBuffer 构造函数 ( |
|
|
SharedArrayBuffer.prototype
|
prototype |
|
|
String
|
String 构造函数 ( |
|
|
String 迭代器对象的原型 ( |
|
|
|
String.prototype
|
prototype |
|
|
Symbol
|
Symbol 构造函数 ( |
|
|
Symbol.prototype
|
prototype |
| %SyntaxError% |
SyntaxError
|
SyntaxError 构造函数 ( |
| %SyntaxErrorPrototype% |
SyntaxError.prototype
|
%SyntaxError% prototype 属性的初始值
|
|
|
一个 |
|
|
|
所有数组类型 |
|
|
|
|
|
| %TypeError% |
TypeError
|
TypeError 构造函数 ( |
| %TypeErrorPrototype% |
TypeError.prototype
|
%TypeError% prototype 属性的初始值
|
| %Uint8Array% |
Uint8Array
|
Uint8Array 构造函数 ( |
| %Uint8ArrayPrototype% |
Uint8Array.prototype
|
%Uint8Array% prototype |
| %Uint8ClampedArray% |
Uint8ClampedArray
|
Uint8ClampedArray 构造函数 ( |
| %Uint8ClampedArrayPrototype% |
Uint8ClampedArray.prototype
|
%Uint8ClampedArray% prototype |
| %Uint16Array% |
Uint16Array
|
Uint16Array 构造函数 ( |
| %Uint16ArrayPrototype% |
Uint16Array.prototype
|
%Uint16Array% prototype |
| %Uint32Array% |
Uint32Array
|
Uint32Array 构造函数 ( |
| %Uint32ArrayPrototype% |
Uint32Array.prototype
|
%Uint32Array% prototype |
| %URIError% |
URIError
|
URIError 构造函数 ( |
| %URIErrorPrototype% |
URIError.prototype
|
%URIError% prototype 属性的初始值
|
|
|
WeakMap
|
WeakMap 构造函数 ( |
|
|
WeakMap.prototype
|
prototype |
|
|
WeakSet
|
WeakSet 构造函数 ( |
|
|
WeakSet.prototype
|
prototype |
规范类型对应那些在算法中用来描述 ECMAScript 语言结构以及 ECMAScript 语言类型语义的元数据。 规范类型包括
List 类型用来解释在 new 表达式,函数调用,以及其它需要一个简单的有序的值的 list 的算法中的参数列表(见
在规范中为了方便,一个字面量语法被用来表达一个新 List 值。 如 « 1, 2 » 定义一个新 List 值,它拥有两个元素,每个元素被初始化为一个特定的值。一个空的 List 值可以用 « » 表示。
Record 类型用来描述在该规范中的算法内的数据聚合。一个 Record 类型值包含一个或多个命名字段。每个字段的值是一个 ECMAScript 值或者通过由与 Record 类型相关联的名称代表的抽象值。字段名称始终用双括号括起来,例如 [[Value]]。
在规范中为了方便,使用类似对象字面量的语法来表示一个 Record 值。 如 { [[Field1]]: 42, [[Field2]]: false, [[Field3]]:
在规范文本和算法中,点记号可以用于指代记录值的特定字段。例如,如果 R 是上一段所示的记录,则 R.[[Field2]] 是 “R 中名称为 [[Field2]] 的字段 ” 的缩写。
应该命名常用记录字段组合的模式, 并且该名称可以用作Record字面量的前缀,以标识特定类型聚合的描述。 例如:PropertyDescriptor { [[Value]]: 42,[[Writable]]: false,[[Configurable]]: true }。
Set 类型被用来解释在内存模型中无序元素的集合。Set 类型的值是简单的元素的集合,其中没有任何元素出现超过一次。元素可以从 Set 中添加或者删除。不同的 Set 可以合并,相交或者相减。
Relation 类型被用来解释在 Set 上的约束。一个关系类型的值是它的的值域中有序对的集合。例如,一个在 event 上的关系是一个有序的的 event 对的集合。对于一个关系 R 以及在 R 的值域中的两个值 a 和 b,a R b 是有序对 (a, b) 是 R 的成员的简写。当 Relation 满足这些条件的最小 Relation 时,Relation 对于某些条件是最小的。
严格偏序是指一个 Relation 值 R 满足如下条件。
对于R值域中的 a,b,c:
上述两种关系的特性被称为自反性和传递性。
严格全序是指一个 Relation 值 R 满足如下条件。
R 值域中的 a,b,c:
上述三种关系的特性,按顺序被称为完全性,自反性,传递性
Completion 类型是一个用来解释运行时数值和控制流传播的 break,continue,return 和 throw)的行为。
Completion 类型值是字段名为表
| 字段名 | 值 | 意义 |
|---|---|---|
| [[Type]] |
|
结束发生的完成类型 |
| [[Value]] |
任何 ECMAScript 语言值或 |
产生的值 |
| [[Target]] |
任何 ECMAScript 字符串或 |
用于定向控制传输的目标标签。 |
术语 “异常结束” 是指 [[Type]] 值为除
Algorithm steps that say
mean the same thing as:
where all variables in the above steps, with the exception of completion, are ephemeral and visible only in the steps pertaining to Await.
Await can be combined with the ? and ! prefixes, so that for example
means the same thing as:
An
When an
The length property of an
An
When an
The length property of an
Is a shorthand that is defined as follows:
The abstract operation ThrowCompletion with a single argument, such as:
是下面定义的简写:
Reference 类型用于解释如 delete,typeof,分配操作,super 关键字以及其他语言功能的操作的行为。例如,分配一个左操作数预计将产生一个引用。
一个 Reference 是一个解析后的名称或者属性组合。一个 Reference 包含3个组件,基值组件,引用名组件,以及一个 Boolean 值的严格引用标志。一个基值组件可以是
一个 Super Reference 是指,用于表示使用 super 关键字表示一个名称组合的 Reference。一个
以下
在步骤 5.a.ii 中创建的对象在上面抽象方法和
ReferenceError exception.true, thentrue, thenReferenceError exception.false).true, thentrue, thenfalse and true, throw a TypeError exception.在步骤 6.a.ii 中创建的对象在上面抽象方法和
Property Descriptor 类型用来解释对象属性的特性的操作和具体化。Property Descriptor 的值为
Property Descriptor 值可以根据某些字段的存在或使用进一步分类为数据 Property Descriptor 和访问器 Property Descriptor。包含字段 [[Value]] 或 [[Writable]] 的是数据 Property Descriptor。包含字段 [[Get]] 或 [[Set]] 的是访问器 Property Descriptor。所有的 Property Descriptor 都可能包含 [[Enumerable]],[[Configurable]] 字段名。一个 Property Descriptor 值可能不会同时为一个数据 Property Descriptor 和一个访问器 Property Descriptor。然而,也不一定,一个通用 Property Descriptor 是一个既不是数据 Property Descriptor 也不是访问器 Property Descriptor 的 Property Descriptor值。一个完全填充的 Property Descriptor 既是一个数据 Property Descriptor 也是一个访问器 Property Descriptor, 他有所有符合表
在本规范中使用以下
当用
undefined, return false.false.true.当用
当用
undefined, return false.false, return true.false.当用
"value", Desc.[[Value]])."writable", Desc.[[Writable]])."get", Desc.[[Get]])."set", Desc.[[Set]])."enumerable", Desc.[[Enumerable]])."configurable", Desc.[[Configurable]]).当用一个对象 Obj 作为参数调用
"enumerable")."configurable")."value")."value")."writable")."get")."get")."set")."set").当用
Data Block 规范类型用来描述不同且可变的字节(8 bit)大小的数字值序列。一个 Data Block 值由初始值为 0,固定数量的字节构成。
在本规范中为了方便,可以使用类似数组的语法来访问一个 Data Block 值的各个字节。这些符号将 Data Block 值的这些字节表示为一个从 0 开始的索引队列。 例如,如果 db 是一个 5 字节的 Data Block 值,那么 db[2] 可以用来访问第三字节。
驻留在内存中,可以被多个代理并发引用的数据块被称为 Shared Data Block。一个 Shared Data Block 有一个 空地址 的标识(目的是平等检测 Shared Data Block 值): 它不依赖于所述块在任何进程中映射到的虚拟地址,而是用该块来表示内存中的位置集合。只有当两个块包含的位置集合相等时他们才相等。否则,他们地址集合的交集为空,他们是不相等的。最后,可以从 Data Block 区分 Shared Data Blocks。
Shared Data Block 的语义由内存模型中的 Shared Data Block 事件来定义。下方的
Shared Data Block 事件由
下列
当用整数参数 size 调用
当用整数参数 size 调用
"Init", [[NoTear]]: 当
"Unordered", [[NoTear]]: "Unordered", [[NoTear]]: 这些操作不是 ECMAScript 语言的一部分;在这里定义他们只是为了规范 ECMAScript 语言的语义。另外,本规范中还定义了其他特定的
ECMAScript 语言根据需要会自动执行类型转换。为了解释清楚某些结构的语义,定义一组转换
"default"."string"."number"."default", set hint to "number".当使用参数 O 和 hint 调用
"string" or "number"."string", then"toString", "valueOf" »."valueOf", "toString" ».| 参数类型 | 结果 |
|---|---|
| Undefined |
返回 |
| Null |
返回 |
| Boolean | 返回 argument。 |
| Number |
如果 argument 为 |
| String |
如果 argument 是一个空字符串 (长度为0的字符串), 返回 |
| Symbol |
返回 |
| Object |
返回 |
| 参数类型 | 结果 |
|---|---|
| Undefined |
返回 |
| Null |
返回 |
| Boolean |
如果 argument 是 |
| Number | 返回 argument (不转换)。 |
| String | 见下面语法和转换算法。 |
| Symbol |
抛出一个 |
| Object |
应用以下步骤:
|
应用
以上所有未明确定义的语法符号都在数字字面量词法定义(
应该注意
0 的数字。
+ 或 - 以指示其符号。
Infinity 和 -Infinity 公认是 字符串到 Number 值的转换和一个的数字字面量 Number 值的确定总体上来说是相似的(见
+∞).
一旦确定了字符串数字字面量确切的数值,它将被舍入为一个 Number 类型的值。如果数值为 0,那么它舍入的值为 "-",这种情况舍入值为
0; 或者
鉴于以上 ToInt32 的定义:
鉴于以上 ToUint16 的定义:
与其他 ECMAScript 整数转换
| 参数类型 | 结果 |
|---|---|
| Undefined |
返回 "undefined".
|
| Null |
返回 "null".
|
| Boolean |
如果 argument 是 如果 argument 是 |
| Number |
返回 |
| String | 返回 argument. |
| Symbol |
抛出一个 |
| Object |
应用如下步骤:
|
"NaN"."0"."-" and ! "Infinity".对于提供了比上述转换规则更准确的实现,建议其中第五步参考下面的另一个版本:
David M. Gay 编写的二进制转换为十进制中关于浮点数的文章和代码对于 ECMAScript 实现者可能会有帮助:
Gay, David M. Correctly Rounded Binary-Decimal and Decimal-Binary Conversions. Numerical Analysis, Manuscript 90-10. AT&T Bell Laboratories (Murray Hill, New Jersey). November 30, 1990. 相关文章可以在
http://ampl.com/REFS/abstracts.html#rounding 找到. 相关代码在
http://netlib.sandia.gov/fp/dtoa.c 和
http://netlib.sandia.gov/fp/g_fmt.c ,这些代码也可以在其他 netlib 镜像网站找到。
| 参数类型 | 结果 |
|---|---|
| Undefined |
抛出一个 |
| Null |
抛出一个 |
| Boolean |
返回一个内部槽 [[BooleanData]] 为 argument 的新 Boolean 对象。见 |
| Number |
返回一个内部槽 [[NumberData]] 为 argument 的新 Number 对象。见 |
| String |
返回一个内部槽 [[StringData]] 为 argument 的新 String 对象。见 |
| Symbol |
返回一个内部槽 [[SymbolData]] 为 argument 的新 Symbol 对象。见 |
| Object | 返回 argument。 |
如果 argument 为是一可以通过 "-0" 的字符串,则undefined。这个
一个规范的数字字符串是指 CanonicalNumericIndexString
undefined, then| 参数类型 | 结果 |
|---|---|
| Undefined |
抛出一个 |
| Null |
抛出一个 |
| Boolean | 返回 argument. |
| Number | 返回 argument. |
| String | 返回 argument. |
| Symbol | 返回 argument. |
| Object | 返回 argument. |
参数为 argument 的
内部比较
这个算法在比较有符号的 0 以及比较 NaN 时和严格相等比较算法不同。
内部比较
false.SameValueZero 与 +0 和 -0 时不同
内部比较
比较x < y,x 和 y 都是 ECMAScript 语言值,将可能产生
true, then算法中的第三步和第七步不同是加法运算 + (
字符串类型的比较使用码元值序列的简单词典排序。这里没有尝试使用 Unicode 规范定义的更复杂的,基于语义的字符或字符串相等,以及排序顺序进行比较。因此,根据 Unicode 标准在规范上相等的字符串值可能测试为不相等。实际上,该算法假设了两个值是已经标准化的值。另外还需注意,对于包含补充字符的字符串,UTF-16 码元值序列与普通码元值序列的词典排序是不同的。
比较 x == y,产生
比较 x === y,产生
该算法与
该
If newTarget is not present, this operation is equivalent to: new F(...argumentsList)
"sealed" or "frozen"."sealed", then"frozen","sealed" or "frozen"."frozen" and this 值, P 是属性 key, argumentsList 是传递给方法的参数列表。 如果 argumentsList 未提供,则使用一个空的
"prototype")."constructor").当使用对象 O 和字符串 kind 作为参数调用
参数为 obj 的
第五步只有在 obj 是一个没有 [[Realm]] 内部槽的非标准函数怪异对象时执行。
When the abstract operation CopyDataProperties is called with arguments target, source, and excludedItems, the following steps are taken:
The target passed in here is always a newly created object which is not directly accessible in case of an error being thrown.
参考常见的迭代接口 (
参数为 obj 和可选参数 hint, method 的
"next").参数为 iteratorRecord 和可选参数 value 的
参数为 iterResult 的
使用参数为 iterResult 的
使用参数 iteratorRecord 的
参数为 iteratorRecord 和 completion 的
"return").The abstract operation AsyncIteratorClose with arguments iteratorRecord and completion is used to notify an async iterator that it should perform any actions it would normally perform when it has reached its completed state:
"return").参数为 value 和 done 的
"value", value)."done", done).参数为 list 的
next (这个迭代器对象列表从不直接通过 ECMAScript 代码访问。
ListIterator next 方法是一个标准的内置函数方法(章节
A Lexical Environment is a specification type used to define the association of
An
The outer environment reference is used to model the logical nesting of Lexical Environment values. The outer reference of a (inner) Lexical Environment is a reference to the Lexical Environment that logically surrounds the inner Lexical Environment. An outer Lexical Environment may, of course, have its own outer Lexical Environment. A Lexical Environment may serve as the outer environment for multiple inner Lexical Environments. For example, if a
A global environment is a Lexical Environment which does not have an outer environment. The
A module environment is a Lexical Environment that contains the bindings for the top level declarations of a
A function environment is a Lexical Environment that corresponds to the invocation of an ECMAScript this binding. A super method invocations.
Lexical Environments and
There are two primary kinds of Environment Record values used in this specification: declarative Environment Records and object Environment Records. Declarative Environment Records are used to define the effect of ECMAScript language syntactic elements such as
For specification purposes Environment Record values are values of the
| Method | Purpose |
|---|---|
| HasBinding(N) |
Determine if an |
| CreateMutableBinding(N, D) |
Create a new but uninitialized mutable binding in an |
| CreateImmutableBinding(N, S) |
Create a new but uninitialized immutable binding in an |
| InitializeBinding(N, V) |
Set the value of an already existing but uninitialized binding in an |
| SetMutableBinding(N, V, S) |
Set the value of an already existing mutable binding in an |
| GetBindingValue(N, S) |
Returns the value of an already existing binding from an |
| DeleteBinding(N) |
Delete a binding from an |
| HasThisBinding() |
Determine if an this binding. Return |
| HasSuperBinding() |
Determine if an super method binding. Return |
| WithBaseObject() |
If this with statement, return the with object. Otherwise, return |
Each declarative
The behaviour of the concrete specification methods for declarative Environment Records is defined by the following algorithms.
The concrete
The concrete
The concrete
The concrete
The concrete
An example of ECMAScript code that results in a missing binding at step 2 is:
function f(){eval("var x; x = (delete x, 0);")}
The concrete
The concrete
Regular declarative Environment Records do not provide a this binding.
Regular declarative Environment Records do not provide a super binding.
Declarative Environment Records always return
Each object
Object Environment Records created for with statements (
The behaviour of the concrete specification methods for object Environment Records is defined by the following algorithms.
The concrete
The concrete
Normally envRec will not have a binding for N but if it does, the semantics of
The concrete
The concrete
In this specification, all uses of CreateMutableBinding for object Environment Records are immediately followed by a call to InitializeBinding for the same name. Hence, implementations do not need to explicitly track the initialization state of individual object
The concrete
The concrete
The concrete
Regular object Environment Records do not provide a this binding.
Regular object Environment Records do not provide a super binding.
Object Environment Records return
A function Environment Record is a declarative this binding. If a function is not an super, its function Environment Record also contains the state that is used to perform super method invocations from within the function.
Function Environment Records have the additional state fields listed in
| Field Name | Value | Meaning |
|---|---|---|
| [[ThisValue]] | Any |
This is the |
| [[ThisBindingStatus]] |
"lexical" | "initialized" | "uninitialized"
|
If the value is "lexical", this is an |
| [[FunctionObject]] | Object |
The |
| [[HomeObject]] |
Object | |
If the associated function has super property accesses and is not an |
| [[NewTarget]] |
Object | |
If this |
Function Environment Records support all of the declarative
| Method | Purpose |
|---|---|
| BindThisValue(V) | Set the [[ThisValue]] and record that it has been initialized. |
| GetThisBinding() |
Return the value of this this binding. Throws a this binding has not been initialized.
|
| GetSuperBase() |
Return the object that is the base for super property accesses bound in this super property accesses will produce runtime errors.
|
The behaviour of the additional concrete specification methods for function Environment Records is defined by the following algorithms:
"lexical"."initialized", throw a "initialized"."lexical", return "lexical", return "lexical"."uninitialized", throw a A global
A global
Properties may be created directly on a
Global Environment Records have the additional fields listed in
| Field Name | Value | Meaning |
|---|---|---|
| [[ObjectRecord]] |
Object |
Binding object is the |
| [[GlobalThisValue]] | Object |
The value returned by this in global scope. Hosts may provide any ECMAScript Object value.
|
| [[DeclarativeRecord]] |
Declarative |
Contains bindings for all declarations in global code for the associated |
| [[VarNames]] |
|
The string names bound by |
| Method | Purpose |
|---|---|
| GetThisBinding() |
Return the value of this this binding.
|
| HasVarDeclaration (N) |
Determines if the argument identifier has a binding in this |
| HasLexicalDeclaration (N) |
Determines if the argument identifier has a binding in this |
| HasRestrictedGlobalProperty (N) |
Determines if the argument is the name of a |
| CanDeclareGlobalVar (N) | Determines if a corresponding CreateGlobalVarBinding call would succeed if called for the same argument N. |
| CanDeclareGlobalFunction (N) | Determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N. |
| CreateGlobalVarBinding(N, D) |
Used to create and initialize to var binding in the [[ObjectRecord]] component of a global var. The String value N is the bound name. If D is |
| CreateGlobalFunctionBinding(N, V, D) |
Create and initialize a global function binding in the [[ObjectRecord]] component of a global function. The String value N is the bound name. V is the initialization value. If the Boolean argument D is |
The behaviour of the concrete specification methods for global Environment Records is defined by the following algorithms.
The concrete
The concrete
The concrete
The concrete
The concrete
The concrete
The concrete
Global Environment Records always return
The concrete
The concrete
The concrete
Properties may exist upon a undefined is an example of such a property.
The concrete
The concrete
The concrete
The concrete
Global function declarations are always represented as own properties of the
A module
Module Environment Records support all of the declarative
| Method | Purpose |
|---|---|
| CreateImportBinding(N, M, N2) |
Create an immutable indirect binding in a module |
| GetThisBinding() |
Return the value of this this binding.
|
The behaviour of the additional concrete specification methods for module Environment Records are defined by the following algorithms:
The concrete
S will always be
The concrete
Module Environment Records are only used within strict code and an
Module Environment Records provide a this binding.
The concrete
The following
The abstract operation GetIdentifierReference is called with a
When the abstract operation NewDeclarativeEnvironment is called with a
When the abstract operation NewObjectEnvironment is called with an Object O and a
When the abstract operation NewFunctionEnvironment is called with arguments F and newTarget the following steps are performed:
"lexical"."uninitialized".When the abstract operation NewGlobalEnvironment is called with arguments G and thisValue, the following steps are performed:
When the abstract operation NewModuleEnvironment is called with a
Before it is evaluated, all ECMAScript code must be associated with a realm. Conceptually, a
A
| Field Name | Value | Meaning |
|---|---|---|
| [[Intrinsics]] |
|
The intrinsic values used by code associated with this |
| [[GlobalObject]] | Object |
The |
| [[GlobalEnv]] |
|
The |
| [[TemplateMap]] |
A |
Template objects are canonicalized separately for each Once a |
| [[HostDefined]] |
Any, default value is |
Field reserved for use by host environments that need to associate additional information with a |
The abstract operation CreateRealm with no arguments performs the following steps:
The abstract operation CreateIntrinsics with argument realmRec performs the following steps:
The abstract operation SetRealmGlobalObject with arguments realmRec, globalObj, and thisValue performs the following steps:
The abstract operation SetDefaultGlobalBindings with argument realmRec performs the following steps:
An execution context is a specification device that is used to track the runtime evaluation of code by an ECMAScript implementation. At any point in time, there is at most one execution context per
The execution context stack is used to track execution contexts. The
An execution context contains whatever implementation specific state is necessary to track the execution progress of its associated code. Each execution context has at least the state components listed in
| Component | Purpose |
|---|---|
| code evaluation state |
Any state needed to perform, suspend, and resume evaluation of the code associated with this |
| Function |
If this |
|
|
The |
| ScriptOrModule |
The |
Evaluation of code by the
The value of the
Execution contexts for ECMAScript code have the additional state components listed in
| Component | Purpose |
|---|---|
| LexicalEnvironment |
Identifies the |
| VariableEnvironment |
Identifies the |
The LexicalEnvironment and VariableEnvironment components of an execution context are always Lexical Environments.
Execution contexts representing the evaluation of generator objects have the additional state components listed in
| Component | Purpose |
|---|---|
| Generator |
The GeneratorObject that this |
In most situations only the
An execution context is purely a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation. It is impossible for ECMAScript code to directly access or observe an execution context.
The GetActiveScriptOrModule abstract operation is used to determine the running script or module, based on the
The ResolveBinding abstract operation is used to determine the binding of name passed as a String value. The optional argument env can be used to explicitly provide the
The result of ResolveBinding is always a
The abstract operation GetThisEnvironment finds the this. GetThisEnvironment performs the following steps:
The loop in step 2 will always terminate because the list of environments always ends with the this binding.
The abstract operation ResolveThisBinding determines the binding of the this using the LexicalEnvironment of the
The abstract operation GetNewTarget determines the NewTarget value using the LexicalEnvironment of the
The abstract operation GetGlobalObject returns the
A
Execution of a
| Field Name | Value | Meaning |
|---|---|---|
| [[Job]] |
The name of a |
This is the abstract operation that is performed when execution of this PendingJob is initiated. |
| [[Arguments]] |
A |
The |
| [[Realm]] |
A |
The |
| [[ScriptOrModule]] |
A |
The script or module for the initial |
| [[HostDefined]] |
Any, default value is |
Field reserved for use by host environments that need to associate additional information with a pending |
A
Each
A request for the future execution of a
The PendingJob records from a single
Typically an ECMAScript implementation will have its
The following
The EnqueueJob abstract operation requires three arguments: queueName, job, and arguments. It performs the following steps:
The abstract operation InitializeHostDefinedRealm performs the following steps:
this binding in realm's global scope return an object other than the this binding should be the The abstract operation RunJobs performs the following steps:
"ScriptJobs", "ScriptJobs", An agent comprises a set of ECMAScript execution contexts, an
An
Some web browsers share a single
While an
| Field Name | Value | Meaning |
|---|---|---|
| [[LittleEndian]] | Boolean | The default value computed for the isLittleEndian parameter when it is needed by the algorithms |
| [[CanBlock]] | Boolean | Determines whether the |
| [[Signifier]] | Any globally-unique value | Uniquely identifies the |
| [[IsLockFree1]] | Boolean | |
| [[IsLockFree2]] | Boolean | |
| [[CandidateExecution]] | A |
See the |
Once the values of [[Signifier]], [[IsLockFree1]], and [[IsLockFree2]] have been observed by any
The values of [[IsLockFree1]] and [[IsLockFree2]] are not necessarily determined by the hardware, but may also reflect implementation choices that can vary over time and between ECMAScript implementations.
There is no [[IsLockFree4]] property: 4-byte atomic operations are always lock-free.
In practice, if an atomic operation is implemented with any type of lock the operation is not lock-free. Lock-free does not imply wait-free: there is no upper bound on how many machine steps may be required to complete a lock-free atomic operation.
That an atomic access of size n is lock-free does not imply anything about the (perceived) atomicity of non-atomic accesses of size n, specifically, non-atomic accesses may still be performed as a sequence of several separate memory accesses. See
An
The abstract operation AgentSignifier takes no arguments. It performs the following steps:
The abstract operation AgentCanSuspend takes no arguments. It performs the following steps:
In some environments it may not be reasonable for a given
An agent cluster is a maximal set of agents that can communicate by operating on shared memory.
Programs within different agents may share memory by unspecified means. At a minimum, the backing memory for SharedArrayBuffer objects can be shared among the agents in the cluster.
There may be agents that can communicate by message passing that cannot share memory; they are never in the same agent cluster.
Every
All agents within a cluster must have the same value for the [[LittleEndian]] property in their respective
If different agents within an agent cluster have different values of [[LittleEndian]] it becomes hard to use shared memory for multi-byte data.
All agents within a cluster must have the same values for the [[IsLockFree1]] property in their respective
All agents within a cluster must have different values for the [[Signifier]] property in their respective
An embedding may deactivate (stop forward progress) or activate (resume forward progress) an
The purpose of the preceding restriction is to avoid a situation where an
The implication of the restriction is that it will not be possible to share memory between agents that don't belong to the same suspend/wake collective within the embedding.
An embedding may terminate an
Prior to any evaluation of any ECMAScript code by any
All agents in an agent cluster share the same
An agent cluster is a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation.
For an
An
Implementations must ensure that:
This, along with the liveness guarantee in the "SeqCst" writes eventually become observable to all agents.
All ordinary objects have an internal slot called [[Prototype]]. The value of this internal slot is either
Every ordinary object has a Boolean-valued [[Extensible]] internal slot that controls whether or not properties may be added to the object. If the value of the [[Extensible]] internal slot is
In the following algorithm descriptions, assume O is an ordinary object, P is a property key value, V is any
Each ordinary object internal method delegates to a similarly-named abstract operation. If such an abstract operation depends on another internal method, then the internal method is invoked on O rather than calling the similarly-named abstract operation directly. These semantics ensure that exotic objects have their overridden internal methods invoked when ordinary object internal methods are applied to them.
When the [[GetPrototypeOf]] internal method of O is called, the following steps are taken:
When the abstract operation OrdinaryGetPrototypeOf is called with Object O, the following steps are taken:
When the [[SetPrototypeOf]] internal method of O is called with argument V, the following steps are taken:
When the abstract operation OrdinarySetPrototypeOf is called with Object O and value V, the following steps are taken:
The loop in step 8 guarantees that there will be no circularities in any prototype chain that only includes objects that use the ordinary object definitions for [[GetPrototypeOf]] and [[SetPrototypeOf]].
When the [[IsExtensible]] internal method of O is called, the following steps are taken:
When the abstract operation OrdinaryIsExtensible is called with Object O, the following steps are taken:
When the [[PreventExtensions]] internal method of O is called, the following steps are taken:
When the abstract operation OrdinaryPreventExtensions is called with Object O, the following steps are taken:
When the [[GetOwnProperty]] internal method of O is called with property key P, the following steps are taken:
When the abstract operation OrdinaryGetOwnProperty is called with Object O and with property key P, the following steps are taken:
When the [[DefineOwnProperty]] internal method of O is called with property key P and
When the abstract operation OrdinaryDefineOwnProperty is called with Object O, property key P, and
When the abstract operation IsCompatiblePropertyDescriptor is called with Boolean value Extensible, and Property Descriptors Desc, and Current, the following steps are taken:
When the abstract operation ValidateAndApplyPropertyDescriptor is called with Object O, property key P, Boolean value extensible, and Property Descriptors Desc, and current, the following steps are taken:
If
When the [[HasProperty]] internal method of O is called with property key P, the following steps are taken:
When the abstract operation OrdinaryHasProperty is called with Object O and with property key P, the following steps are taken:
When the [[Get]] internal method of O is called with property key P and
When the abstract operation OrdinaryGet is called with Object O, property key P, and
When the [[Set]] internal method of O is called with property key P, value V, and
When the abstract operation OrdinarySet is called with Object O, property key P, value V, and
When the abstract operation OrdinarySetWithOwnDescriptor is called with Object O, property key P, value V,
When the [[Delete]] internal method of O is called with property key P, the following steps are taken:
When the abstract operation OrdinaryDelete is called with Object O and property key P, the following steps are taken:
When the [[OwnPropertyKeys]] internal method of O is called, the following steps are taken:
When the abstract operation OrdinaryOwnPropertyKeys is called with Object O, the following steps are taken:
The abstract operation ObjectCreate with argument proto (an object or null) is used to specify the runtime creation of new ordinary objects. The optional argument internalSlotsList is a
The abstract operation OrdinaryCreateFromConstructor creates an ordinary object whose [[Prototype]] value is retrieved from a prototype property, if it exists. Otherwise the intrinsic named by intrinsicDefaultProto is used for [[Prototype]]. The optional internalSlotsList is a
The abstract operation GetPrototypeFromConstructor determines the [[Prototype]] value that should be used to create an object corresponding to a specific prototype property, if it exists. Otherwise the intrinsic named by intrinsicDefaultProto is used for [[Prototype]]. This abstract operation performs the following steps:
"prototype").If constructor does not supply a [[Prototype]] value, the default value that is used is obtained from the
ECMAScript function objects encapsulate parameterized ECMAScript code closed over a lexical environment and support the dynamic evaluation of that code. An ECMAScript
ECMAScript function objects have the additional internal slots listed in
| Internal Slot | Type | Description |
|---|---|---|
| [[Environment]] |
|
The |
| [[FormalParameters]] |
|
The root parse node of the source text that defines the function's formal parameter list. |
| [[FunctionKind]] | String |
Either "normal", "classConstructor", "generator", or "async".
|
| [[ECMAScriptCode]] |
|
The root parse node of the source text that defines the function's body. |
| [[ConstructorKind]] | String |
Either "base" or "derived".
|
| [[Realm]] |
|
The |
| [[ScriptOrModule]] |
|
The script or module in which the function was created. |
| [[ThisMode]] | (lexical, strict, global) |
Defines how this references are interpreted within the formal parameters and code body of the function. this refers to the |
| [[Strict]] | Boolean |
|
| [[HomeObject]] | Object |
If the function uses super, this is the object whose [[GetPrototypeOf]] provides the object where super property lookups begin.
|
All ECMAScript function objects have the [[Call]] internal method defined here. ECMAScript functions that are also constructors in addition have the [[Construct]] internal method.
The [[Call]] internal method for an ECMAScript
"classConstructor", throw a When calleeContext is removed from the
When the abstract operation PrepareForOrdinaryCall is called with
When the abstract operation OrdinaryCallBindThis is called with
"initialized".When the abstract operation OrdinaryCallEvaluateBody is called with
The [[Construct]] internal method for an ECMAScript
"base", then"%ObjectPrototype%")."base", perform "base", return The abstract operation FunctionAllocate requires the three arguments functionPrototype, strict and functionKind. FunctionAllocate performs the following steps:
"normal", "non-constructor", "generator", "async", or "async generator"."normal", let needsConstruct be "non-constructor", set functionKind to "normal"."base".The abstract operation FunctionInitialize requires the arguments: a
The abstract operation FunctionCreate requires the arguments: kind which is one of (Normal, Method, Arrow), a parameter list
"non-constructor"."normal".The abstract operation GeneratorFunctionCreate requires the arguments: kind which is one of (Normal, Method), a parameter list
"generator").The abstract operation AsyncGeneratorFunctionCreate requires the arguments: kind which is one of (
"generator").The abstract operation AsyncFunctionCreate requires the arguments: kind which is one of (
"async").The abstract operation AddRestrictedFunctionProperties is called with a
"caller", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: "arguments", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: The %ThrowTypeError% intrinsic is an anonymous built-in
The value of the [[Extensible]] internal slot of a %ThrowTypeError% function is
The length property of a %ThrowTypeError% function has the attributes { [[Writable]]:
The abstract operation MakeConstructor requires a Function argument F and optionally, a Boolean writablePrototype and an object prototype. If prototype is provided it is assumed to already contain, if needed, a "constructor" property whose value is F. This operation converts F into a
prototype own property."constructor", PropertyDescriptor { [[Value]]: F, [[Writable]]: writablePrototype, [[Enumerable]]: "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: writablePrototype, [[Enumerable]]: The abstract operation MakeClassConstructor with argument F performs the following steps:
"normal"."classConstructor".The abstract operation MakeMethod with arguments F and homeObject configures F as a method by performing the following steps:
The abstract operation SetFunctionName requires a Function argument F, a String or Symbol argument name and optionally a String argument prefix. This operation adds a name property to F by performing the following steps:
name own property."[", description, and "]"."name", PropertyDescriptor { [[Value]]: name, [[Writable]]: The abstract operation SetFunctionLength requires a Function argument F and a Number argument length. This operation adds a length property to F by performing the following steps:
length own property."length", PropertyDescriptor{[[Value]]: length, [[Writable]]: When an
FunctionDeclarationInstantiation is performed as follows using arguments func and argumentsList. func is the
"arguments" is an element of parameterNames, then"arguments" is an element of functionNames or if "arguments" is an element of lexicalNames, then"arguments", "arguments", "arguments", ao)."arguments" appended.Parameter
The built-in function objects defined in this specification may be implemented as either ECMAScript function objects (
If a built-in
Unless otherwise specified every built-in
The behaviour specified for each built-in function via algorithm steps or other means is the specification of the function body behaviour for both [[Call]] and [[Construct]] invocations of the function. However, [[Construct]] invocation is not supported by all built-in functions. For each built-in function, when invoked with [[Call]], the [[Call]] thisArgument provides the "classConstructor".
Built-in function objects that are not identified as constructors do not implement the [[Construct]] internal method unless otherwise specified in the description of a particular function. When a built-in new expression the argumentsList parameter of the invoked [[Construct]] internal method provides the values for the built-in
Built-in functions that are not constructors do not have a prototype property unless otherwise specified in the description of a particular function.
If a built-in
The [[Call]] internal method for a built-in
When calleeContext is removed from the
The [[Construct]] internal method for built-in
The abstract operation CreateBuiltinFunction takes arguments steps, internalSlotsList, realm, and prototype. The argument internalSlotsList is a
Each built-in function defined in this specification is created by calling the CreateBuiltinFunction abstract operation.
This specification defines several kinds of built-in exotic objects. These objects generally behave similar to ordinary objects except for a few specific situations. The following exotic objects use the ordinary object internal methods except where it is explicitly specified otherwise below:
A bound function is an
Bound function objects do not have the internal slots of ECMAScript function objects defined in
| Internal Slot | Type | Description |
|---|---|---|
| [[BoundTargetFunction]] | Callable Object |
The wrapped |
| [[BoundThis]] | Any |
The value that is always passed as the |
| [[BoundArguments]] |
|
A list of values whose elements are used as the first arguments to any call to the wrapped function. |
Bound function objects provide all of the essential internal methods as specified in
When the [[Call]] internal method of a
When the [[Construct]] internal method of a
The abstract operation BoundFunctionCreate with arguments targetFunction, boundThis and boundArgs is used to specify the creation of new Bound Function exotic objects. It performs the following steps:
An Array object is an length property whose value is always a nonnegative length property is numerically greater than the name of every own property whose name is an length property is changed, if necessary, to be one more than the numeric value of that length property is changed, every own property whose name is an length or
A String
Array exotic objects always have a non-configurable property named "length".
Array exotic objects provide an alternative definition for the [[DefineOwnProperty]] internal method. Except for that internal method, Array exotic objects provide all of the other essential internal methods as specified in
When the [[DefineOwnProperty]] internal method of an Array
"length", then"length")."length", oldLenDesc).The abstract operation ArrayCreate with argument length (either 0 or a positive
"length", PropertyDescriptor{[[Value]]: length, [[Writable]]: The abstract operation ArraySpeciesCreate with arguments originalArray and length is used to specify the creation of a new Array object using a
"constructor").If originalArray was created using the standard built-in Array
When the abstract operation ArraySetLength is called with an Array
"length", Desc)."length")."length", newLenDesc)."length", newLenDesc)."length", newLenDesc)."length", PropertyDescriptor { [[Writable]]: In steps 3 and 4, if Desc.[[Value]] is an object then its valueOf method is called twice. This is legacy behaviour that was specified with this effect starting with the 2nd Edition of this specification.
A String object is an "length" whose value is the number of code unit elements in the encapsulated String value. Both the code unit data properties and the "length" property are non-writable and non-configurable.
String exotic objects have the same internal slots as ordinary objects. They also have a [[StringData]] internal slot.
String exotic objects provide alternative definitions for the following internal methods. All of the other String
When the [[GetOwnProperty]] internal method of a String
When the [[DefineOwnProperty]] internal method of a String
When the [[OwnPropertyKeys]] internal method of a String
The abstract operation StringCreate with arguments value and prototype is used to specify the creation of new String exotic objects. It performs the following steps:
"length", PropertyDescriptor { [[Value]]: length, [[Writable]]: The abstract operation StringGetOwnProperty called with arguments S and P performs the following steps:
Most ECMAScript functions make an arguments object available to their code. Depending upon the characteristics of the function definition, its arguments object is either an ordinary object or an arguments
Arguments exotic objects have the same internal slots as ordinary objects. They also have a [[ParameterMap]] internal slot. Ordinary arguments objects also have a [[ParameterMap]] internal slot whose value is always undefined. For ordinary argument objects the [[ParameterMap]] internal slot is only used by Object.prototype.toString (
Arguments exotic objects provide alternative definitions for the following internal methods. All of the other arguments
The
The ParameterMap object and its property values are used as a device for specifying the arguments object correspondence to argument bindings. The ParameterMap object and the objects that are the values of its properties are not directly observable from ECMAScript code. An ECMAScript implementation does not need to actually create or use such objects to implement the specified semantics.
Ordinary arguments objects define a non-configurable "callee" which throws a "callee" property has a more specific meaning for arguments exotic objects, which are created only for some class of non-strict functions. The definition of this property in the ordinary variant exists to ensure that it is not defined in any other manner by conforming ECMAScript implementations.
ECMAScript implementations of arguments exotic objects have historically contained an "caller". Prior to ECMAScript 2017, this specification included the definition of a throwing "caller" property on ordinary arguments objects. Since implementations do not contain this extension any longer, ECMAScript 2017 dropped the requirement for a throwing "caller" accessor.
The [[GetOwnProperty]] internal method of an arguments
The [[DefineOwnProperty]] internal method of an arguments
The [[Get]] internal method of an arguments
The [[Set]] internal method of an arguments
The [[Delete]] internal method of an arguments
The abstract operation CreateUnmappedArgumentsObject called with an argument argumentsList performs the following steps:
"length", PropertyDescriptor { [[Value]]: len, [[Writable]]: "callee", PropertyDescriptor { [[Get]]: The abstract operation CreateMappedArgumentsObject is called with object func,
"length", PropertyDescriptor { [[Value]]: len, [[Writable]]: "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: The abstract operation MakeArgGetter called with String name and
An ArgGetter function is an anonymous built-in function with [[Name]] and [[Env]] internal slots. When an ArgGetter function f that expects no arguments is called it performs the following steps:
ArgGetter functions are never directly accessible to ECMAScript code.
The abstract operation MakeArgSetter called with String name and
An ArgSetter function is an anonymous built-in function with [[Name]] and [[Env]] internal slots. When an ArgSetter function f is called with argument value it performs the following steps:
ArgSetter functions are never directly accessible to ECMAScript code.
An Integer-Indexed exotic object is an
When the [[GetOwnProperty]] internal method of an
When the [[HasProperty]] internal method of an
When the [[DefineOwnProperty]] internal method of an
When the [[Get]] internal method of an
When the [[Set]] internal method of an
When the [[OwnPropertyKeys]] internal method of an
The abstract operation IntegerIndexedObjectCreate with arguments prototype and internalSlotsList is used to specify the creation of new
The abstract operation IntegerIndexedElementGet with arguments O and index performs the following steps:
"Unordered").The abstract operation IntegerIndexedElementSet with arguments O, index, and value performs the following steps:
"Unordered").A module namespace object is an export * export items. Each String-valued own property key is the StringValue of the corresponding exported binding name. These are the only String-keyed properties of a module namespace
Module namespace objects have the internal slots defined in
| Internal Slot | Type | Description |
|---|---|---|
| [[Module]] |
|
The |
| [[Exports]] |
|
A Array.prototype.sort using |
| [[Prototype]] | Null |
This slot always contains the value |
Module namespace exotic objects provide alternative definitions for all of the internal methods except [[GetPrototypeOf]], which behaves as defined in
When the [[SetPrototypeOf]] internal method of a module namespace
When the [[IsExtensible]] internal method of a module namespace
When the [[PreventExtensions]] internal method of a module namespace
When the [[GetOwnProperty]] internal method of a module namespace
When the [[DefineOwnProperty]] internal method of a module namespace
When the [[HasProperty]] internal method of a module namespace
When the [[Get]] internal method of a module namespace
ResolveExport is idempotent and side-effect free. An implementation might choose to pre-compute or cache the ResolveExport results for the [[Exports]] of each module namespace
When the [[Set]] internal method of a module namespace
When the [[Delete]] internal method of a module namespace
When the [[OwnPropertyKeys]] internal method of a module namespace
The abstract operation ModuleNamespaceCreate with arguments module, and exports is used to specify the creation of new module namespace exotic objects. It performs the following steps:
Array.prototype.sort using An immutable prototype exotic object is an
Immutable prototype exotic objects have the same internal slots as ordinary objects. They are exotic only in the following internal methods. All other internal methods of immutable prototype exotic objects that are not explicitly defined below are instead defined as in ordinary objects.
When the [[SetPrototypeOf]] internal method of an
When the SetImmutablePrototype abstract operation is called with arguments O and V, the following steps are taken:
A proxy object is an
| Internal Method | Handler Method |
|---|---|
| [[GetPrototypeOf]] |
getPrototypeOf
|
| [[SetPrototypeOf]] |
setPrototypeOf
|
| [[IsExtensible]] |
isExtensible
|
| [[PreventExtensions]] |
preventExtensions
|
| [[GetOwnProperty]] |
getOwnPropertyDescriptor
|
| [[DefineOwnProperty]] |
defineProperty
|
| [[HasProperty]] |
has
|
| [[Get]] |
get
|
| [[Set]] |
set
|
| [[Delete]] |
deleteProperty
|
| [[OwnPropertyKeys]] |
ownKeys
|
| [[Call]] |
apply
|
| [[Construct]] |
construct
|
When a handler method is called to provide the implementation of a proxy object internal method, the handler method is passed the proxy's target object as a parameter. A proxy's handler object does not necessarily have a method corresponding to every essential internal method. Invoking an internal method on the proxy results in the invocation of the corresponding internal method on the proxy's target object if the handler object does not have a method corresponding to the internal trap.
The [[ProxyHandler]] and [[ProxyTarget]] internal slots of a proxy object are always initialized when the object is created and typically may not be modified. Some proxy objects are created in a manner that permits them to be subsequently revoked. When a proxy is revoked, its [[ProxyHandler]] and [[ProxyTarget]] internal slots are set to
Because proxy objects permit the implementation of internal methods to be provided by arbitrary ECMAScript code, it is possible to define a proxy object whose handler methods violates the invariants defined in
In the following algorithm descriptions, assume O is an ECMAScript proxy object, P is a property key value, V is any
When the [[GetPrototypeOf]] internal method of a Proxy
"getPrototypeOf").[[GetPrototypeOf]] for proxy objects enforces the following invariants:
When the [[SetPrototypeOf]] internal method of a Proxy
"setPrototypeOf").[[SetPrototypeOf]] for proxy objects enforces the following invariants:
When the [[IsExtensible]] internal method of a Proxy
"isExtensible").[[IsExtensible]] for proxy objects enforces the following invariants:
When the [[PreventExtensions]] internal method of a Proxy
"preventExtensions").[[PreventExtensions]] for proxy objects enforces the following invariants:
When the [[GetOwnProperty]] internal method of a Proxy
"getOwnPropertyDescriptor").[[GetOwnProperty]] for proxy objects enforces the following invariants:
When the [[DefineOwnProperty]] internal method of a Proxy
"defineProperty").[[DefineOwnProperty]] for proxy objects enforces the following invariants:
When the [[HasProperty]] internal method of a Proxy
"has").[[HasProperty]] for proxy objects enforces the following invariants:
When the [[Get]] internal method of a Proxy
"get").[[Get]] for proxy objects enforces the following invariants:
When the [[Set]] internal method of a Proxy
"set").[[Set]] for proxy objects enforces the following invariants:
When the [[Delete]] internal method of a Proxy
"deleteProperty").[[Delete]] for proxy objects enforces the following invariants:
When the [[OwnPropertyKeys]] internal method of a Proxy
"ownKeys").[[OwnPropertyKeys]] for proxy objects enforces the following invariants:
The [[Call]] internal method of a Proxy
"apply").A Proxy
The [[Construct]] internal method of a Proxy
"construct").A Proxy
[[Construct]] for proxy objects enforces the following invariants:
The abstract operation ProxyCreate with arguments target and handler is used to specify the creation of new Proxy exotic objects. It performs the following steps:
ECMAScript code is expressed using Unicode. ECMAScript source text is a sequence of code points. All Unicode code point values from U+0000 to U+10FFFF, including surrogate code points, may occur in source text where permitted by the ECMAScript grammars. The actual encodings used to store and interchange ECMAScript source text is not relevant to this specification. Regardless of the external source text encoding, a conforming ECMAScript implementation processes the source text as if it was an equivalent sequence of
The components of a combining character sequence are treated as individual Unicode code points even though a user might think of the whole sequence as a single character.
In string literals, regular expression literals, template literals and identifiers, any Unicode code point may also be expressed using Unicode escape sequences that explicitly express a code point's numeric value. Within a comment, such an escape sequence is effectively ignored as part of the comment.
ECMAScript differs from the Java programming language in the behaviour of Unicode escape sequences. In a Java program, if the Unicode escape sequence \u000A, for example, occurs within a single-line comment, it is interpreted as a line terminator (Unicode code point U+000A is LINE FEED (LF)) and therefore the next code point is not part of the comment. Similarly, if the Unicode escape sequence \u000A occurs within a string literal in a Java program, it is likewise interpreted as a line terminator, which is not allowed within a string literal—one must write \n instead of \u000A to cause a LINE FEED (LF) to be part of the String value of a string literal. In an ECMAScript program, a Unicode escape sequence occurring within a comment is never interpreted and therefore cannot contribute to termination of the comment. Similarly, a Unicode escape sequence occurring within a string literal in an ECMAScript program always contributes to the literal and is never interpreted as a line terminator or as a code point that might terminate the string literal.
The UTF16Encoding of a numeric code point value, cp, is determined as follows:
Two code units, lead and trail, that form a UTF-16
There are four types of ECMAScript code:
eval function. More precisely, if the parameter to the built-in eval function is a String, it is treated as an ECMAScript eval is the global code portion of that Function code is generally provided as the bodies of Function Definitions (Function GeneratorFunction AsyncFunction
An ECMAScript
eval is a Function, Generator, AsyncFunction, and AsyncGenerator constructors is strict mode code if the last argument is a String that when processed is a ECMAScript code that is not strict mode code is called non-strict code.
An ECMAScript implementation may support the evaluation of function exotic objects whose evaluative behaviour is expressed in some implementation-defined form of executable code other than via ECMAScript code. Whether a
The source text of an ECMAScript
There are several situations where the identification of lexical input elements is sensitive to the syntactic grammar context that is consuming the input elements. This requires multiple goal symbols for the lexical grammar. The
The use of multiple lexical goals ensures that there are no lexical ambiguities that would affect automatic semicolon insertion. For example, there are no syntactic grammar contexts where both a leading division or division-assignment, and a leading
a = b
/hi/g.exec(c).map(d);
where the first non-whitespace, non-comment code point after a
a = b / hi / g.exec(c).map(d);
The Unicode format-control characters (i.e., the characters in category “Cf” in the Unicode Character Database such as LEFT-TO-RIGHT MARK or RIGHT-TO-LEFT MARK) are control codes used to control the formatting of a range of text in the absence of higher-level protocols for this (such as mark-up languages).
It is useful to allow format-control characters in source text to facilitate editing and display. All format control characters may be used within comments, and within string literals, template literals, and regular expression literals.
U+200C (ZERO WIDTH NON-JOINER) and U+200D (ZERO WIDTH JOINER) are format-control characters that are used to make necessary distinctions when forming words or phrases in certain languages. In ECMAScript source text these code points may also be used in an
U+FEFF (ZERO WIDTH NO-BREAK SPACE) is a format-control character used primarily at the start of a text to mark it as Unicode and to allow detection of the text's encoding and byte order. <ZWNBSP> characters intended for this purpose can sometimes also appear after the start of a text, for example as a result of concatenating files. In ECMAScript source text <ZWNBSP> code points are treated as white space characters (see
The special treatment of certain format-control characters outside of comments, string literals, and regular expression literals is summarized in
| Code Point | Name | Abbreviation | Usage |
|---|---|---|---|
U+200C
|
ZERO WIDTH NON-JOINER | <ZWNJ> |
|
U+200D
|
ZERO WIDTH JOINER | <ZWJ> |
|
U+FEFF
|
ZERO WIDTH NO-BREAK SPACE | <ZWNBSP> |
|
White space code points are used to improve source text readability and to separate tokens (indivisible lexical units) from each other, but are otherwise insignificant. White space code points may occur between any two tokens and at the start or end of input. White space code points may occur within a
The ECMAScript white space code points are listed in
| Code Point | Name | Abbreviation |
|---|---|---|
U+0009
|
CHARACTER TABULATION | <TAB> |
U+000B
|
LINE TABULATION | <VT> |
U+000C
|
FORM FEED (FF) | <FF> |
U+0020
|
SPACE | <SP> |
U+00A0
|
NO-BREAK SPACE | <NBSP> |
U+FEFF
|
ZERO WIDTH NO-BREAK SPACE | <ZWNBSP> |
| Other category “Zs” | Any other Unicode “Space_Separator” code point | <USP> |
ECMAScript implementations must recognize as
Other than for the code points listed in
Like white space code points, line terminator code points are used to improve source text readability and to separate tokens (indivisible lexical units) from each other. However, unlike white space code points, line terminators have some influence over the behaviour of the syntactic grammar. In general, line terminators may occur between any two tokens, but there are a few places where they are forbidden by the syntactic grammar. Line terminators also affect the process of automatic semicolon insertion (
A line terminator can occur within a
Line terminators are included in the set of white space code points that are matched by the \s class in regular expressions.
The ECMAScript line terminator code points are listed in
| Code Point | Unicode Name | Abbreviation |
|---|---|---|
U+000A
|
LINE FEED (LF) | <LF> |
U+000D
|
CARRIAGE RETURN (CR) | <CR> |
U+2028
|
LINE SEPARATOR | <LS> |
U+2029
|
PARAGRAPH SEPARATOR | <PS> |
Only the Unicode code points in
Comments can be either single or multi-line. Multi-line comments cannot nest.
Because a single-line comment can contain any Unicode code point except a // marker to the end of the line. However, the
Comments behave like white space and are discarded except that, if a
The
This standard specifies specific code point additions: U+0024 (DOLLAR SIGN) and U+005F (LOW LINE) are permitted anywhere in an
Unicode escape sequences are permitted in an \ preceding the u and { } code units, if they appear, do not contribute code points to the \
Two
The definitions of the nonterminal
The nonterminal _ via
The sets of code points with Unicode properties “ID_Start” and “ID_Continue” include, respectively, the code points with Unicode properties “Other_ID_Start” and “Other_ID_Continue”.
"$", or "_", or the "$", or "_", or the \ A
The \
The following tokens are ECMAScript keywords and may not be used as
In some contexts yield and await are given the semantics of an let and static are treated as reserved words through static semantic restrictions (see
The following tokens are reserved for use as keywords in future language extensions.
Use of the following tokens within
implements
|
package
|
protected
|
|
interface
|
private
|
public
|
The
For example: 3in is an error and not the two input elements 3 and in.
A conforming implementation, when processing
A numeric literal stands for a value of the Number type. This value is determined in two steps: first, a
Once the exact MV for a numeric literal has been determined, it is then rounded to a value of the Number type. If the MV is 0, then the rounded value is 0 digit or the 0 digit and then incrementing the literal at the 20th significant digit position. A digit is significant if it is not part of an
0; or
A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+2028 (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded as defined in
A conforming implementation, when processing
The definition of the nonterminal
A line terminator code point cannot appear in a string literal, except as part of a \n or \u000A.
A string literal stands for a value of the String type. The String value (SV) of the literal is described in terms of code unit values contributed by the various parts of the string literal. As part of this process, some Unicode code points within the string literal are interpreted as having a
| Escape Sequence | Code Unit Value | Unicode Character Name | Symbol |
|---|---|---|---|
\b
|
0x0008
|
BACKSPACE | <BS> |
\t
|
0x0009
|
CHARACTER TABULATION | <HT> |
\n
|
0x000A
|
LINE FEED (LF) | <LF> |
\v
|
0x000B
|
LINE TABULATION | <VT> |
\f
|
0x000C
|
FORM FEED (FF) | <FF> |
\r
|
0x000D
|
CARRIAGE RETURN (CR) | <CR> |
\"
|
0x0022
|
QUOTATION MARK |
"
|
\'
|
0x0027
|
APOSTROPHE |
'
|
\\
|
0x005C
|
REVERSE SOLIDUS |
\
|
A regular expression literal is an input element that is converted to a RegExp object (see === to each other even if the two literals' contents are identical. A RegExp object may also be created at runtime by new RegExp or calling the RegExp
The productions below describe the syntax for a regular expression literal and are used by the input element scanner to find the end of the regular expression literal. The source text comprising the
An implementation may extend the ECMAScript Regular Expression grammar defined in
Regular expression literals may not be empty; instead of representing an empty regular expression literal, the code unit sequence // starts a single-line comment. To specify an empty regular expression, use: /(?:)/.
A conforming implementation must not use the extended definition of
A template literal component is interpreted as a sequence of Unicode code points. The Template Value (TV) of a literal component is described in terms of code unit values (SV,
TV excludes the code units of
Most ECMAScript statements and declarations must be terminated with a semicolon. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
In the following rules, “token” means the actual recognized lexical token determined using the current lexical
There are three basic rules of semicolon insertion:
When, as the source text is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
}.
) and the inserted semicolon would then be parsed as the terminating semicolon of a do-while statement (However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see
The following are the only restricted productions in the grammar:
The practical effect of these restricted productions is as follows:
++ or -- token is encountered where the parser would treat it as a postfix operator, and at least one ++ or -- token, then a semicolon is automatically inserted before the ++ or -- token.
continue, break, return, throw, or yield token is encountered and a continue, break, return, throw, or yield token.
The resulting practical advice to ECMAScript programmers is:
++ or -- operator should appear on the same line as its operand.
return or throw statement or an yield expression should start on the same line as the return, throw, or yield token.
break or continue statement should be on the same line as the break or continue token.
The source
{ 1 2 } 3
is not a valid sentence in the ECMAScript grammar, even with the automatic semicolon insertion rules. In contrast, the source
{ 1
2 } 3
is also not a valid ECMAScript sentence, but is transformed by automatic semicolon insertion into the following:
{ 1
;2 ;} 3;
which is a valid ECMAScript sentence.
The source
for (a; b
)
is not a valid ECMAScript sentence and is not altered by automatic semicolon insertion because the semicolon is needed for the header of a for statement. Automatic semicolon insertion never inserts one of the two semicolons in the header of a for statement.
The source
return
a + b
is transformed by automatic semicolon insertion into the following:
return;
a + b;
The expression a + b is not treated as a value to be returned by the return statement, because a return.
The source
a = b
++c
is transformed by automatic semicolon insertion into the following:
a = b;
++c;
The token ++ is not treated as a postfix operator applying to the variable b, because a b and ++.
The source
if (a > b)
else c = d
is not a valid ECMAScript sentence and is not altered by automatic semicolon insertion before the else token, even though no production of the grammar applies at that point, because an automatically inserted semicolon would then be parsed as an empty statement.
The source
a = b + c
(d + e).print()
is not transformed by automatic semicolon insertion, because the parenthesized expression that begins the second line can be interpreted as an argument list for a function call:
a = b + c(d + e).print()
In the circumstance that an assignment statement must begin with a left parenthesis, it is a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement rather than to rely on automatic semicolon insertion.
yield and await are permitted as
let
await 0;
"arguments" or "eval".
"yield".
"await".
"implements", "interface", "let", "package", "private", "protected", "public", "static", or "yield".
"await".
yield or await.
StringValue of
"yield"."await"."eval" or "arguments", return "yield"."await".With parameters value and environment.
var statements and formal parameter lists of some non-strict functions (See
"yield", value, environment)."await", value, environment)."yield")."await").The result of evaluating an
In yield may be used as an identifier. Evaluating the yield as if it was an
When processing an instance of the production
the interpretation of
this KeywordSee
false, return true, return An
Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an
With parameters array and nextIndex.
"length", "length", "length", An object initializer is an expression describing the initialization of an Object, written in a form resembling a literal. It is a list of zero or more pairs of property keys and associated values, enclosed in curly brackets. The values need not be literals; they are evaluated each time the object initializer is evaluated.
In certain contexts,
In addition to describing an actual object initializer the
This production exists so that
With parameter symbol.
With parameter symbol.
Static semantic rules that depend upon substructure generally do not look into function definitions.
With parameters object and enumerable.
"name").An alternative semantics for this production is given in
See
See
See
See
See
See
"g", "i", "m", "s", "u", or "y", or if it contains the same code point more than once.
With parameter raw.
The abstract operation GetTemplateObject is called with a
"frozen")."raw", PropertyDescriptor { [[Value]]: rawObj, [[Writable]]: "frozen").The creation of a template object cannot result in an
Each
Future editions of this specification may define additional non-enumerable properties of template objects.
The string conversion semantics applied to the String.prototype.concat rather than the + operator.
The string conversion semantics applied to the String.prototype.concat rather than the + operator.
The string conversion semantics applied to the String.prototype.concat rather than the + operator.
This algorithm does not apply delete and typeof may be applied to parenthesized expressions.
When processing an instance of the production
With parameter symbol.
super, return Properties are accessed by name, using either the dot notation:
or the bracket notation:
The dot notation is explained by the following syntactic conversion:
is identical in its behaviour to
and similarly
is identical in its behaviour to
where <identifier-name-string> is the result of evaluating StringValue of
Is evaluated in exactly the same manner as
Is evaluated in exactly the same manner as
new OperatorThe abstract operation EvaluateNew with arguments constructExpr, and arguments performs the following steps:
"eval", thenA
The abstract operation EvaluateCall takes as arguments a value func, a value ref, a
super KeywordThe abstract operation GetSuperConstructor performs the following steps:
The abstract operation MakeSuperPropertyReference with arguments propertyKey and strict performs the following steps:
The evaluation of an argument list produces a
A tagged template is a function call where the arguments of the call are derived from a
+ operator (see - operator (see + operator (see - operator (see delete OperatorIt is a Syntax Error if the derived
and
The last rule means that expressions such as delete (((foo))) produce early errors because of recursive application of the first rule.
When a delete operator occurs within delete operator occurs within
void Operatortypeof Operator"undefined".| Type of val | Result |
|---|---|
| Undefined |
"undefined"
|
| Null |
"object"
|
| Boolean |
"boolean"
|
| Number |
"number"
|
| String |
"string"
|
| Symbol |
"symbol"
|
| Object (ordinary and does not implement [[Call]]) |
"object"
|
| Object (standard exotic and does not implement [[Call]]) |
"object"
|
| Object (implements [[Call]]) |
"function"
|
| Object (non-standard exotic and does not implement [[Call]]) |
Implementation-defined. Must not be "undefined", "boolean", "function", "number", "symbol", or "string".
|
Implementations are discouraged from defining new typeof result values for non-standard exotic objects. If possible "object" should be used for such objects.
+ OperatorThe unary + operator converts its operand to Number type.
- OperatorThe unary - operator converts its operand to Number type and then negates it. Negating
~ )! )** OperatorReturns an implementation-dependent approximation of the result of raising base to the power exponent.
The result of base ** exponent when base is
*, /, or %) to lnum and rnum as specified in * OperatorThe *
The result of a floating-point multiplication is governed by the rules of IEEE 754-2008 binary double-precision arithmetic:
/ OperatorThe /
% OperatorThe %
In C and C++, the remainder operator accepts only integral operands; in ECMAScript, it also accepts floating-point operands.
The result of a floating-point remainder operation as computed by the % operator is not the same as the “remainder” operation defined by IEEE 754-2008. The IEEE 754-2008 “remainder” operation computes the remainder from a rounding division, not a truncating division, and so its behaviour is not analogous to that of the usual % on floating-point operations to behave in a manner analogous to that of the Java
The result of an ECMAScript floating-point remainder operation is determined by the rules of IEEE arithmetic:
+ )The addition operator either performs string concatenation or numeric addition.
No hint is provided in the calls to
Step 7 differs from step 3 of the
- )The + operator performs addition when applied to two operands of numeric type, producing the sum of the operands. The - operator performs subtraction, producing the difference of two numeric operands.
Addition is a commutative operation, but not always associative.
The result of an addition is determined using the rules of IEEE 754-2008 binary double-precision arithmetic:
The - operator performs subtraction when applied to two operands of numeric type, producing the difference of its operands; the left operand is the minuend and the right operand is the subtrahend. Given numeric operands a and b, it is always the case that a-b produces the same result as a+(-b).
<< )Performs a bitwise left shift operation on the left operand by the amount specified by the right operand.
>> )Performs a sign-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
>>> )Performs a zero-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
The result of evaluating a relational operator is always of type Boolean, reflecting whether the relationship named by the operator holds between its two operands.
The [In] grammar parameter is needed to avoid confusing the in operator in a relational expression with the in operator in a for statement.
The abstract operation InstanceofOperator(V, target) implements the generic algorithm for determining if ECMAScript value V is an instance of object target either by consulting target's @@hasinstance method or, if absent, determining whether the value of target's prototype property is present in V's prototype chain. This abstract operation performs the following steps:
Steps 4 and 5 provide compatibility with previous editions of ECMAScript that did not use a @@hasInstance method to define the instanceof operator semantics. If an object does not define or inherit @@hasInstance it uses the default instanceof semantics.
The result of evaluating an equality operator is always of type Boolean, reflecting whether the relationship named by the operator holds between its two operands.
Given the above definition of equality:
"" + a == "" + b.
+a == +b.
!a == !b.
The equality operators maintain the following invariants:
A != B is equivalent to !(A == B).
A == B is equivalent to B == A, except in the order of evaluation of A and B.
The equality operator is not always transitive. For example, there might be two distinct String objects, each representing the same String value; each String object would be considered equal to the String value by the == operator, but the two String objects would not be equal to each other. For example:
new String("a") == "a" and "a" == new String("a") are both new String("a") == new String("a") is Comparison of Strings uses a simple equality test on sequences of code unit values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore Strings values that are canonically equal according to the Unicode standard could test as unequal. In effect this algorithm assumes that both Strings are already in normalized form.
The production
The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
? : )The grammar for a
"name").@ where @=.When an assignment occurs within
In certain circumstances when processing an instance of the production
With parameter value.
With parameter value.
"name").With parameters value and excludedNames.
With parameter iteratorRecord.
"name").Left to right evaluation order is maintained by evaluating a
With parameters value and propertyName.
"name")., )With parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
With parameter labelSet.
A
With parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.
At the top level of a function or script, inner function declarations are treated like var declarations.
No matter how control leaves the
The value of a eval function all return the value 1:
eval("1;;;;;")
eval("1;{}")
eval("1;var a;")
When a
BlockDeclarationInstantiation is performed as follows using arguments code and env. code is the
let and const declarations define variables that are scoped to the let declaration does not have an
"let".
A const declaration.
"name").A var statement declares variables that are scoped to the
"name").If a
With parameters value and environment.
When
With parameters value and environment.
With parameters value, environment, and excludedNames.
With parameters iteratorRecord and environment.
When
"name").With parameters value, environment, and propertyName.
When
"name").An function or class keywords because that would make it ambiguous with a async function because that would make it ambiguous with an let [ because that would make it ambiguous with a let
if StatementEach else for which the choice of associated if is ambiguous shall be associated with the nearest possible if that would otherwise have no corresponding else.
It is only necessary to apply this rule if the extension specified in
With parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
This section is extended by Annex
It is only necessary to apply this rule if the extension specified in
The abstract operation LoopContinues with arguments completion and labelSet is defined by the following steps:
Within the
do-while StatementWith parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
With parameter labelSet.
while StatementWith parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
With parameter labelSet.
for StatementWith parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
With parameter labelSet.
The abstract operation ForBodyEvaluation with arguments test, increment, stmt, perIterationBindings, and labelSet is performed as follows:
The abstract operation CreatePerIterationEnvironment with argument perIterationBindings is performed as follows:
for-in, for-of, and for-await-of StatementsIf
The last rule means that the other rules are applied even if parentheses surround
"let".
With parameter labelSet.
This section is extended by Annex
With parameter labelSet.
This section is extended by Annex
With parameters iterationSet and labelSet.
This section is extended by Annex
This section is extended by Annex
This section is extended by Annex
This section is extended by Annex
With parameters value and environment.
var statements and the formal parameter lists of some non-strict functions (see
With parameter environment.
With parameter labelSet.
This section is extended by Annex
The abstract operation ForIn/OfHeadEvaluation is called with arguments TDZnames, expr, and iterationKind. The value of iterationKind is either
The abstract operation ForIn/OfBodyEvaluation is called with arguments lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet, and optional argument iteratorKind. The value of lhsKind is either
When the abstract operation EnumerateObjectProperties is called with argument O, the following steps are taken:
next method iterates over all the String-valued keys of enumerable properties of O. The iterator object is never directly accessible to ECMAScript code. The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.The iterator's throw and return methods are next method processes object properties to determine whether the property key should be returned as an iterator value. Returned property keys do not include keys that are Symbols. Properties of the target object may be deleted during enumeration. A property that is deleted before it is processed by the iterator's next method is ignored. If new properties are added to the target object during enumeration, the newly added properties are not guaranteed to be processed in the active enumeration. A next method at most once in any enumeration.
Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively; but a property of a prototype is not processed if it has the same name as a property that has already been processed by the iterator's next method. The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object has already been processed. The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the prototype object as the argument. EnumerateObjectProperties must obtain the own property keys of the target object by calling its [[OwnPropertyKeys]] internal method. Property attributes of the target object must be obtained by calling its [[GetOwnProperty]] internal method.
The following is an informative definition of an ECMAScript generator function that conforms to these rules:
function* EnumerateObjectProperties(obj) {
const visited = new Set();
for (const key of Reflect.ownKeys(obj)) {
if (typeof key === "symbol") continue;
const desc = Reflect.getOwnPropertyDescriptor(obj, key);
if (desc) {
visited.add(key);
if (desc.enumerable) yield key;
}
}
const proto = Reflect.getPrototypeOf(obj);
if (proto === null) return;
for (const protoKey of EnumerateObjectProperties(proto)) {
if (!visited.has(protoKey)) yield protoKey;
}
}
continue StatementWith parameters iterationSet and labelSet.
break StatementWith parameter labelSet.
return StatementA return statement causes a function to cease execution and, in most cases, returns a value to the caller. If return statement may not actually return a value to the caller depending on surrounding context. For example, in a try block, a return statement's completion record may be replaced with another completion record during evaluation of the finally block.
with StatementThe with statement adds an object
It is only necessary to apply the second rule if the extension specified in
With parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
No matter how control leaves the embedded
switch StatementWith parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
With parameter input.
The abstract operation CaseClauseIsSelected, given
This operation does not execute C's
No matter how control leaves the
A break and continue statements. ECMAScript has no goto statement. A
An alternative definition for this rule is provided in
With parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
The abstract operation IsLabelledFunction with argument stmt performs the following steps:
With parameter labelSet.
throw Statementtry StatementThe try statement encloses a block of code in which an exceptional condition can occur, such as a runtime error or a throw statement. The catch clause provides the exception-handling code. When a catch clause catches an exception, its
An alternative
With parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
With parameter thrownValue.
No matter how control leaves the
debugger StatementEvaluating a
A Directive Prologue is the longest sequence of
A Use Strict Directive is an "use strict" or 'use strict'. A
A
The
"eval" or "arguments".
The LexicallyDeclaredNames of a
Multiple occurrences of the same
"*default*" »."*default*" is used within this specification as a synthetic name for hoistable anonymous functions that are defined using export declarations.
With parameter symbol.
Static semantic rules that depend upon substructure generally do not look into function definitions.
The ExpectedArgumentCount of a
The abstract operation IsAnonymousFunctionDefinition determines if its argument is a function definition that does not bind a name. The argument expr is the result of parsing an
With parameters functionObject and
With parameters iteratorRecord and environment.
When
The new
The new
With parameter scope.
"default").An anonymous export default declaration, and its function code is therefore always
An alternative semantics is provided in
The
A prototype property is automatically created for every function defined using a
When the production
is recognized the following grammar is used to refine the interpretation of
With parameter symbol.
super or this, return Normally, Contains does not look inside most function forms. However, Contains is used to detect new.target, this, and super usage within an
With parameters iteratorRecord and environment.
When
With parameters functionObject and
An arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an super, the super is always contained within a non-super is accessible via the scope that is captured by the
With parameter symbol.
With parameters object and optional parameter functionPrototype.
With parameters object and enumerable.
"get")."set").The syntactic context immediately following yield requires use of the
"eval" or "arguments".
"*default*" »."*default*" is used within this specification as a synthetic name for hoistable anonymous functions that are defined using export declarations.
With parameter symbol.
With parameter symbol.
Static semantic rules that depend upon substructure generally do not look into function definitions.
With parameters functionObject and
"%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]] »).With parameter scope.
"prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "default").An anonymous export default declaration, and its function code is therefore always
With parameters object and enumerable.
"prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: The
"throw").throw method are propagated. Normal completions from an inner throw method are processed similarly to an inner next.throw method, this throw is going to terminate the yield* loop. But first we need to give iterator a chance to clean up.yield* protocol violation: iterator does not have a throw method."return").eval or the arguments."*default*" »."*default*" is used within this specification as a synthetic name for hoistable anonymous functions that are defined using export declarations.
With parameter symbol.
With parameter symbol.
Static semantic rules that depend upon substructure generally do not look into function definitions.
With parameters functionObject and
"%AsyncGeneratorPrototype%", « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]] »).With parameter scope.
"prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "default").An anonymous export default declaration.
With parameter object and enumerable.
"prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: The
A class definition is always
It is a Syntax Error if
"constructor".
"constructor" and HasDirectSuper of "constructor" and SpecialMethod of "prototype".
"*default*" »."constructor", return "constructor", return Early Error rules ensure that there is only one method definition named "constructor" and that it is not an
With parameter symbol.
Static semantic rules that depend upon substructure generally do not look into class bodies except for
With parameter symbol.
"constructor", return a new empty "constructor", return list.With parameter className.
constructor(... args){ super (...args);}
using the syntactic grammar with the constructor(){ }
using the syntactic grammar with the "derived"."constructor", F)."name")."name").If the class definition included a name static method then that method is not over-written with a name
await is parsed as an
When await is parsed as a await may be parsed as an identifier when the [Await] parameter is absent. This includes the following contexts:
Unlike
"eval" or "arguments"."*default*" ».*default*" is used within this specification as a synthetic name for hoistable anonymous functions that are defined using export declarations.With parameter symbol.
With parameter symbol.
With parameter scope.
"default").With parameters functionObject and
With parameters object and enumerable.
When processing an instance of the production
With parameter symbol.
super, or this, return super, or this, return new.target, this, and super usage within an AsyncArrowFunction.With parameters iteratorRecord and environment.
With parameters functionObject and
The abstract operation IsInTailPosition with argument call performs the following steps:
Tail Position calls are only defined in
With parameter call.
call is a
The abstract operation PrepareForTailCall performs the following steps:
A tail position call must either release any transient internal resources associated with the currently executing function
For example, a tail position call should only grow an implementation's activation record stack by the amount that the size of the target function's activation record exceeds the size of the calling function's activation record. If the target function's activation record is smaller, then the total size of the stack should decrease.
super unless the source code containing super is eval code that is being processed by a super within At the top level of a
A Script Record encapsulates information about a script being evaluated. Each script record contains the fields listed in
| Field Name | Value Type | Meaning |
|---|---|---|
| [[Realm]] |
|
The |
| [[Environment]] |
|
The |
| [[ECMAScriptCode]] |
a |
The result of parsing the source text of this module using |
| [[HostDefined]] |
Any, default value is |
Field reserved for use by host environments that need to associate additional information with a script. |
The abstract operation ParseScript with arguments sourceText, realm, and hostDefined creates a
An implementation may parse script source text and analyse it for Early Error conditions prior to evaluation of ParseScript for that script source text. However, the reporting of any errors must be deferred until the point where this specification actually performs ParseScript upon that source text.
When an
GlobalDeclarationInstantiation is performed as follows using arguments script and env. script is the
Early errors specified in
Unlike explicit var or function declarations, properties that are directly created on the
The job ScriptEvaluationJob with parameters sourceText and hostDefined parses, validates, and evaluates sourceText as a
super.
The duplicate ExportedNames rule implies that multiple export default
With parameter labelSet.
With parameter labelSet.
With parameters iterationSet and labelSet.
ExportedBindings are the locally bound names that are explicitly associated with a
ExportedNames are the externally visible names that a
The abstract operation ImportedLocalNames with argument importEntries creates a
The LexicallyDeclaredNames of a
export At the top level of a
export export A Module Record encapsulates structural information about the imports and exports of a single module. This information is used to link the imports and exports of sets of connected modules. A Module Record includes four fields that are only used when evaluating a module.
For specification purposes Module Record values are values of the
Module Record defines the fields listed in
| Field Name | Value Type | Meaning |
|---|---|---|
| [[Realm]] |
|
The |
| [[Environment]] |
|
The |
| [[Namespace]] |
Object | |
The Module Namespace Object ( |
| [[HostDefined]] |
Any, default value is |
Field reserved for use by host environments that need to associate additional information with a module. |
| Method | Purpose |
|---|---|
| GetExportedNames(exportStarSet) | Return a list of all names that are either directly or indirectly exported from this module. |
| ResolveExport(exportName, resolveSet) |
Return the binding of a name exported by this module. Bindings are represented by a ResolvedBinding Record, of the form { [[Module]]: This operation must be idempotent if it completes normally. Each time it is called with a specific exportName, resolveSet pair as arguments it must return the same result. |
| Instantiate() |
Prepare the module for evaluation by transitively resolving all module dependencies and creating a module |
| Evaluate() |
If this module has already been evaluated successfully, return Instantiate must have completed successfully prior to invoking this method. |
A Source Text Module Record is used to represent information about a module that was defined from ECMAScript source text (
A
In addition to the fields, defined in
| Field Name | Value Type | Meaning |
|---|---|---|
| [[ECMAScriptCode]] |
a |
The result of parsing the source text of this module using |
| [[RequestedModules]] |
|
A |
| [[ImportEntries]] |
|
A |
| [[LocalExportEntries]] |
|
A |
| [[IndirectExportEntries]] |
|
A |
| [[StarExportEntries]] |
|
A |
| [[Status]] | String |
Initially "uninstantiated". Transitions to "instantiating", "instantiated", "evaluating", "evaluated" (in that order) as the module progresses throughout its lifecycle.
|
| [[EvaluationError]] |
An |
A completion of type "evaluated".
|
| [[DFSIndex]] |
|
Auxiliary field used during Instantiate and Evaluate only.
If [[Status]] is "instantiating" or "evaluating", this non-negative number records the point at which the module was first visited during the ongoing depth-first traversal of the dependency graph.
|
| [[DFSAncestorIndex]] |
|
Auxiliary field used during Instantiate and Evaluate only. If [[Status]] is "instantiating" or "evaluating", this is either the module's own [[DFSIndex]] or that of an "earlier" module in the same strongly connected component.
|
An ImportEntry Record is a
| Field Name | Value Type | Meaning |
|---|---|---|
| [[ModuleRequest]] | String |
String value of the |
| [[ImportName]] | String |
The name under which the desired binding is exported by the module identified by [[ModuleRequest]]. The value "*" indicates that the import request is for the target module's namespace object.
|
| [[LocalName]] | String | The name that is used to locally access the imported value from within the importing module. |
| Import Statement Form | [[ModuleRequest]] | [[ImportName]] | [[LocalName]] |
|---|---|---|---|
import v from "mod";
|
"mod"
|
"default"
|
"v"
|
import * as ns from "mod";
|
"mod"
|
"*"
|
"ns"
|
import {x} from "mod";
|
"mod"
|
"x"
|
"x"
|
import {x as v} from "mod";
|
"mod"
|
"x"
|
"v"
|
import "mod";
|
An |
||
An ExportEntry Record is a
| Field Name | Value Type | Meaning |
|---|---|---|
| [[ExportName]] | String | The name used to export this binding by this module. |
| [[ModuleRequest]] | String | null |
The String value of the |
| [[ImportName]] | String | null |
The name under which the desired binding is exported by the module identified by [[ModuleRequest]]. "*" indicates that the export request is for all exported bindings.
|
| [[LocalName]] | String | null |
The name that is used to locally access the exported value from within the importing module. |
| Export Statement Form | [[ExportName]] | [[ModuleRequest]] | [[ImportName]] | [[LocalName]] |
|---|---|---|---|---|
export var v;
|
"v"
|
|
|
"v"
|
export default function f(){}
|
"default"
|
|
|
"f"
|
export default function(){}
|
"default"
|
|
|
"*default*"
|
export default 42;
|
"default"
|
|
|
"*default*"
|
export {x};
|
"x"
|
|
|
"x"
|
export {v as x};
|
"x"
|
|
|
"v"
|
export {x} from "mod";
|
"x"
|
"mod"
|
"x"
|
|
export {v as x} from "mod";
|
"x"
|
"mod"
|
"v"
|
|
export * from "mod";
|
|
"mod"
|
"*"
|
|
The following definitions specify the required concrete methods and other
The abstract operation ParseModule with arguments sourceText, realm, and hostDefined creates a
"*", then"*", then"uninstantiated", [[EvaluationError]]: An implementation may parse module source text and analyse it for Early Error conditions prior to the evaluation of ParseModule for that module source text. However, the reporting of any errors must be deferred until the point where this specification actually performs ParseModule upon that source text.
The GetExportedNames concrete method of a
It performs the following steps:
"default") is GetExportedNames does not filter out or throw an exception for names that have ambiguous star export bindings.
The ResolveExport concrete method of a
ResolveExport attempts to resolve an imported binding to the actual defining module and local binding name. The defining module may be the module represented by the
If a defining module is found, a "ambiguous" is returned.
This abstract method performs the following steps:
"default") is default export was not explicitly defined by this module.default export cannot be provided by an export *."ambiguous", return "ambiguous".* import that includes the requested name."ambiguous".The Instantiate concrete method of a
On success, Instantiate transitions this module's [[Status]] from "uninstantiated" to "instantiated". On failure, an exception is thrown and this module's [[Status]] remains "uninstantiated".
This abstract method performs the following steps (most of the work is done by the auxiliary function
"instantiating" or "evaluating"."instantiated" or "evaluated".The InnerModuleInstantiation abstract operation is used by Instantiate to perform the actual instantiation process for the "instantiated" together.
This abstract operation performs the following steps:
"instantiating", "instantiated", or "evaluated", then"uninstantiated"."instantiating"."instantiating", "instantiated", or "evaluated"."instantiating" if and only if requiredModule is in stack."instantiating", then"instantiated".The ModuleDeclarationEnvironmentSetup abstract operation is used by
This abstract operation performs the following steps:
"ambiguous", throw a "*", then"ambiguous", throw a The Evaluate concrete method of a
Evaluate transitions this module's [[Status]] from "instantiated" to "evaluated".
If execution results in an exception, that exception is recorded in the [[EvaluationError]] field and rethrown by future invocations of Evaluate.
This abstract method performs the following steps (most of the work is done by the auxiliary function
"instantiated" or "evaluated"."evaluated" and module.[[EvaluationError]] is The InnerModuleEvaluation abstract operation is used by Evaluate to perform the actual evaluation process for the
This abstract operation performs the following steps:
"evaluated", then"evaluating", return index."instantiated"."evaluating"."evaluating" or "evaluated"."evaluating" if and only if requiredModule is in stack."evaluating", then"evaluated".The ModuleExecution abstract operation is used by
This abstract operation performs the following steps:
This non-normative section gives a series of examples of the instantiation and evaluation of a few common module graphs, with a specific focus on how errors can occur.
First consider the following simple module graph:
Let's first assume that there are no error conditions. When a host first calls A.Instantiate(), this will complete successfully by assumption, and recursively instantiate modules B and C as well, such that A.[[Status]] = B.[[Status]] = C.[[Status]] = "instantiated". This preparatory step can be performed at any time. Later, when the host is ready to incur any possible side effects of the modules, it can call A.Evaluate(), which will complete successfully (again by assumption), recursively having evaluated first C and then B. Each module's [[Status]] at this point will be "evaluated".
Consider then cases involving instantiation errors. If "uninstantiated". C's [[Status]] has become "instantiated", though.
Finally, consider a case involving evaluation errors. If "evaluated". C will also become "evaluated" but, in contrast to A and B, will remain without an [[EvaluationError]], as it successfully completed evaluation. Storing the exception ensures that any time a host tries to reuse A or B by calling their Evaluate() method, it will encounter the same exception. (Hosts are not required to reuse Source Text Module Records; similarly, hosts are not required to expose the exception objects thrown by these methods. However, the specification enables such uses.)
The difference here between instantiation and evaluation errors is due to how evaluation must be only performed once, as it can cause side effects; it is thus important to remember whether evaluation has already been performed, even if unsuccessfully. (In the error case, it makes sense to also remember the exception because otherwise subsequent Evaluate() calls would have to synthesize a new one.) Instantiation, on the other hand, is side-effect-free, and thus even if it fails, it can be retried at a later time with no issues.
Now consider a different type of error condition:
In this scenario, module A declares a dependency on some other module, but no "uninstantiated".
Lastly, consider a module graph with a cycle:
Here we assume that the entry point is module A, so that the host proceeds by calling A.Instantiate(), which performs "instantiating". B.[[Status]] itself remains "instantiating" when control gets back to A and "instantiated" , both A and B transition from "instantiating" to "instantiated" together; this is by design, since they form a strongly connected component.
An analogous story occurs for the evaluation phase of a cyclic module graph, in the success case.
Now consider a case where A has an instantiation error; for example, it tries to import a binding from C that does not exist. In that case, the above steps still occur, including the early return from the second call to "instantiating"). Hence both A and B become "uninstantiated". Note that C is left as "instantiated".
Finally, consider a case where A has an evaluation error; for example, its source code throws an exception. In that case, the evaluation-time analog of the above steps still occurs, including the early return from the second call to "evaluating"). Hence both A and B become "evaluated" and the exception is recorded in both A and B's [[EvaluationError]] fields, while C is left as "evaluated" with no [[EvaluationError]].
HostResolveImportedModule is an implementation-defined abstract operation that provides the concrete
The implementation of HostResolveImportedModule must conform to the following requirements:
Multiple different referencingModule, specifier pairs may map to the same
The GetModuleNamespace abstract operation retrieves the Module Namespace
This abstract operation performs the following steps:
"uninstantiated"."evaluated", module.[[EvaluationError]] is The only way GetModuleNamespace can throw is via one of the triggered
A TopLevelModuleEvaluationJob with parameters sourceText and hostDefined is a job that parses, validates, and evaluates sourceText as a
An implementation may parse a sourceText as a
The value of a
With parameter module.
"default", [[LocalName]]: localName }."*", [[LocalName]]: localName }."implements", "interface", "let", "package", "private", "protected", "public", or "static".
The above rule means that each ReferencedBindings of
"*default*", append "*default*" to declarationNames."*default*", append "*default*" to declarationNames."*default*" »."default" »."*", [[LocalName]]: "default" }."default" }."*default*", [[ExportName]]: "default" }."*default*" is used within this specification as a synthetic name for anonymous default export values.
With parameter module.
It is not necessary to treat export default
"*default*", then"name")."default")."*default*", value, env)."name")."default")."*default*", value, env).An implementation must report most errors at the time the relevant ECMAScript language construct is evaluated. An early error is an error that can be detected and reported prior to the evaluation of any construct in the eval is called and prevent evaluation of the eval code. All errors that are not early errors are runtime errors.
An implementation must report as an
An implementation shall not treat other kinds of errors as early errors even if the compiler can prove that a construct cannot execute without error under any circumstances. An implementation may issue an early warning in such a case, but it should not report the error until the relevant construct is actually executed.
An implementation shall report all errors as specified, except for the following:
eval, using a regular expression literal, or using the Function or RegExp HostReportErrors is an implementation-defined abstract operation that allows host environments to report parsing errors, early errors, and runtime errors.
An implementation of HostReportErrors must complete normally in all cases. The default implementation of HostReportErrors is to unconditionally return an empty normal completion.
errorList will be a
An implementation must not extend this specification in the following ways:
"caller" or "arguments". Such own properties also must not be created for function objects defined using an Function Generator AsyncFunction bind method also must not be created with such own properties.
"caller" the value of that property, as observed using [[Get]] or [[GetOwnProperty]], must not be a "caller".
Object.prototype.toLocaleString, Array.prototype.toLocaleString, Number.prototype.toLocaleString, Date.prototype.toLocaleDateString, Date.prototype.toLocaleString, Date.prototype.toLocaleTimeString, String.prototype.localeCompare, %TypedArray%.prototype.toLocaleString.
: to immediately follow source text that matches the There are certain built-in objects available whenever an ECMAScript
Unless specified otherwise, a built-in object that is callable as a function is a built-in
Many built-in objects are functions: they can be invoked with arguments. Some of them furthermore are constructors: they are functions intended for use with the new operator. For each built-in function, this specification describes the arguments required by that function and the properties of that new expression that invokes that
Unless otherwise specified in the description of a particular function, if a built-in function or this value” and “NewTarget” have the meanings given in
Unless otherwise specified in the description of a particular function, if a built-in function or
Implementations that add additional capabilities to the set of built-in functions are encouraged to do so by adding new functions rather than adding new parameters to existing functions.
Unless otherwise specified every built-in function and every built-in Function.prototype (
Unless otherwise specified every built-in prototype object has the Object prototype object, which is the initial value of the expression Object.prototype (
Built-in function objects that are not identified as constructors do not implement the [[Construct]] internal method unless otherwise specified in the description of a particular function.
Each built-in function defined in this specification is created by calling the
Every built-in length property whose value is an [ ]) or rest parameters (which are shown using the form «...name») are not included in the default argument count.
For example, the map property of the Array prototype object is described under the subclause heading «Array.prototype.map (callbackFn [ , thisArg])» which shows the two named arguments callbackFn and thisArg, the latter being optional; therefore the value of the length property of that
Unless otherwise specified, the length property of a built-in
Every built-in name property whose value is a String. Unless otherwise specified, this value is the name that is given to the function in this specification. For functions that are specified as properties of objects, the name value is the "get " or "set " prepended to the name property is explicitly specified for each built-in functions whose property key is a Symbol value.
Unless otherwise specified, the name property of a built-in
Every other
Every
The global object:
new operator.window property of the global object is the global object itself.The value of Infinity is
The value of NaN is
The value of undefined is
The eval function is the %eval% intrinsic object. When the eval function is called with one argument x, the following steps are taken:
The abstract operation PerformEval with arguments x, evalRealm, strictCaller, and direct performs the following steps:
"derived", let inDerivedConstructor be eval function.The eval code cannot instantiate variable or function bindings in the variable environment of the calling context that invoked the eval if the calling context is evaluating formal parameter initializers or if either the code of the calling context or the eval code is let, const, or class declarations are always instantiated in a new LexicalEnvironment.
These
These
These
HostEnsureCanCompileStrings is an implementation-defined abstract operation that allows host environments to block certain ECMAScript functions which allow developers to compile strings into ECMAScript code.
An implementation of HostEnsureCanCompileStrings may complete normally or abruptly. Any abrupt completions will be propagated to its callers. The default implementation of HostEnsureCanCompileStrings is to unconditionally return an empty normal completion.
When the abstract operation EvalDeclarationInstantiation is called with arguments body, varEnv, lexEnv, and strict, the following steps are taken:
eval will not create a global var declaration that would be shadowed by a global lexical declaration.An alternative version of this algorithm is described in
The isFinite function is the %isFinite% intrinsic object. When the isFinite function is called with one argument number, the following steps are taken:
The isNaN function is the %isNaN% intrinsic object. When the isNaN function is called with one argument number, the following steps are taken:
A reliable way for ECMAScript code to test if a value X is a X !== X. The result will be X is a
The parseFloat function produces a
The parseFloat function is the %parseFloat% intrinsic object. When the parseFloat function is called with one argument string, the following steps are taken:
parseFloat may interpret only a leading portion of string as a
The parseInt function produces an 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, the number may also optionally begin with the code unit pairs 0x or 0X.
The parseInt function is the %parseInt% intrinsic object. When the parseInt function is called, the following steps are taken:
"0x" or "0X", remove the first two code units from S and let R be 16.Uniform Resource Identifiers, or URIs, are Strings that identify resources (e.g. web pages or files) and transport protocols by which to access them (e.g. HTTP or FTP) on the Internet. The ECMAScript language itself does not provide any support for using URIs except for functions that encode and decode URIs as described in
Many implementations of ECMAScript provide additional functions and methods that manipulate web pages; these functions are beyond the scope of this standard.
A URI is composed of a sequence of components separated by component separators. The general form is:
: / ; ? where the italicized names represent components and “:”, “/”, “;” and “?” are reserved for use as separators. The encodeURI and decodeURI functions are intended to work with complete URIs; they assume that any reserved code units in the URI are intended to have special meaning and so are not encoded. The encodeURIComponent and decodeURIComponent functions are intended to work with the individual component parts of a URI; they assume that any reserved code units represent text and so must be encoded so that they are not interpreted as reserved code units when the component is part of a complete URI.
The following lexical grammar specifies the form of encoded URIs.
The above syntax is based upon RFC 2396 and does not reflect changes introduced by the more recent RFC 3986.
When a code unit to be included in a URI is not listed above or is not intended to have the special meaning sometimes given to the reserved code units, that code unit must be encoded. The code unit is transformed into its UTF-8 encoding, with "%xx".
The encoding and escaping process is described by the abstract operation Encode taking two String arguments string and unescapedSet.
"%"The unescaping and decoding process is described by the abstract operation Decode taking two String arguments string and reservedSet.
This syntax of Uniform Resource Identifiers is based upon RFC 2396 and does not reflect the more recent RFC 3986 which replaces RFC 2396. A formal description and implementation of UTF-8 is given in RFC 3629.
In UTF-8, characters are encoded using sequences of 1 to 6 octets. The only octet of a sequence of one has the higher-order bit set to 0, the remaining 7 bits being used to encode the character value. In a sequence of n octets, n>1, the initial octet has the n higher-order bits set to 1, followed by a bit set to 0. The remaining bits of that octet contain bits from the value of the character to be encoded. The following octets all have the higher-order bit set to 1 and the following bit set to 0, leaving 6 bits in each to contain bits from the character to be encoded. The possible UTF-8 encodings of ECMAScript characters are specified in
| Code Unit Value | Representation | 1st Octet | 2nd Octet | 3rd Octet | 4th Octet |
|---|---|---|---|---|---|
0x0000 - 0x007F
|
00000000 0zzzzzzz
|
0zzzzzzz
|
|||
0x0080 - 0x07FF
|
00000yyy yyzzzzzz
|
110yyyyy
|
10zzzzzz
|
||
0x0800 - 0xD7FF
|
xxxxyyyy yyzzzzzz
|
1110xxxx
|
10yyyyyy
|
10zzzzzz
|
|
0xD800 - 0xDBFF
followed by 0xDC00 - 0xDFFF
|
110110vv vvwwwwxx
followed by 110111yy yyzzzzzz
|
11110uuu
|
10uuwwww
|
10xxyyyy
|
10zzzzzz
|
0xD800 - 0xDBFF
not followed by 0xDC00 - 0xDFFF
|
causes URIError
|
||||
0xDC00 - 0xDFFF
|
causes URIError
|
||||
0xE000 - 0xFFFF
|
xxxxyyyy yyzzzzzz
|
1110xxxx
|
10yyyyyy
|
10zzzzzz
|
Where
uuuuu = vvvv + 1
to account for the addition of 0x10000 as in section 3.8 of the Unicode Standard (Surrogates).
The above transformation combines each
RFC 3629 prohibits the decoding of invalid UTF-8 octet sequences. For example, the invalid sequence C0 80 must not decode into the code unit 0x0000. Implementations of the Decode algorithm are required to throw a
The decodeURI function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by the encodeURI function is replaced with the UTF-16 encoding of the code points that it represents. Escape sequences that could not have been introduced by encodeURI are not replaced.
The decodeURI function is the %decodeURI% intrinsic object. When the decodeURI function is called with one argument encodedURI, the following steps are taken:
"#".The code point "#" is not decoded from escape sequences even though it is not a reserved URI code point.
The decodeURIComponent function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by the encodeURIComponent function is replaced with the UTF-16 encoding of the code points that it represents.
The decodeURIComponent function is the %decodeURIComponent% intrinsic object. When the decodeURIComponent function is called with one argument encodedURIComponent, the following steps are taken:
The encodeURI function computes a new version of a UTF-16 encoded (
The encodeURI function is the %encodeURI% intrinsic object. When the encodeURI function is called with one argument uri, the following steps are taken:
"#".The code unit "#" is not encoded to an escape sequence even though it is not a reserved or unescaped URI code point.
The encodeURIComponent function computes a new version of a UTF-16 encoded (
The encodeURIComponent function is the %encodeURIComponent% intrinsic object. When the encodeURIComponent function is called with one argument uriComponent, the following steps are taken:
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
See
The Object
Object property of the extends clause of a class definition.When Object function is called with optional argument value, the following steps are taken:
"%ObjectPrototype%").The length property of the Object
The Object
length property.The assign function is used to copy the values of all of the enumerable own properties from one or more source objects to a target object. When the assign function is called, the following steps are taken:
The length property of the assign function is 2.
The create function creates a new object with a specified prototype. When the create function is called, the following steps are taken:
The defineProperties function is used to add own properties and/or update the attributes of existing own properties of an object. When the defineProperties function is called, the following steps are taken:
The abstract operation ObjectDefineProperties with arguments O and Properties performs the following steps:
The defineProperty function is used to add an own property and/or update the attributes of an existing own property of an object. When the defineProperty function is called, the following steps are taken:
When the entries function is called with argument O, the following steps are taken:
When the freeze function is called, the following steps are taken:
"frozen").When the getOwnPropertyDescriptor function is called, the following steps are taken:
When the getOwnPropertyDescriptors function is called, the following steps are taken:
When the getOwnPropertyNames function is called, the following steps are taken:
When the getOwnPropertySymbols function is called with argument O, the following steps are taken:
The abstract operation GetOwnPropertyKeys is called with arguments O and Type where O is an Object and Type is one of the ECMAScript specification types String or Symbol. The following steps are taken:
When the getPrototypeOf function is called with argument O, the following steps are taken:
When the is function is called with arguments value1 and value2, the following steps are taken:
When the isExtensible function is called with argument O, the following steps are taken:
When the isFrozen function is called with argument O, the following steps are taken:
"frozen").When the isSealed function is called with argument O, the following steps are taken:
"sealed").When the keys function is called with argument O, the following steps are taken:
When the preventExtensions function is called, the following steps are taken:
The initial value of Object.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
When the seal function is called, the following steps are taken:
"sealed").When the setPrototypeOf function is called with arguments O and proto, the following steps are taken:
When the values function is called with argument O, the following steps are taken:
The Object prototype object:
The initial value of Object.prototype.constructor is the intrinsic object
When the hasOwnProperty method is called with argument V, the following steps are taken:
The ordering of steps 1 and 2 is chosen to ensure that any exception that would have been thrown by step 1 in previous editions of this specification will continue to be thrown even if the
When the isPrototypeOf method is called with argument V, the following steps are taken:
The ordering of steps 1 and 2 preserves the behaviour specified by previous editions of this specification for the case where V is not an object and the
When the propertyIsEnumerable method is called with argument V, the following steps are taken:
This method does not consider objects in the prototype chain.
The ordering of steps 1 and 2 is chosen to ensure that any exception that would have been thrown by step 1 in previous editions of this specification will continue to be thrown even if the
When the toLocaleString method is called, the following steps are taken:
"toString").The optional parameters to this function are not used but are intended to correspond to the parameter pattern used by ECMA-402 toLocaleString functions. Implementations that do not include ECMA-402 support must not use those parameter positions for other purposes.
This function provides a generic toLocaleString implementation for objects that have no locale-specific toString behaviour. Array, Number, Date, and Typed Arrays provide their own locale-sensitive toLocaleString methods.
ECMA-402 intentionally does not provide an alternative to this default implementation.
When the toString method is called, the following steps are taken:
"[object Undefined]"."[object Null]"."Array"."String"."Arguments"."Function"."Error"."Boolean"."Number"."Date"."RegExp"."Object"."[object ", tag, and "]".This function is the %ObjProto_toString% intrinsic object.
Historically, this function was occasionally used to access the String value of the [[Class]] internal slot that was used in previous editions of this specification as a nominal type tag for various built-in objects. The above definition of toString preserves compatibility for legacy code that uses toString as a test for those specific kinds of built-in objects. It does not provide a reliable type testing mechanism for other kinds of built-in or program defined objects. In addition, programs can use @@toStringTag in ways that will invalidate the reliability of such legacy type tests.
When the valueOf method is called, the following steps are taken:
This function is the %ObjProto_valueOf% intrinsic object.
Object instances have no special properties beyond those inherited from the Object prototype object.
The Function
Function property of the Function(…) is equivalent to the object creation expression new Function(…) with the same arguments.extends clause of a class definition. Subclass constructors that intend to inherit the specified Function behaviour must include a super call to the Function Function. There is no syntactic means to create instances of Function subclasses except for the built-in GeneratorFunction, AsyncFunction, and AsyncGeneratorFunction subclasses.The last argument specifies the body (executable code) of a function; any preceding arguments specify formal parameters.
When the Function function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no “ p ” arguments, and where body might also not be provided), the following steps are taken:
"normal", args).It is permissible but not necessary to have one argument for each formal parameter to be specified. For example, all three of the following expressions produce the same result:
new Function("a", "b", "c", "return a+b+c")
new Function("a, b, c", "return a+b+c")
new Function("a,b", "c", "return a+b+c")
The abstract operation CreateDynamicFunction is called with arguments constructor, newTarget, kind, and args. constructor is the new was initially applied to, kind is either "normal", "generator", "async", or "async generator", and args is a
"normal", then"%FunctionPrototype%"."generator", then"%Generator%"."async", then"async"."%AsyncFunctionPrototype%"."async generator"."%AsyncGenerator%"."," (a comma), and nextArgString."generator" or "async generator", then"async" or "async generator", then"generator", then"prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "async generator", then"prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: "normal", perform "prototype" property."anonymous").A prototype property is created for every non-async function created using CreateDynamicFunction to provide for the possibility that the function will be used as a
The Function
This is a
The value of Function.prototype is
This property has the attributes { [[Writable]]:
The Function prototype object:
new operator.prototype property.length property whose value is 0.name property whose value is the empty String.The Function prototype object is specified to be a
When the apply method is called on an object func with arguments thisArg and argArray, the following steps are taken:
The thisArg value is passed without modification as the
If func is an arrow function or a
When the bind method is called with argument thisArg and zero or more args, it performs the following steps:
"length")."name")."bound").Function objects created using Function.prototype.bind are exotic objects. They also do not have a prototype property.
If Target is an arrow function or a
When the call method is called on an object func with argument, thisArg and zero or more args, the following steps are taken:
The thisArg value is passed without modification as the
If func is an arrow function or a
The initial value of Function.prototype.constructor is the intrinsic object
When the toString method is called on an object func, the following steps are taken:
toString Representation Requirements:
eval in a lexical context that is equivalent to the lexical context used to create the original object, it will result in a new functionally equivalent object. In that case the returned source code must not mention freely any variables that were not mentioned freely by the original function's source code, even if these “extra” names were originally in scope.
eval will throw a When the @@hasInstance method of an object F is called with value V, the following steps are taken:
The value of the name property of this function is "[Symbol.hasInstance]".
This property has the attributes { [[Writable]]:
This is the default implementation of @@hasInstance that most functions inherit. @@hasInstance is called by the instanceof operator to determine whether a value is an instance of a specific
v instanceof F
evaluates as
F[@@hasInstance](v)
A instanceof by exposing a different @@hasInstance method on the function.
This property is non-writable and non-configurable to prevent tampering that could be used to globally expose the target function of a
Every Function instance is an ECMAScript Function.prototype.bind method (
Function instances have the following properties:
The value of the length property is an length property depends on the function. This property has the attributes { [[Writable]]:
The value of the name property is a String that is descriptive of the function. The name has no semantic significance but is typically a variable or
Anonymous functions objects that do not have a contextual name associated with them by this specification do not have a name own property but inherit the name property of
Function instances that can be used as a prototype property. Whenever such a Function instance is created another ordinary object is also created and is the initial value of the function's prototype property. Unless otherwise specified, the value of the prototype property is used to initialize the [[Prototype]] internal slot of the object created when that function is invoked as a
This property has the attributes { [[Writable]]:
Function objects created using Function.prototype.bind, or by evaluating a prototype property.
The Boolean
Boolean property of the extends clause of a class definition. Subclass constructors that intend to inherit the specified Boolean behaviour must include a super call to the Boolean When Boolean is called with argument value, the following steps are taken:
"%BooleanPrototype%", « [[BooleanData]] »).The Boolean
The initial value of Boolean.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
The Boolean prototype object:
The abstract operation thisBooleanValue(value) performs the following steps:
The initial value of Boolean.prototype.constructor is the intrinsic object
The following steps are taken:
"true"; else return "false".The following steps are taken:
Boolean instances are ordinary objects that inherit properties from the Boolean prototype object. Boolean instances have a [[BooleanData]] internal slot. The [[BooleanData]] internal slot is the Boolean value represented by this Boolean object.
The Symbol
Symbol property of the new operator.extends clause of a class definition but a super call to it will cause an exception.When Symbol is called with optional argument description, the following steps are taken:
The Symbol
The initial value of Symbol.asyncIterator is the well known symbol @@asyncIterator (
This property has the attributes { [[Writable]]:
When Symbol.for is called with argument key it performs the following steps:
The GlobalSymbolRegistry is a
The initial value of Symbol.hasInstance is the well-known symbol @@hasInstance (
This property has the attributes { [[Writable]]:
The initial value of Symbol.isConcatSpreadable is the well-known symbol @@isConcatSpreadable (
This property has the attributes { [[Writable]]:
The initial value of Symbol.iterator is the well-known symbol @@iterator (
This property has the attributes { [[Writable]]:
When Symbol.keyFor is called with argument sym it performs the following steps:
The initial value of Symbol.match is the well-known symbol @@match (
This property has the attributes { [[Writable]]:
The initial value of Symbol.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
The initial value of Symbol.replace is the well-known symbol @@replace (
This property has the attributes { [[Writable]]:
The initial value of Symbol.search is the well-known symbol @@search (
This property has the attributes { [[Writable]]:
The initial value of Symbol.species is the well-known symbol @@species (
This property has the attributes { [[Writable]]:
The initial value of Symbol.split is the well-known symbol @@split (
This property has the attributes { [[Writable]]:
The initial value of Symbol.toPrimitive is the well-known symbol @@toPrimitive (
This property has the attributes { [[Writable]]:
The initial value of Symbol.toStringTag is the well-known symbol @@toStringTag (
This property has the attributes { [[Writable]]:
The initial value of Symbol.unscopables is the well-known symbol @@unscopables (
This property has the attributes { [[Writable]]:
The Symbol prototype object:
The abstract operation thisSymbolValue(value) performs the following steps:
The initial value of Symbol.prototype.constructor is the intrinsic object
The following steps are taken:
When the abstract operation SymbolDescriptiveString is called with argument sym, the following steps are taken:
"Symbol(", desc, and ")".The following steps are taken:
This function is called by ECMAScript language operators to convert a Symbol object to a primitive value. The allowed values for hint are "default", "number", and "string".
When the @@toPrimitive method is called with argument hint, the following steps are taken:
The value of the name property of this function is "[Symbol.toPrimitive]".
This property has the attributes { [[Writable]]:
The initial value of the @@toStringTag property is the String value "Symbol".
This property has the attributes { [[Writable]]:
Symbol instances are ordinary objects that inherit properties from the Symbol prototype object. Symbol instances have a [[SymbolData]] internal slot. The [[SymbolData]] internal slot is the Symbol value represented by this Symbol object.
Instances of Error objects are thrown as exceptions when runtime errors occur. The Error objects may also serve as base objects for user-defined exception classes.
The Error
Error property of the Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.extends clause of a class definition. Subclass constructors that intend to inherit the specified Error behaviour must include a super call to the Error When the Error function is called with argument message, the following steps are taken:
"%ErrorPrototype%", « [[ErrorData]] »)."message", msgDesc).The Error
The initial value of Error.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
The Error prototype object:
The initial value of Error.prototype.constructor is the intrinsic object
The initial value of Error.prototype.message is the empty String.
The initial value of Error.prototype.name is "Error".
The following steps are taken:
"name")."Error"; otherwise let name be ? "message").Error instances are ordinary objects that inherit properties from the Error prototype object and have an [[ErrorData]] internal slot whose value is Object.prototype.toString.
A new instance of one of the NativeError objects below is thrown when a runtime error is detected. All of these objects share the same structure, as described in
This exception is not currently used within this specification. This object remains for compatibility with previous editions of this specification.
Indicates a value that is not in the set or range of allowable values.
Indicate that an invalid reference value has been detected.
Indicates that a parsing error has occurred.
TypeError is used to indicate an unsuccessful operation when none of the other NativeError objects are an appropriate indication of the failure cause.
Indicates that one of the global URI handling functions was used in a way that is incompatible with its definition.
When an ECMAScript implementation detects a runtime error, it throws a new instance of one of the NativeError objects defined in name property of the prototype object, and in the implementation-defined message property of the prototype object.
For each error object, references to NativeError in the definition should be replaced with the appropriate error object name from
Each NativeError
NativeError(…) is equivalent to the object creation expression new NativeError(…) with the same arguments.extends clause of a class definition. Subclass constructors that intend to inherit the specified NativeError behaviour must include a super call to the NativeError When a NativeError function is called with argument message, the following steps are taken:
"%NativeErrorPrototype%", « [[ErrorData]] »)."message", msgDesc).The actual value of the string passed in step 2 is either "%EvalErrorPrototype%", "%RangeErrorPrototype%", "%ReferenceErrorPrototype%", "%SyntaxErrorPrototype%", "%TypeErrorPrototype%", or "%URIErrorPrototype%" corresponding to which NativeError
Each NativeError
name property whose value is the String value `"NativeError"`.The initial value of NativeError.prototype is a NativeError prototype object (
This property has the attributes { [[Writable]]:
Each NativeError prototype object:
The initial value of the constructor property of the prototype for a given NativeError
The initial value of the message property of the prototype for a given NativeError
The initial value of the name property of the prototype for a given NativeError
NativeError instances are ordinary objects that inherit properties from their NativeError prototype object and have an [[ErrorData]] internal slot whose value is Object.prototype.toString (
The Number
Number property of the extends clause of a class definition. Subclass constructors that intend to inherit the specified Number behaviour must include a super call to the Number When Number is called with argument value, the following steps are taken:
"%NumberPrototype%", « [[NumberData]] »).The Number
The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 that is representable as a
This property has the attributes { [[Writable]]:
When Number.isFinite is called with one argument number, the following steps are taken:
When Number.isInteger is called with one argument number, the following steps are taken:
When Number.isNaN is called with one argument number, the following steps are taken:
This function differs from the global isNaN function (
When Number.isSafeInteger is called with one argument number, the following steps are taken:
The value of Number.MAX_SAFE_INTEGER is the largest
The value of Number.MAX_SAFE_INTEGER is 9007199254740991 (253-1).
This property has the attributes { [[Writable]]:
The value of Number.MAX_VALUE is the largest positive finite value of the Number type, which is approximately
This property has the attributes { [[Writable]]:
The value of Number.MIN_SAFE_INTEGER is the smallest
The value of Number.MIN_SAFE_INTEGER is -9007199254740991 (-(253-1)).
This property has the attributes { [[Writable]]:
The value of Number.MIN_VALUE is the smallest positive value of the Number type, which is approximately
In the IEEE 754-2008 double precision binary representation, the smallest possible value is a denormalized number. If an implementation does not support denormalized values, the value of Number.MIN_VALUE must be the smallest non-zero positive value that can actually be represented by the implementation.
This property has the attributes { [[Writable]]:
The value of Number.NaN is
This property has the attributes { [[Writable]]:
The value of Number.NEGATIVE_INFINITY is
This property has the attributes { [[Writable]]:
The value of the Number.parseFloat parseFloat property of the
The value of the Number.parseInt parseInt property of the
The value of Number.POSITIVE_INFINITY is
This property has the attributes { [[Writable]]:
The initial value of Number.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
The Number prototype object:
Unless explicitly stated otherwise, the methods of the Number prototype object defined below are not generic and the
The abstract operation thisNumberValue(value) performs the following steps:
The phrase “this
The initial value of Number.prototype.constructor is the intrinsic object
Return a String containing this
"NaN"."-"."Infinity".".", and b."+"."0"."+"."-"."e", c, and d.For implementations that provide more accurate conversions than required by the rules above, it is recommended that the following alternative version of step 10.b.i be used as a guideline:
toFixed returns a String containing this
The following steps are performed:
"NaN"."-"."0". Otherwise, let m be the String value consisting of the digits of the decimal representation of n (in order, with no leading zeroes).".", and b.The output of toFixed may be more precise than toString for some values because toString only prints enough significant digits to distinguish the number from adjacent number values. For example,
(1000000000000000128).toString() returns "1000000000000000100", while
(1000000000000000128).toFixed(0) returns "1000000000000000128".
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the Number.prototype.toLocaleString method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the toLocaleString method is used.
Produces a String value that represents this toString.
The meanings of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
Return a String containing this
"NaN"."Infinity".".", and b.The optional radix should be an
The following steps are performed:
a-z are used for digits with values 10 through 35. The precise algorithm is implementation-dependent, however the algorithm should be a generalization of that specified in The toString function is not generic; it throws a
The length property of the toString method is 1.
Number instances are ordinary objects that inherit properties from the Number prototype object. Number instances also have a [[NumberData]] internal slot. The [[NumberData]] internal slot is the
The Math object:
Math property of the new operator.In this specification, the phrase “the
The
This property has the attributes { [[Writable]]:
The
This property has the attributes { [[Writable]]:
The
This property has the attributes { [[Writable]]:
The
This property has the attributes { [[Writable]]:
The value of Math.LOG10E is approximately the reciprocal of the value of Math.LN10.
The
This property has the attributes { [[Writable]]:
The value of Math.LOG2E is approximately the reciprocal of the value of Math.LN2.
The
This property has the attributes { [[Writable]]:
The
This property has the attributes { [[Writable]]:
The value of Math.SQRT1_2 is approximately the reciprocal of the value of Math.SQRT2.
The
This property has the attributes { [[Writable]]:
The initial value of the @@toStringTag property is the String value "Math".
This property has the attributes { [[Writable]]:
Each of the following Math object functions applies the
In the function descriptions below, the symbols
The behaviour of the functions acos, acosh, asin, asinh, atan, atanh, atan2, cbrt, cos, cosh, exp, expm1, hypot, log,log1p, log2, log10, pow, random, sin, sinh, sqrt, tan, and tanh is not precisely specified here except to require specific results for certain argument values that represent boundary cases of interest. For other argument values, these functions are intended to compute approximations to the results of familiar mathematical functions, but some latitude is allowed in the choice of approximation algorithms. The general intent is that an implementer should be able to use the same mathematical library for ECMAScript on a given hardware platform that is available to C programmers on that platform.
Although the choice of algorithms is left to the implementation, it is recommended (but not specified by this standard) that implementations use the approximation algorithms for IEEE 754-2008 arithmetic contained in fdlibm, the freely distributable mathematical library from Sun Microsystems (http://www.netlib.org/fdlibm).
Returns the absolute value of x; the result has the same magnitude as x but has positive sign.
Returns an implementation-dependent approximation to the arc cosine of x. The result is expressed in radians and ranges from
Returns an implementation-dependent approximation to the inverse hyperbolic cosine of x.
Returns an implementation-dependent approximation to the arc sine of x. The result is expressed in radians and ranges from -π/2 to +π/2.
Returns an implementation-dependent approximation to the inverse hyperbolic sine of x.
Returns an implementation-dependent approximation to the arc tangent of x. The result is expressed in radians and ranges from -π/2 to +π/2.
Returns an implementation-dependent approximation to the inverse hyperbolic tangent of x.
Returns an implementation-dependent approximation to the arc tangent of the quotient
Returns an implementation-dependent approximation to the cube root of x.
Returns the smallest (closest to
The value of Math.ceil(x) is the same as the value of -Math.floor(-x).
When Math.clz32 is called with one argument x, the following steps are taken:
If n is 0, p will be 32. If the most significant bit of the 32-bit binary encoding of n is 1, p will be 0.
Returns an implementation-dependent approximation to the cosine of x. The argument is expressed in radians.
Returns an implementation-dependent approximation to the hyperbolic cosine of x.
The value of cosh(x) is the same as (exp(x) + exp(-x))/2.
Returns an implementation-dependent approximation to the exponential function of x (e raised to the power of x, where e is the base of the natural logarithms).
Returns an implementation-dependent approximation to subtracting 1 from the exponential function of x (e raised to the power of x, where e is the base of the natural logarithms). The result is computed in a way that is accurate even when the value of x is close 0.
Returns the greatest (closest to
The value of Math.floor(x) is the same as the value of -Math.ceil(-x).
When Math.fround is called with argument x, the following steps are taken:
Math.hypot returns an implementation-dependent approximation of the square root of the sum of squares of its arguments.
Implementations should take care to avoid the loss of precision from overflows and underflows that are prone to occur in naive implementations when this function is called with two or more arguments.
When Math.imul is called with arguments x and y, the following steps are taken:
Returns an implementation-dependent approximation to the natural logarithm of x.
Returns an implementation-dependent approximation to the natural logarithm of 1 + x. The result is computed in a way that is accurate even when the value of x is close to zero.
Returns an implementation-dependent approximation to the base 10 logarithm of x.
Returns an implementation-dependent approximation to the base 2 logarithm of x.
Given zero or more arguments, calls
Given zero or more arguments, calls
Returns a
Each Math.random function created for distinct realms must produce a distinct sequence of values from successive calls.
Returns the
Math.round(3.5) returns 4, but Math.round(-3.5) returns -3.
The value of Math.round(x) is not always the same as the value of Math.floor(x+0.5). When x is Math.round(x) returns Math.floor(x+0.5) returns Math.round(x) may also differ from the value of Math.floor(x+0.5)because of internal rounding when computing x+0.5.
Returns the sign of x, indicating whether x is positive, negative, or zero.
Returns an implementation-dependent approximation to the sine of x. The argument is expressed in radians.
Returns an implementation-dependent approximation to the hyperbolic sine of x.
The value of sinh(x) is the same as (exp(x) - exp(-x))/2.
Returns an implementation-dependent approximation to the square root of x.
Returns an implementation-dependent approximation to the tangent of x. The argument is expressed in radians.
Returns an implementation-dependent approximation to the hyperbolic tangent of x.
The value of tanh(x) is the same as (exp(x) - exp(-x))/(exp(x) + exp(-x)).
Returns the integral part of the number x, removing any fractional digits. If x is already an
The following functions are
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be
Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from -9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly -100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value
A given
where the number of milliseconds per day is
The remainder is called the time within the day:
ECMAScript uses a proleptic Gregorian calendar to map a day number to a year number and to determine the month and date within that year. In this calendar, leap years are precisely those which are (divisible by 4) and ((not divisible by 100) or (divisible by 400)). The number of days in year number y is therefore defined by
All non-leap years have 365 days with the usual number of days per month and leap years have an extra day in February. The day number of the first day of year y is given by:
The
A
The leap-year function is 1 for a time within a leap year and otherwise is zero:
Months are identified by an
where
A month value of 0 specifies January; 1 specifies February; 2 specifies March; 3 specifies April; 4 specifies May; 5 specifies June; 6 specifies July; 7 specifies August; 8 specifies September; 9 specifies October; 10 specifies November; and 11 specifies December. Note that
A date number is identified by an
The weekday for a particular
A weekday value of 0 specifies Sunday; 1 specifies Monday; 2 specifies Tuesday; 3 specifies Wednesday; 4 specifies Thursday; 5 specifies Friday; and 6 specifies Saturday. Note that
LocalTZA( t, isUTC ) is an implementation-defined algorithm that must return a number representing milliseconds suitable for adding to a Time Value. The local political rules for standard time and daylight saving time in effect at t should be used to determine the result in the way specified in the following three paragraphs.
When isUTC is true, LocalTZA( t, true ) should return the offset of the local time zone from UTC measured in milliseconds at time represented by
When isUTC is false, LocalTZA( t, false ) should return the offset of the local time zone from UTC measured in milliseconds at local time represented by
When
If an implementation does not support a conversion described above or if political rules for time t are not available within the implementation, the result must be 0.
It is recommended that implementations use the time zone information of the IANA Time Zone Database https://www.iana.org/time-zones/.
1:30 AM on November 5, 2017 in America/New_York is repeated twice (fall backward), but it must be interpreted as 1:30 AM UTC-04 instead of 1:30 AM UTC-05. LocalTZA(
2:30 AM on March 12, 2017 in America/New_York does not exist, but it must be interpreted as 2:30 AM UTC-05 (equivalent to 3:30 AM UTC-04). LocalTZA(
The abstract operation LocalTime with argument t converts t from UTC to local time by performing the following steps:
Two different time values (t (UTC)) are converted to the same local time
The abstract operation UTC with argument t converts t from local time to UTC. It performs the following steps:
The following
where
The abstract operation MakeTime calculates a number of milliseconds from its four arguments, which must be ECMAScript Number values. This operator functions as follows:
* + m * + s * + milli, performing the arithmetic according to IEEE 754-2008 rules (that is, as if using the ECMAScript operators * and +).The abstract operation MakeDay calculates a number of days from its three arguments, which must be ECMAScript Number values. This operator functions as follows:
The abstract operation MakeDate calculates a number of milliseconds from its two arguments, which must be ECMAScript Number values. This operator functions as follows:
The abstract operation TimeClip calculates a number of milliseconds from its argument, which must be an ECMAScript
The point of step 4 is that an implementation is permitted a choice of internal representations of time values, for example as a 64-bit signed
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
Where the fields are as follows:
YYYY
|
is the decimal digits of the year 0000 to 9999 in the proleptic Gregorian calendar. |
-
|
"-" (hyphen) appears literally twice in the string.
|
MM
|
is the month of the year from 01 (January) to 12 (December). |
DD
|
is the day of the month from 01 to 31. |
T
|
"T" appears literally in the string, to indicate the beginning of the time element.
|
HH
|
is the number of complete hours that have passed since midnight as two decimal digits from 00 to 24. |
:
|
":" (colon) appears literally twice in the string.
|
mm
|
is the number of complete minutes since the start of the hour as two decimal digits from 00 to 59. |
ss
|
is the number of complete seconds since the start of the minute as two decimal digits from 00 to 59. |
.
|
"." (dot) appears literally in the string.
|
sss
|
is the number of complete milliseconds since the start of the second as three decimal digits. |
Z
|
is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression HH:mm
|
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes “date-time” forms that consist of one of the above date-only forms immediately followed by one of the following time forms with an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
All numbers must be base 10. If the MM or DD fields are absent "01" is used as the value. If the HH, mm, or ss fields are absent "00" is used as the value and the value of an absent sss field is "000". When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
Illegal values (out-of-bounds as well as syntax errors) in a format string means that the format string is not a valid instance of this format.
As every day both starts and ends with midnight, the two notations 00:00 and 24:00 are available to distinguish the two midnights that can be associated with one date. This means that the following two notations refer to exactly the same point in time: 1995-02-04T24:00 and 1995-02-05T00:00
There exists no international standard that specifies abbreviations for civil time zones like CET, EST, etc. and sometimes the same abbreviation is even used for two very different time zones. For this reason, ISO 8601 and this format specifies numeric representations of date and time.
ECMAScript requires the ability to specify 6 digit years (extended years); approximately 285,426 years, either forward or backward, from 01 January, 1970 UTC. To represent years before 0 or after 9999, ISO 8601 permits the expansion of the year representation, but only by prior agreement between the sender and the receiver. In the simplified ECMAScript format such an expanded year representation shall have 2 extra year digits and is always prefixed with a + or - sign. The year 0 is considered positive and hence prefixed with a + sign.
Examples of extended years:
| -283457-03-21T15:00:59.008Z | 283458 B.C. |
| -000001-01-01T00:00:00Z | 2 B.C. |
| +000000-01-01T00:00:00Z | 1 B.C. |
| +000001-01-01T00:00:00Z | 1 A.D. |
| +001970-01-01T00:00:00Z | 1970 A.D. |
| +002009-12-15T00:00:00Z | 2009 A.D. |
| +287396-10-12T08:59:00.992Z | 287396 A.D. |
The Date
Date property of the extends clause of a class definition. Subclass constructors that intend to inherit the specified Date behaviour must include a super call to the Date length property whose value is 7.This description applies only if the Date
When the Date function is called, the following steps are taken:
"%DatePrototype%", « [[DateValue]] »).This description applies only if the Date
When the Date function is called, the following steps are taken:
parse method ("%DatePrototype%", « [[DateValue]] »).This description applies only if the Date
When the Date function is called, the following steps are taken:
"%DatePrototype%", « [[DateValue]] »).The Date
The now function returns a now.
The parse function applies the parse interprets the resulting String as a date and time; it returns a Number, the UTC Date.parse to return
If x is any Date object whose milliseconds amount is zero within a particular implementation of ECMAScript, then all of the following expressions should produce the same numeric value in that implementation, if all the properties referenced have their initial values:
x.valueOf()
Date.parse(x.toString())
Date.parse(x.toUTCString())
Date.parse(x.toISOString())
However, the expression
Date.parse(x.toLocaleString())
is not required to produce the same Date.parse is implementation-dependent when given any String value that does not conform to the Date Time String Format (toString or toUTCString method.
The initial value of Date.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
When the UTC function is called, the following steps are taken:
The length property of the UTC function is 7.
The UTC function differs from the Date
The Date prototype object:
Unless explicitly defined otherwise, the methods of the Date prototype object defined below are not generic and the
The abstract operation thisTimeValue(value) performs the following steps:
In following descriptions of functions that are properties of the Date prototype object, the phrase “this Date object” refers to the object that is the
The initial value of Date.prototype.constructor is the intrinsic object
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The following steps are performed:
The length property of the setFullYear method is 3.
If month is not present, this method behaves as if month was present with the value getMonth(). If date is not present, it behaves as if date was present with the value getDate().
The following steps are performed:
The length property of the setHours method is 4.
If min is not present, this method behaves as if min was present with the value getMinutes(). If sec is not present, it behaves as if sec was present with the value getSeconds(). If ms is not present, it behaves as if ms was present with the value getMilliseconds().
The following steps are performed:
The following steps are performed:
The length property of the setMinutes method is 3.
If sec is not present, this method behaves as if sec was present with the value getSeconds(). If ms is not present, this behaves as if ms was present with the value getMilliseconds().
The following steps are performed:
The length property of the setMonth method is 2.
If date is not present, this method behaves as if date was present with the value getDate().
The following steps are performed:
The length property of the setSeconds method is 2.
If ms is not present, this method behaves as if ms was present with the value getMilliseconds().
The following steps are performed:
The following steps are performed:
The following steps are performed:
The length property of the setUTCFullYear method is 3.
If month is not present, this method behaves as if month was present with the value getUTCMonth(). If date is not present, it behaves as if date was present with the value getUTCDate().
The following steps are performed:
The length property of the setUTCHours method is 4.
If min is not present, this method behaves as if min was present with the value getUTCMinutes(). If sec is not present, it behaves as if sec was present with the value getUTCSeconds(). If ms is not present, it behaves as if ms was present with the value getUTCMilliseconds().
The following steps are performed:
The following steps are performed:
The length property of the setUTCMinutes method is 3.
If sec is not present, this method behaves as if sec was present with the value getUTCSeconds(). If ms is not present, it function behaves as if ms was present with the value return by getUTCMilliseconds().
The following steps are performed:
The length property of the setUTCMonth method is 2.
If date is not present, this method behaves as if date was present with the value getUTCDate().
The following steps are performed:
The length property of the setUTCSeconds method is 2.
If ms is not present, this method behaves as if ms was present with the value getUTCMilliseconds().
The following steps are performed:
"Invalid Date".This function returns a String value representing the instance in time corresponding to
This function provides a String representation of a Date object for use by JSON.stringify (
When the toJSON method is called with argument key, the following steps are taken:
"toISOString").The argument is ignored.
The toJSON function is intentionally generic; it does not require that its toISOString method.
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the Date.prototype.toLocaleDateString method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the toLocaleDateString method is used.
This function returns a String value. The contents of the String are implementation-dependent, but are intended to represent the “date” portion of the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the Date.prototype.toLocaleString method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the toLocaleString method is used.
This function returns a String value. The contents of the String are implementation-dependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the Date.prototype.toLocaleTimeString method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the toLocaleTimeString method is used.
This function returns a String value. The contents of the String are implementation-dependent, but are intended to represent the “time” portion of the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
The following steps are performed:
For any Date object d whose milliseconds amount is zero, the result of Date.parse(d.toString()) is equal to d.valueOf(). See
The toString function is intentionally generic; it does not require that its
The following steps are performed:
":", minute, ":", second, the code unit 0x0020 (SPACE), and "GMT".The following steps are performed:
| Number | Name |
|---|---|
| 0 |
"Sun"
|
| 1 |
"Mon"
|
| 2 |
"Tue"
|
| 3 |
"Wed"
|
| 4 |
"Thu"
|
| 5 |
"Fri"
|
| 6 |
"Sat"
|
| Number | Name |
|---|---|
| 0 |
"Jan"
|
| 1 |
"Feb"
|
| 2 |
"Mar"
|
| 3 |
"Apr"
|
| 4 |
"May"
|
| 5 |
"Jun"
|
| 6 |
"Jul"
|
| 7 |
"Aug"
|
| 8 |
"Sep"
|
| 9 |
"Oct"
|
| 10 |
"Nov"
|
| 11 |
"Dec"
|
The following steps are performed:
"+"; otherwise, let offsetSign be "-".The following steps are performed:
"Invalid Date".The following steps are performed:
"Invalid Date".The following steps are performed:
"Invalid Date".",", the code unit 0x0020 (SPACE), day, the code unit 0x0020 (SPACE), month, the code unit 0x0020 (SPACE), year, the code unit 0x0020 (SPACE), and The following steps are performed:
This function is called by ECMAScript language operators to convert a Date object to a primitive value. The allowed values for hint are "default", "number", and "string". Date objects, are unique among built-in ECMAScript object in that they treat "default" as being equivalent to "string", All other built-in ECMAScript objects treat "default" as being equivalent to "number".
When the @@toPrimitive method is called with argument hint, the following steps are taken:
"string" or the String value "default", then"string"."number", then"number".The value of the name property of this function is "[Symbol.toPrimitive]".
This property has the attributes { [[Writable]]:
Date instances are ordinary objects that inherit properties from the Date prototype object. Date instances also have a [[DateValue]] internal slot. The [[DateValue]] internal slot is the
The String
String property of the extends clause of a class definition. Subclass constructors that intend to inherit the specified String behaviour must include a super call to the String When String is called with argument value, the following steps are taken:
""."%StringPrototype%")).The String
The String.fromCharCode function may be called with any number of arguments which form the rest parameter codeUnits. The following steps are taken:
The length property of the fromCharCode function is 1.
The String.fromCodePoint function may be called with any number of arguments which form the rest parameter codePoints. The following steps are taken:
The length property of the fromCodePoint function is 1.
The initial value of String.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
The String.raw function may be called with a variable number of arguments. The first argument is template and the remainder of the arguments form the
"raw"))."length")).String.raw is intended for use as a tag function of a Tagged Template (
The String prototype object:
length property whose initial value is 0 and whose attributes are { [[Writable]]: Unless explicitly stated otherwise, the methods of the String prototype object defined below are not generic and the
The abstract operation thisStringValue(value) performs the following steps:
Returns a single element String containing the code unit at index pos within the String value resulting from converting this object to a String. If there is no element at that index, the result is the empty String. The result is a String value, not a String object.
If pos is a value of Number type that is an x.charAt(pos) is equal to the result of x.substring(pos, pos+1).
When the charAt method is called with one argument pos, the following steps are taken:
The charAt function is intentionally generic; it does not require that its
Returns a Number (a nonnegative
When the charCodeAt method is called with one argument pos, the following steps are taken:
The charCodeAt function is intentionally generic; it does not require that its
Returns a nonnegative
When the codePointAt method is called with one argument pos, the following steps are taken:
The codePointAt function is intentionally generic; it does not require that its
When the concat method is called it returns the String value consisting of the code units of the this object (converted to a String) followed by the code units of each of the arguments converted to a String. The result is a String value, not a String object.
When the concat method is called with zero or more arguments, the following steps are taken:
The length property of the concat method is 1.
The concat function is intentionally generic; it does not require that its
The initial value of String.prototype.constructor is the intrinsic object
The following steps are taken:
Returns
Throwing an exception if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.
The endsWith function is intentionally generic; it does not require that its
The includes method takes two arguments, searchString and position, and performs the following steps:
If searchString appears as a substring of the result of converting this object to a String, at one or more indices that are greater than or equal to position, return
Throwing an exception if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.
The includes function is intentionally generic; it does not require that its
If searchString appears as a substring of the result of converting this object to a String, at one or more indices that are greater than or equal to position, then the smallest such index is returned; otherwise, -1 is returned. If position is
The indexOf method takes two arguments, searchString and position, and performs the following steps:
The indexOf function is intentionally generic; it does not require that its
If searchString appears as a substring of the result of converting this object to a String at one or more indices that are smaller than or equal to position, then the greatest such index is returned; otherwise, -1 is returned. If position is
The lastIndexOf method takes two arguments, searchString and position, and performs the following steps:
The lastIndexOf function is intentionally generic; it does not require that its
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the localeCompare method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the localeCompare method is used.
When the localeCompare method is called with argument that, it returns a Number other than
Before performing the comparisons, the following steps are performed to prepare the Strings:
The meaning of the optional second and third parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not assign any other interpretation to those parameter positions.
The localeCompare method, if considered as a function of two arguments
The actual return values are implementation-defined to permit implementers to encode additional information in the value, but the function is required to define a total ordering on all Strings. This function must treat Strings that are canonically equivalent according to the Unicode standard as identical and must return 0 when comparing Strings that are considered canonically equivalent.
The localeCompare method itself is not directly suitable as an argument to Array.prototype.sort because the latter requires a function of two arguments.
This function is intended to rely on whatever language-sensitive comparison functionality is available to the ECMAScript environment from the host environment, and to compare according to the rules of the host environment's current locale. However, regardless of the host provided comparison capabilities, this function must treat Strings that are canonically equivalent according to the Unicode standard as identical. It is recommended that this function should not honour Unicode compatibility equivalences or decompositions. For a definition and discussion of canonical equivalence see the Unicode Standard, chapters 2 and 3, as well as Unicode Standard Annex #15, Unicode Normalization Forms (https://unicode.org/reports/tr15/) and Unicode Technical Note #5, Canonical Equivalence in Applications (https://www.unicode.org/notes/tn5/). Also see Unicode Technical Standard #10, Unicode Collation Algorithm (https://unicode.org/reports/tr10/).
The localeCompare function is intentionally generic; it does not require that its
When the match method is called with argument regexp, the following steps are taken:
The match function is intentionally generic; it does not require that its
When the normalize method is called with one argument form, the following steps are taken:
"NFC"."NFC", "NFD", "NFKC", or "NFKD", throw a The normalize function is intentionally generic; it does not require that its
When the padEnd method is called, the following steps are taken:
The first argument maxLength will be clamped such that it can be no smaller than the length of the
The optional second argument fillString defaults to
When the padStart method is called, the following steps are taken:
The first argument maxLength will be clamped such that it can be no smaller than the length of the
The optional second argument fillString defaults to
The following steps are taken:
This method creates the String value consisting of the code units of the this object (converted to String) repeated count times.
The repeat function is intentionally generic; it does not require that its
When the replace method is called with arguments searchValue and replaceValue, the following steps are taken:
The replace function is intentionally generic; it does not require that its
The abstract operation GetSubstitution performs the following steps:
$ replacements are done left-to-right, and, once such a replacement is performed, the new replacement text is not subject to further replacements.| Code units | Unicode Characters | Replacement text |
|---|---|---|
| 0x0024, 0x0024 |
$$
|
$
|
| 0x0024, 0x0026 |
$&
|
matched |
| 0x0024, 0x0060 |
$`
|
If position is 0, the replacement is the empty String. Otherwise the replacement is the substring of str that starts at index 0 and whose last code unit is at index position - 1. |
| 0x0024, 0x0027 |
$'
|
If tailPos ≥ stringLength, the replacement is the empty String. Otherwise the replacement is the substring of str that starts at index tailPos and continues to the end of str. |
|
0x0024, N
Where 0x0031 ≤ N ≤ 0x0039 |
$n where
n is one of 1 2 3 4 5 6 7 8 9 and $n is not followed by a decimal digit
|
The nth element of captures, where n is a single digit in the range 1 to 9. If n≤m and the nth element of captures is |
|
0x0024, N, N
Where 0x0030 ≤ N ≤ 0x0039 |
$nn where
n is one of 0 1 2 3 4 5 6 7 8 9
|
The nnth element of captures, where nn is a two-digit decimal number in the range 01 to 99. If nn≤m and the nnth element of captures is |
| 0x0024, 0x003C |
$<
|
|
| 0x0024 |
$ in any context that does not match any of the above.
|
$
|
When the search method is called with argument regexp, the following steps are taken:
The search function is intentionally generic; it does not require that its
The slice method takes two arguments, start and end, and returns a substring of the result of converting this object to a String, starting from index start and running to, but not including, index end (or through the end of the String if end is
The slice function is intentionally generic; it does not require that its
Returns an Array object into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any substring in the returned array, but serve to divide up the String value. The value of separator may be a String of any length or it may be an object, such as a RegExp, that has a @@split method.
When the split method is called, the following steps are taken:
"0", S)."0", S).The value of separator may be an empty String. In this case, separator does not match the empty substring at the beginning or end of the input String, nor does it match the empty substring at the end of the previous separator match. If separator is the empty String, the String is split up into individual code unit elements; the length of the result array equals the length of the String, and each substring contains one code unit.
If the
If separator is
The split function is intentionally generic; it does not require that its
The abstract operation SplitMatch takes three parameters, a String S, an
The following steps are taken:
This method returns
Throwing an exception if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.
The startsWith function is intentionally generic; it does not require that its
The substring method takes two arguments, start and end, and returns a substring of the result of converting this object to a String, starting from index start and running to, but not including, index end of the String (or through the end of the String if end is
If either argument is
If start is larger than end, they are swapped.
The following steps are taken:
The substring function is intentionally generic; it does not require that its
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the toLocaleLowerCase method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the toLocaleLowerCase method is used.
This function interprets a String value as a sequence of UTF-16 encoded code points, as described in
This function works exactly the same as toLowerCase except that its result is intended to yield the correct result for the host environment's current locale, rather than a locale-independent result. There will only be a difference in the few cases (such as Turkish) where the rules for that language conflict with the regular Unicode case mappings.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
The toLocaleLowerCase function is intentionally generic; it does not require that its
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the toLocaleUpperCase method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the toLocaleUpperCase method is used.
This function interprets a String value as a sequence of UTF-16 encoded code points, as described in
This function works exactly the same as toUpperCase except that its result is intended to yield the correct result for the host environment's current locale, rather than a locale-independent result. There will only be a difference in the few cases (such as Turkish) where the rules for that language conflict with the regular Unicode case mappings.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
The toLocaleUpperCase function is intentionally generic; it does not require that its
This function interprets a String value as a sequence of UTF-16 encoded code points, as described in
The result must be derived according to the locale-insensitive case mappings in the Unicode Character Database (this explicitly includes not only the UnicodeData.txt file, but also all locale-insensitive mappings in the SpecialCasings.txt file that accompanies it).
The case mapping of some code points may produce multiple code points. In this case the result String may not be the same length as the source String. Because both toUpperCase and toLowerCase have context-sensitive behaviour, the functions are not symmetrical. In other words, s.toUpperCase().toLowerCase() is not necessarily equal to s.toLowerCase().
The toLowerCase function is intentionally generic; it does not require that its
When the toString method is called, the following steps are taken:
For a String object, the toString method happens to return the same thing as the valueOf method.
This function interprets a String value as a sequence of UTF-16 encoded code points, as described in
This function behaves in exactly the same way as String.prototype.toLowerCase, except that the String is mapped using the toUppercase algorithm of the Unicode Default Case Conversion.
The toUpperCase function is intentionally generic; it does not require that its
This function interprets a String value as a sequence of UTF-16 encoded code points, as described in
The following steps are taken:
The trim function is intentionally generic; it does not require that its
When the valueOf method is called, the following steps are taken:
When the @@iterator method is called it returns an Iterator object (
The value of the name property of this function is "[Symbol.iterator]".
String instances are String exotic objects and have the internal methods specified for such objects. String instances inherit properties from the String prototype object. String instances also have a [[StringData]] internal slot.
String instances have a length property, and a set of enumerable properties with
The number of elements in the String value represented by this String object.
Once a String object is initialized, this property is unchanging. It has the attributes { [[Writable]]:
A String Iterator is an object, that represents a specific iteration over some specific String instance object. There is not a named
Several methods of String objects return Iterator objects. The abstract operation CreateStringIterator with argument string is used to create such iterator objects. It performs the following steps:
The %StringIteratorPrototype% object:
The initial value of the @@toStringTag property is the String value "String Iterator".
This property has the attributes { [[Writable]]:
String Iterator instances are ordinary objects that inherit properties from the
| Internal Slot | Description |
|---|---|
| [[IteratedString]] | The String value whose elements are being iterated. |
| [[StringIteratorNextIndex]] |
The |
A RegExp object contains a regular expression and the associated flags.
The form and functionality of regular expressions is modelled after the regular expression facility in the Perl 5 programming language.
The RegExp
Each \u u u \u
"$", or "_", or the "$", or "_", or the The definitions of “the MV of
| ControlEscape | Code Point Value | Code Point | Unicode Name | Symbol |
|---|---|---|---|---|
t
|
9 |
U+0009
|
CHARACTER TABULATION | <HT> |
n
|
10 |
U+000A
|
LINE FEED (LF) | <LF> |
v
|
11 |
U+000B
|
LINE TABULATION | <VT> |
f
|
12 |
U+000C
|
FORM FEED (FF) | <FF> |
r
|
13 |
U+000D
|
CARRIAGE RETURN (CR) | <CR> |
\0 represents the <NUL> character and cannot be followed by a decimal digit.
\ A regular expression pattern is converted into an internal procedure using the process described below. An implementation is encouraged to use more efficient algorithms than the ones listed below, as long as the results are the same. The internal procedure is used as the value of a RegExp object's [[RegExpMatcher]] internal slot.
A "u". A BMP pattern matches against a String interpreted as consisting of a sequence of 16-bit values that are Unicode code points in the range of the Basic Multilingual Plane. A Unicode pattern matches against a String interpreted as consisting of Unicode code points encoded using UTF-16. In the context of describing the behaviour of a BMP pattern “character” means a single 16-bit Unicode BMP code point. In the context of describing the behaviour of a Unicode pattern “character” means a UTF-16 encoded code point (
The syntax and semantics of
For example, consider a pattern expressed in source text as the single non-BMP character U+1D11E (MUSICAL SYMBOL G CLEF). Interpreted as a Unicode pattern, it would be a single element (character)
Patterns are passed to the RegExp
An implementation may not actually perform such translations to or from UTF-16, but the semantics of this specification requires that the result of pattern matching be as if such translations were performed.
The descriptions below use the following variables:
( pattern character that is matched by the ( terminal of the "s" and otherwise is "i" and otherwise is "m" and otherwise is "u" and otherwise is Furthermore, the descriptions below use the following internal data structures:
The production
A Pattern evaluates (“compiles”) to an internal procedure value.
With parameter direction.
The production
The production
The | regular expression operator separates two alternatives. The pattern first tries to match the left | produce
/a|ab/.exec("abc")
returns the result "a" and not "ab". Moreover,
/((a)|(ab))((c)|(bc))/.exec("abc")
returns the array
["abc", "a", "a", undefined, "bc", undefined, "bc"]
and not
["abc", "ab", undefined, "ab", "c", "c", undefined]
The order in which the two alternatives are tried is independent of the value of direction.
With parameter direction.
The production
The production
Consecutive
With parameter direction.
The production
The AssertionTester is independent of direction.
The production
The production
The abstract operation RepeatMatcher takes eight parameters, a Matcher m, an
An
If the
Compare
/a[a-z]{2,4}/.exec("abcdefghi")
which returns "abcde" with
/a[a-z]{2,4}?/.exec("abcdefghi")
which returns "abc".
Consider also
/(aa|aabaac|ba|b|c)*/.exec("aabaac")
which, by the choice point ordering above, returns the array
["aaba", "ba"]
and not any of:
["aabaac", "aabaac"]
["aabaac", "c"]
The above ordering of choice points can be used to write a regular expression that calculates the greatest common divisor of two numbers (represented in unary notation). The following example calculates the gcd of 10 and 15:
"aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\1*,\1+$/, "$1")
which returns the gcd in unary notation "aaaaa".
Step 4 of the RepeatMatcher clears
/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")
which returns the array
["zaacbbbcac", "z", "ac", "a", undefined, "c"]
and not
["zaacbbbcac", "z", "ac", "a", "bbb", "c"]
because each iteration of the outermost * clears all captured Strings contained in the quantified
Step 1 of the RepeatMatcher's d closure states that, once the minimum number of repetitions has been satisfied, any more expansions of
/(a*)*/.exec("b")
or the slightly more complicated:
/(a*)b\1+/.exec("baaaac")
which returns the array
["b", ""]
The production
Even when the y flag is used with a pattern, ^ always matches only at the beginning of Input, or (if Multiline is
The production
The production
The production
The production
The production
The production
The production
The abstract operation WordCharacters performs the following steps:
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
|
_
|
The abstract operation IsWordChar takes an
The production
The production
The production
The production
The production
The production
The production
The production
With parameter direction.
The production
The production
The production
The production
The production
The production
The abstract operation CharacterSetMatcher takes three arguments, a CharSet A, a Boolean flag invert, and an
The abstract operation Canonicalize takes a character parameter ch and performs the following steps:
String.prototype.toUpperCase using s as the Parentheses of the form ( ) serve both to group the components of the \ followed by a nonzero decimal number), referenced in a replace String, or returned as part of an array from the regular expression matching internal procedure. To inhibit the capturing behaviour of parentheses, use the form (?: ) instead.
The form (?= ) specifies a zero-width positive lookahead. In order for it to succeed, the pattern inside (?= form (this unusual behaviour is inherited from Perl). This only matters when the
For example,
/(?=(a+))/.exec("baaabac")
matches the empty String immediately after the first b and therefore returns the array:
["", "aaa"]
To illustrate the lack of backtracking into the lookahead, consider:
/(?=(a+))a*b\1/.exec("baaabac")
This expression returns
["aba", "a"]
and not:
["aaaba", "a"]
The form (?! ) specifies a zero-width negative lookahead. In order for it to succeed, the pattern inside
/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")
looks for an a not immediately followed by some positive number n of a's, a b, another n a's (specified by the first \2) and a c. The second \2 is outside the negative lookahead, so it matches against
["baaabaac", "ba", undefined, "abaac"]
In case-insignificant matches when Unicode is "ß" (U+00DF) to "SS". It may however map a code point outside the Basic Latin range to a character within, for example, "ſ" (U+017F) to "s". Such characters are not mapped if Unicode is /[a-z]/i, but they will match /[a-z]/ui.
The abstract operation UnicodeMatchProperty takes a parameter p that is a
Implementations must support the Unicode property names and aliases listed in
For example, Script_Extensions (scx (property alias) are valid, but script_extensions or Scx aren't.
The listed properties form a superset of what UTS18 RL1.2 requires.
| Canonical |
|
|---|---|
|
General_Category |
|
Script |
|
Script_Extensions |
| Canonical |
|
|---|---|
ASCII |
ASCII |
|
ASCII_Hex_Digit |
|
Alphabetic |
Any |
Any |
Assigned |
Assigned |
|
Bidi_Control |
|
Bidi_Mirrored |
|
Case_Ignorable |
Cased |
Cased |
|
Changes_When_Casefolded |
|
Changes_When_Casemapped |
|
Changes_When_Lowercased |
|
Changes_When_NFKC_Casefolded |
|
Changes_When_Titlecased |
|
Changes_When_Uppercased |
Dash |
Dash |
|
Default_Ignorable_Code_Point |
|
Deprecated |
|
Diacritic |
Emoji |
Emoji |
Emoji_Component |
Emoji_Component |
Emoji_Modifier |
Emoji_Modifier |
Emoji_Modifier_Base |
Emoji_Modifier_Base |
Emoji_Presentation |
Emoji_Presentation |
|
Extender |
|
Grapheme_Base |
|
Grapheme_Extend |
|
Hex_Digit |
|
IDS_Binary_Operator |
|
IDS_Trinary_Operator |
|
ID_Continue |
|
ID_Start |
|
Ideographic |
|
Join_Control |
|
Logical_Order_Exception |
|
Lowercase |
Math |
Math |
|
Noncharacter_Code_Point |
|
Pattern_Syntax |
|
Pattern_White_Space |
|
Quotation_Mark |
Radical |
Radical |
|
Regional_Indicator |
|
Sentence_Terminal |
|
Soft_Dotted |
|
Terminal_Punctuation |
|
Unified_Ideograph |
|
Uppercase |
|
Variation_Selector |
|
White_Space |
|
XID_Continue |
|
XID_Start |
The abstract operation UnicodeMatchPropertyValue takes two parameters p and v, each of which is a
Implementations must support the Unicode property value names and aliases listed in
For example, Xpeo and Old_Persian are valid Script_Extension values, but xpeo and Old Persian aren't.
This algorithm differs from the matching rules for symbolic values listed in UAX44: case, Is prefix is not supported.
General_Category| Property value and aliases | Canonical property value |
|---|---|
|
Cased_Letter |
|
Close_Punctuation |
|
Connector_Punctuation |
|
Control |
|
Currency_Symbol |
|
Dash_Punctuation |
|
Decimal_Number |
|
Enclosing_Mark |
|
Final_Punctuation |
|
Format |
|
Initial_Punctuation |
|
Letter |
|
Letter_Number |
|
Line_Separator |
|
Lowercase_Letter |
|
Mark |
|
Math_Symbol |
|
Modifier_Letter |
|
Modifier_Symbol |
|
Nonspacing_Mark |
|
Number |
|
Open_Punctuation |
|
Other |
|
Other_Letter |
|
Other_Number |
|
Other_Punctuation |
|
Other_Symbol |
|
Paragraph_Separator |
|
Private_Use |
|
Punctuation |
|
Separator |
|
Space_Separator |
|
Spacing_Mark |
|
Surrogate |
|
Symbol |
|
Titlecase_Letter |
|
Unassigned |
|
Uppercase_Letter |
Script and Script_Extensions| Property value and aliases | Canonical property value |
|---|---|
|
Adlam |
|
Ahom |
|
Anatolian_Hieroglyphs |
|
Arabic |
|
Armenian |
|
Avestan |
|
Balinese |
|
Bamum |
|
Bassa_Vah |
|
Batak |
|
Bengali |
|
Bhaiksuki |
|
Bopomofo |
|
Brahmi |
|
Braille |
|
Buginese |
|
Buhid |
|
Canadian_Aboriginal |
|
Carian |
|
Caucasian_Albanian |
|
Chakma |
|
Cham |
|
Cherokee |
|
Common |
|
Coptic |
|
Cuneiform |
|
Cypriot |
|
Cyrillic |
|
Deseret |
|
Devanagari |
|
Duployan |
|
Egyptian_Hieroglyphs |
|
Elbasan |
|
Ethiopic |
|
Georgian |
|
Glagolitic |
|
Gothic |
|
Grantha |
|
Greek |
|
Gujarati |
|
Gurmukhi |
|
Han |
|
Hangul |
|
Hanunoo |
|
Hatran |
|
Hebrew |
|
Hiragana |
|
Imperial_Aramaic |
|
Inherited |
|
Inscriptional_Pahlavi |
|
Inscriptional_Parthian |
|
Javanese |
|
Kaithi |
|
Kannada |
|
Katakana |
|
Kayah_Li |
|
Kharoshthi |
|
Khmer |
|
Khojki |
|
Khudawadi |
|
Lao |
|
Latin |
|
Lepcha |
|
Limbu |
|
Linear_A |
|
Linear_B |
|
Lisu |
|
Lycian |
|
Lydian |
|
Mahajani |
|
Malayalam |
|
Mandaic |
|
Manichaean |
|
Marchen |
|
Masaram_Gondi |
|
Meetei_Mayek |
|
Mende_Kikakui |
|
Meroitic_Cursive |
|
Meroitic_Hieroglyphs |
|
Miao |
|
Modi |
|
Mongolian |
|
Mro |
|
Multani |
|
Myanmar |
|
Nabataean |
|
New_Tai_Lue |
|
Newa |
|
Nko |
|
Nushu |
|
Ogham |
|
Ol_Chiki |
|
Old_Hungarian |
|
Old_Italic |
|
Old_North_Arabian |
|
Old_Permic |
|
Old_Persian |
|
Old_South_Arabian |
|
Old_Turkic |
|
Oriya |
|
Osage |
|
Osmanya |
|
Pahawh_Hmong |
|
Palmyrene |
|
Pau_Cin_Hau |
|
Phags_Pa |
|
Phoenician |
|
Psalter_Pahlavi |
|
Rejang |
|
Runic |
|
Samaritan |
|
Saurashtra |
|
Sharada |
|
Shavian |
|
Siddham |
|
SignWriting |
|
Sinhala |
|
Sora_Sompeng |
|
Soyombo |
|
Sundanese |
|
Syloti_Nagri |
|
Syriac |
|
Tagalog |
|
Tagbanwa |
|
Tai_Le |
|
Tai_Tham |
|
Tai_Viet |
|
Takri |
|
Tamil |
|
Tangut |
|
Telugu |
|
Thaana |
|
Thai |
|
Tibetan |
|
Tifinagh |
|
Tirhuta |
|
Ugaritic |
|
Vai |
|
Warang_Citi |
|
Yi |
|
Zanabazar_Square |
With parameter direction.
The production
The production
The production
An escape sequence of the form \ followed by a nonzero decimal number n matches the result of the nth set of capturing parentheses (
The production
The abstract operation BackreferenceMatcher takes two arguments, an
The
The
If \ is followed by a decimal number n whose first digit is not 0, then the escape sequence is considered to be a backreference. It is an error if n is greater than the total number of left-capturing parentheses in the entire regular expression.
The production
0 through 9 inclusive.The production
The production
The production
The production
The production
The production
The production
The production
The production
"General_Category", s) is identical to a The production
The production
The production
The production
The production
The production
The production
The abstract operation CharacterRange takes two CharSet parameters A and B and performs the following steps:
The production
The production
The production
Even if the pattern ignores case, the case of the two ends of a range is significant in determining which characters belong to the range. Thus, for example, the pattern /[E-F]/i matches only the letters E, F, e, and f, while the pattern /[E-f]/i matches all upper and lower-case letters in the Unicode Basic Latin block as well as the symbols [, \, ], ^, _, and `.
A - character can be treated literally or it can denote a range. It is treated literally if it is the first or last character of
The production
- U+002D (HYPHEN-MINUS).The production
The production
The production
The
A \b, \B, and backreferences. Inside a \b means the backspace character, while \B and backreferences raise errors. Using a backreference inside a
The RegExp
RegExp property of the RegExp(…) is equivalent to the object creation expression new RegExp(…) with the same arguments.extends clause of a class definition. Subclass constructors that intend to inherit the specified RegExp behaviour must include a super call to the RegExp The following steps are taken:
If pattern is supplied using a
When the abstract operation RegExpAlloc with argument newTarget is called, the following steps are taken:
"%RegExpPrototype%", « [[RegExpMatcher]], [[OriginalSource]], [[OriginalFlags]] »)."lastIndex", PropertyDescriptor { [[Writable]]: When the abstract operation RegExpInitialize with arguments obj, pattern, and flags is called, the following steps are taken:
"g", "i", "m", "s", "u", or "y" or if it contains the same code unit more than once, throw a "u", let BMP be "lastIndex", 0, When the abstract operation RegExpCreate with arguments P and F is called, the following steps are taken:
When the abstract operation EscapeRegExpPattern with arguments P and F is called, the following occurs:
"u") equivalent to P interpreted as UTF-16 encoded Unicode code points ("u") must behave identically to the internal procedure given by the constructed object's [[RegExpMatcher]] internal slot. Multiple calls to this abstract operation using the same values for P and F must produce identical results./ or any "/", S, "/", and F can be parsed (in an appropriate lexical context) as a "/", then S could be "\/" or "\u002F", among other possibilities, but not "/", because /// followed by F would be parsed as a "(?:)".The RegExp
The initial value of RegExp.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
RegExp[@@species] is an
The value of the name property of this function is "get [Symbol.species]".
RegExp prototype methods normally use their this object's
The RegExp prototype object:
The RegExp prototype object does not have a valueOf property of its own; however, it inherits the valueOf property from the Object prototype object.
The initial value of RegExp.prototype.constructor is the intrinsic object
Performs a regular expression match of string against the regular expression and returns an Array object containing the results of the match, or
The String
The abstract operation RegExpExec with arguments R and S performs the following steps:
"exec").If a callable exec property is not found this algorithm falls back to attempting to use the built-in RegExp matching algorithm. This provides compatible behaviour for code written for prior editions where most built-in algorithms that use regular expressions did not perform a dynamic property lookup of exec.
The abstract operation RegExpBuiltinExec with arguments R and S performs the following steps:
"lastIndex"))."g", let global be "y", let sticky be "u", let fullUnicode be "lastIndex", 0, "lastIndex", 0, "lastIndex", e, "length" property is n + 1."index", lastIndex)."input", S)."0", matchedSubstr)."groups", groups).The abstract operation AdvanceStringIndex with arguments S, index, and unicode performs the following steps:
RegExp.prototype.dotAll is an
RegExp.prototype.flags is an
"global"))."ignoreCase"))."multiline"))."dotAll"))."unicode"))."sticky")).RegExp.prototype.global is an
RegExp.prototype.ignoreCase is an
When the @@match method is called with argument string, the following steps are taken:
"global"))."unicode"))."lastIndex", 0, "0"))."lastIndex"))."lastIndex", nextIndex, The value of the name property of this function is "[Symbol.match]".
The @@match property is used by the
RegExp.prototype.multiline is an
When the @@replace method is called with arguments string and replaceValue, the following steps are taken:
"global"))."length"))."0"))."index"))."groups").The value of the name property of this function is "[Symbol.replace]".
When the @@search method is called with argument string, the following steps are taken:
"lastIndex")."lastIndex", 0, "lastIndex")."lastIndex", previousLastIndex, "index").The value of the name property of this function is "[Symbol.search]".
The lastIndex and global properties of this RegExp object are ignored when performing the search. The lastIndex property is left unchanged.
RegExp.prototype.source is an
"(?:)".Returns an Array object into which substrings of the result of converting string to a String have been stored. The substrings are determined by searching from left to right for matches of the
The /a*?/[Symbol.split]("ab") evaluates to the array ["a", "b"], while /a*/[Symbol.split]("ab") evaluates to the array ["","b"].)
If the string is (or converts to) the empty String, the result depends on whether the regular expression can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String.
If the regular expression contains capturing parentheses, then each time separator is matched the results (including any
/<(\/)?([^<>]+)>/[Symbol.split]("A<B>bold</B>and<CODE>coded</CODE>")
evaluates to the array
["A", undefined, "B", "bold", "/", "B", "and", undefined, "CODE", "coded", "/", "CODE", ""]
If limit is not
When the @@split method is called, the following steps are taken:
"flags"))."u", let unicodeMatching be "y", let newFlags be flags."y"."0", S)."lastIndex", q, "lastIndex"))."length")).The value of the name property of this function is "[Symbol.split]".
The @@split method ignores the value of the global and sticky properties of this RegExp object.
RegExp.prototype.sticky is an
The following steps are taken:
The returned String has the form of a
RegExp.prototype.unicode is an
RegExp instances are ordinary objects that inherit properties from the RegExp prototype object. RegExp instances have internal slots [[RegExpMatcher]], [[OriginalSource]], and [[OriginalFlags]]. The value of the [[RegExpMatcher]] internal slot is an implementation-dependent representation of the
Prior to ECMAScript 2015, RegExp instances were specified as having the own data properties source, global, ignoreCase, and multiline. Those properties are now specified as accessor properties of RegExp.prototype.
RegExp instances also have the following property:
The value of the lastIndex property specifies the String index at which to start the next match. It is coerced to an
Array objects are exotic objects that give special treatment to a certain class of property names. See
The Array
Array property of the Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.extends clause of a class definition. Subclass constructors that intend to inherit the exotic Array behaviour must include a super call to the Array Array.prototype methods are generic methods that are not dependent upon their this value being an Array length property whose value is 1.This description applies if and only if the Array
"%ArrayPrototype%").This description applies if and only if the Array
"%ArrayPrototype%")."0", len)."length", intLen, This description applies if and only if the Array
When the Array function is called, the following steps are taken:
"%ArrayPrototype%").length property is numberOfArgs.The Array
When the from method is called with argument items and optional arguments mapfn and thisArg, the following steps are taken:
"length", k, "length"))."length", len, The from function is an intentionally generic factory method; it does not require that its
The isArray function takes one argument arg, and performs the following steps:
When the of method is called with any number of arguments, the following steps are taken:
"length", len, The items argument is assumed to be a well-formed rest argument value.
The of function is an intentionally generic factory method; it does not require that its
The value of Array.prototype is
This property has the attributes { [[Writable]]:
Array[@@species] is an
The value of the name property of this function is "get [Symbol.species]".
Array prototype methods normally use their this object's
The Array prototype object:
length property whose initial value is 0 and whose attributes are { [[Writable]]: The Array prototype object is specified to be an Array
When the concat method is called with zero or more arguments, it returns an array containing the array elements of the object followed by the array elements of each argument in order.
The following steps are taken:
"length"))."length", n, The length property of the concat method is 1.
The explicit setting of the length property in step 6 is necessary to ensure that its value is correct in situations where the trailing elements of the result Array are not present.
The concat function is intentionally generic; it does not require that its
The abstract operation IsConcatSpreadable with argument O performs the following steps:
The initial value of Array.prototype.constructor is the intrinsic object
The copyWithin method takes up to three arguments target, start and end.
The end argument is optional with the length of the
The following steps are taken:
"length")).The copyWithin function is intentionally generic; it does not require that its
The following steps are taken:
"key+value").This function is the %ArrayProto_entries% intrinsic object.
callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value every calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns every immediately returns every will return
If a thisArg parameter is provided, it will be used as the
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
every does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by every is set before the first call to callbackfn. Elements which are appended to the array after the call to every begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time every visits them; elements that are deleted after the call to every begins and before being visited are not visited. every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns
When the every method is called with one or two arguments, the following steps are taken:
"length")).The every function is intentionally generic; it does not require that its
The fill method takes up to three arguments value, start and end.
The start and end arguments are optional with default values of 0 and the length of the
The following steps are taken:
"length")).The fill function is intentionally generic; it does not require that its
callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value filter calls callbackfn once for each element in the array, in ascending order, and constructs a new array of all the values for which callbackfn returns
If a thisArg parameter is provided, it will be used as the
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
filter does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by filter is set before the first call to callbackfn. Elements which are appended to the array after the call to filter begins will not be visited by callbackfn. If existing elements of the array are changed their value as passed to callbackfn will be the value at the time filter visits them; elements that are deleted after the call to filter begins and before being visited are not visited.
When the filter method is called with one or two arguments, the following steps are taken:
"length")).The filter function is intentionally generic; it does not require that its
The find method is called with one or two arguments, predicate and thisArg.
predicate should be a function that accepts three arguments and returns a value that is coercible to a Boolean value. find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns find immediately returns that element value. Otherwise, find returns
If a thisArg parameter is provided, it will be used as the
predicate is called with three arguments: the value of the element, the index of the element, and the object being traversed.
find does not directly mutate the object on which it is called but the object may be mutated by the calls to predicate.
The range of elements processed by find is set before the first call to predicate. Elements that are appended to the array after the call to find begins will not be visited by predicate. If existing elements of the array are changed, their value as passed to predicate will be the value at the time that find visits them.
When the find method is called, the following steps are taken:
"length")).The find function is intentionally generic; it does not require that its
predicate should be a function that accepts three arguments and returns a value that is coercible to the Boolean value findIndex calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns findIndex immediately returns the index of that element value. Otherwise, findIndex returns -1.
If a thisArg parameter is provided, it will be used as the
predicate is called with three arguments: the value of the element, the index of the element, and the object being traversed.
findIndex does not directly mutate the object on which it is called but the object may be mutated by the calls to predicate.
The range of elements processed by findIndex is set before the first call to predicate. Elements that are appended to the array after the call to findIndex begins will not be visited by predicate. If existing elements of the array are changed, their value as passed to predicate will be the value at the time that findIndex visits them.
When the findIndex method is called with one or two arguments, the following steps are taken:
"length")).The findIndex function is intentionally generic; it does not require that its
callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each element present in the array, in ascending order. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
When the forEach method is called with one or two arguments, the following steps are taken:
"length")).This function is the %ArrayProto_forEach% intrinsic object.
The forEach function is intentionally generic; it does not require that its
includes compares searchElement to the elements of the array, in ascending order, using the
The optional second argument fromIndex defaults to 0 (i.e. the whole array is searched). If it is greater than or equal to the length of the array,
When the includes method is called, the following steps are taken:
"length")).The includes function is intentionally generic; it does not require that its
The includes method intentionally differs from the similar indexOf method in two ways. First, it uses the
indexOf compares searchElement to the elements of the array, in ascending order, using the
The optional second argument fromIndex defaults to 0 (i.e. the whole array is searched). If it is greater than or equal to the length of the array, -1 is returned, i.e. the array will not be searched. If it is negative, it is used as the offset from the end of the array to compute fromIndex. If the computed index is less than 0, the whole array will be searched.
When the indexOf method is called with one or two arguments, the following steps are taken:
"length")).The indexOf function is intentionally generic; it does not require that its
The elements of the array are converted to Strings, and these Strings are then concatenated, separated by occurrences of the separator. If no separator is provided, a single comma is used as the separator.
The join method takes one argument, separator, and performs the following steps:
"length")).",".The join function is intentionally generic; it does not require that its
The following steps are taken:
"key").This function is the %ArrayProto_keys% intrinsic object.
lastIndexOf compares searchElement to the elements of the array in descending order using the
The optional second argument fromIndex defaults to the array's length minus one (i.e. the whole array is searched). If it is greater than or equal to the length of the array, the whole array will be searched. If it is negative, it is used as the offset from the end of the array to compute fromIndex. If the computed index is less than 0, -1 is returned.
When the lastIndexOf method is called with one or two arguments, the following steps are taken:
"length")).The lastIndexOf function is intentionally generic; it does not require that its
callbackfn should be a function that accepts three arguments. map calls callbackfn once for each element in the array, in ascending order, and constructs a new Array from the results. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
map does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by map is set before the first call to callbackfn. Elements which are appended to the array after the call to map begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time map visits them; elements that are deleted after the call to map begins and before being visited are not visited.
When the map method is called with one or two arguments, the following steps are taken:
"length")).The map function is intentionally generic; it does not require that its
The last element of the array is removed from the array and returned.
When the pop method is called, the following steps are taken:
"length"))."length", 0, "length", newLen, The pop function is intentionally generic; it does not require that its
The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.
When the push method is called with zero or more arguments, the following steps are taken:
"length"))."length", len, The length property of the push method is 1.
The push function is intentionally generic; it does not require that its
callbackfn should be a function that takes four arguments. reduce calls the callback, as a function, once for each element after the first element present in the array, in ascending order.
callbackfn is called with four arguments: the previousValue (value from the previous call to callbackfn), the currentValue (value of the current element), the currentIndex, and the object being traversed. The first time that callback is called, the previousValue and currentValue can be one of two values. If an initialValue was supplied in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was supplied, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. It is a
reduce does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by reduce is set before the first call to callbackfn. Elements that are appended to the array after the call to reduce begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time reduce visits them; elements that are deleted after the call to reduce begins and before being visited are not visited.
When the reduce method is called with one or two arguments, the following steps are taken:
"length")).The reduce function is intentionally generic; it does not require that its
callbackfn should be a function that takes four arguments. reduceRight calls the callback, as a function, once for each element after the first element present in the array, in descending order.
callbackfn is called with four arguments: the previousValue (value from the previous call to callbackfn), the currentValue (value of the current element), the currentIndex, and the object being traversed. The first time the function is called, the previousValue and currentValue can be one of two values. If an initialValue was supplied in the call to reduceRight, then previousValue will be equal to initialValue and currentValue will be equal to the last value in the array. If no initialValue was supplied, then previousValue will be equal to the last value in the array and currentValue will be equal to the second-to-last value. It is a
reduceRight does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by reduceRight is set before the first call to callbackfn. Elements that are appended to the array after the call to reduceRight begins will not be visited by callbackfn. If existing elements of the array are changed by callbackfn, their value as passed to callbackfn will be the value at the time reduceRight visits them; elements that are deleted after the call to reduceRight begins and before being visited are not visited.
When the reduceRight method is called with one or two arguments, the following steps are taken:
"length")).The reduceRight function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method.
The elements of the array are rearranged so as to reverse their order. The object is returned as the result of the call.
When the reverse method is called, the following steps are taken:
"length")).The reverse function is intentionally generic; it does not require that its
The first element of the array is removed from the array and returned.
When the shift method is called, the following steps are taken:
"length"))."length", 0, "0")."length", len-1, The shift function is intentionally generic; it does not require that its
The slice method takes two arguments, start and end, and returns an array containing the elements of the array from element start up to, but not including, element end (or through the end of the array if end is
The following steps are taken:
"length"))."length", n, The explicit setting of the length property of the result Array in step 11 was necessary in previous editions of ECMAScript to ensure that its length was correct in situations where the trailing elements of the result Array were not present. Setting length became unnecessary starting in ES2015 when the result Array was initialized to its proper length rather than an empty Array but is carried forward to preserve backward compatibility.
The slice function is intentionally generic; it does not require that its
callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value some calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns some immediately returns some returns
If a thisArg parameter is provided, it will be used as the
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
some does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by some is set before the first call to callbackfn. Elements that are appended to the array after the call to some begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time that some visits them; elements that are deleted after the call to some begins and before being visited are not visited. some acts like the "exists" quantifier in mathematics. In particular, for an empty array, it returns
When the some method is called with one or two arguments, the following steps are taken:
"length")).The some function is intentionally generic; it does not require that its
The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not
Upon entry, the following steps are performed to initialize evaluation of the sort function:
"length")).Within this specification of the sort method, an object, obj, is said to be sparse if the following algorithm returns
The sort order is the ordering, after completion of this function, of the sort function is then determined as follows:
If comparefn is not
Let proto be obj.[[GetPrototypeOf]](). If proto is not
The sort order is also implementation-defined if obj is sparse and any of the following conditions are true:
The sort order is also implementation-defined if any of the following conditions are true:
The following steps are taken:
Unless the sort order is specified above to be implementation-defined, the returned object must have the following two characteristics:
Here the notation
A function comparefn is a consistent comparison function for a set of values S if all of the requirements below are met for all values a, b, and c (possibly the same value) in the set S: The notation
The above conditions are necessary and sufficient to ensure that comparefn divides the set S into equivalence classes and that these equivalence classes are totally ordered.
The sort function is intentionally generic; it does not require that its
The SortCompare abstract operation is called with two arguments x and y. It also has access to the comparefn argument passed to the current invocation of the sort method. The following steps are taken:
Because non-existent property values always compare greater than
Method calls performed by the
When the splice method is called with two or more arguments start, deleteCount and zero or more items, the deleteCount elements of the array starting at
The following steps are taken:
"length"))."length", actualDeleteCount, "length", len - actualDeleteCount + itemCount, The explicit setting of the length property of the result Array in step 19 was necessary in previous editions of ECMAScript to ensure that its length was correct in situations where the trailing elements of the result Array were not present. Setting length became unnecessary starting in ES2015 when the result Array was initialized to its proper length rather than an empty Array but is carried forward to preserve backward compatibility.
The splice function is intentionally generic; it does not require that its
An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement the Array.prototype.toLocaleString method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of the toLocaleString method is used.
The first edition of ECMA-402 did not include a replacement specification for the Array.prototype.toLocaleString method.
The meanings of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
The following steps are taken:
"length"))."toLocaleString")).The elements of the array are converted to Strings using their toLocaleString methods, and these Strings are then concatenated, separated by occurrences of a separator String that has been derived in an implementation-defined locale-specific way. The result of calling this function is intended to be analogous to the result of toString, except that the result of this function is intended to be locale-specific.
The toLocaleString function is intentionally generic; it does not require that its
When the toString method is called, the following steps are taken:
"join").The toString function is intentionally generic; it does not require that its
The arguments are prepended to the start of the array, such that their order within the array is the same as the order in which they appear in the argument list.
When the unshift method is called with zero or more arguments item1, item2, etc., the following steps are taken:
"length"))."length", len+argCount, The length property of the unshift method is 1.
The unshift function is intentionally generic; it does not require that its
The following steps are taken:
"value").This function is the %ArrayProto_values% intrinsic object.
The initial value of the @@iterator property is the same Array.prototype.values property.
The initial value of the @@unscopables
"copyWithin", "entries", "fill", "find", "findIndex", "includes", "keys", "values", This property has the attributes { [[Writable]]:
The own property names of this object are property names that were not included as standard properties of Array.prototype prior to the ECMAScript 2015 specification. These names are ignored for with statement binding purposes in order to preserve the behaviour of existing code that might use one of these names as a binding in an outer scope that is shadowed by a with statement whose binding object is an Array object.
Array instances are Array exotic objects and have the internal methods specified for such objects. Array instances inherit properties from the Array prototype object.
Array instances have a length property, and a set of enumerable properties with
The length property of an Array instance is a
The length property initially has the attributes { [[Writable]]:
Reducing the value of the length property has the side-effect of deleting own array elements whose
An Array Iterator is an object, that represents a specific iteration over some specific Array instance object. There is not a named
Several methods of Array objects return Iterator objects. The abstract operation CreateArrayIterator with arguments array and kind is used to create such iterator objects. It performs the following steps:
The %ArrayIteratorPrototype% object:
"key", return "value", let result be elementValue."key+value".The initial value of the @@toStringTag property is the String value "Array Iterator".
This property has the attributes { [[Writable]]:
Array Iterator instances are ordinary objects that inherit properties from the
| Internal Slot | Description |
|---|---|
| [[IteratedObject]] | The object whose array elements are being iterated. |
| [[ArrayIteratorNextIndex]] |
The |
| [[ArrayIterationKind]] |
A String value that identifies what is returned for each element of the iteration. The possible values are: "key", "value", "key+value".
|
TypedArray objects present an array-like view of an underlying binary data buffer (
|
|
Element Type | Element Size | Conversion Operation | Description | Equivalent C Type |
|---|---|---|---|---|---|
|
Int8Array
%Int8Array% |
Int8 | 1 |
|
8-bit 2's complement signed |
signed char |
|
Uint8Array
%Uint8Array% |
Uint8 | 1 |
|
8-bit unsigned |
unsigned char |
|
Uint8ClampedArray
%Uint8ClampedArray% |
Uint8C | 1 |
|
8-bit unsigned |
unsigned char |
|
Int16Array
%Int16Array% |
Int16 | 2 |
|
16-bit 2's complement signed |
short |
|
Uint16Array
%Uint16Array% |
Uint16 | 2 |
|
16-bit unsigned |
unsigned short |
|
Int32Array
%Int32Array% |
Int32 | 4 |
|
32-bit 2's complement signed |
int |
|
Uint32Array
%Uint32Array% |
Uint32 | 4 |
|
32-bit unsigned |
unsigned int |
|
Float32Array
%Float32Array% |
Float32 | 4 | 32-bit IEEE floating point | float | |
|
Float64Array
%Float64Array% |
Float64 | 8 | 64-bit IEEE floating point | double |
In the definitions below, references to TypedArray should be replaced with the appropriate
The %TypedArray% intrinsic object:
super call to it.The
The length property of the
The
name property whose value is "TypedArray".When the from method is called with argument source, and optional arguments mapfn and thisArg, the following steps are taken:
"length")).The abstract operation IterableToList performs the following steps:
When the of method is called with any number of arguments, the following steps are taken:
The items argument is assumed to be a well-formed rest argument value.
The initial value of
This property has the attributes { [[Writable]]:
The value of the name property of this function is "get [Symbol.species]".
this object's
The %TypedArrayPrototype% object:
prototype.buffer is an
prototype.byteLength is an
prototype.byteOffset is an
The initial value of
The interpretation and use of the arguments of .prototype.copyWithin are the same as for Array.prototype.copyWithin as defined in
The following steps are taken:
"Uint8", "Unordered")."Uint8", value, "Unordered").When called with argument O, the following steps are taken:
The following steps are taken:
"key+value")..prototype.every is a distinct function that implements the same algorithm as Array.prototype.every as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
The interpretation and use of the arguments of .prototype.fill are the same as for Array.prototype.fill as defined in
The following steps are taken:
The interpretation and use of the arguments of .prototype.filter are the same as for Array.prototype.filter as defined in
When the filter method is called with one or two arguments, the following steps are taken:
This function is not generic. The
.prototype.find is a distinct function that implements the same algorithm as Array.prototype.find as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.findIndex is a distinct function that implements the same algorithm as Array.prototype.findIndex as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.forEach is a distinct function that implements the same algorithm as Array.prototype.forEach as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
%TypedArray%.prototype.includes is a distinct function that implements the same algorithm as Array.prototype.includes as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.indexOf is a distinct function that implements the same algorithm as Array.prototype.indexOf as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.join is a distinct function that implements the same algorithm as Array.prototype.join as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
The following steps are taken:
"key")..prototype.lastIndexOf is a distinct function that implements the same algorithm as Array.prototype.lastIndexOf as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
prototype.length is an
This function is not generic. The
The interpretation and use of the arguments of .prototype.map are the same as for Array.prototype.map as defined in
When the map method is called with one or two arguments, the following steps are taken:
This function is not generic. The
.prototype.reduce is a distinct function that implements the same algorithm as Array.prototype.reduce as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.reduceRight is a distinct function that implements the same algorithm as Array.prototype.reduceRight as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.reverse is a distinct function that implements the same algorithm as Array.prototype.reverse as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.set is a single function whose behaviour is overloaded based upon the type of its first argument.
This function is not generic. The
Sets multiple values in this TypedArray, reading the values from the object array. The optional offset value indicates the first element index in this TypedArray where values are written. If omitted, it is assumed to be 0.
"length"))."Unordered").Sets multiple values in this TypedArray, reading the values from the typedArray argument object. The optional offset value indicates the first element index in this TypedArray where values are written. If omitted, it is assumed to be 0.
"Uint8", "Unordered")."Uint8", value, "Unordered")."Unordered")."Unordered").The interpretation and use of the arguments of .prototype.slice are the same as for Array.prototype.slice as defined in
"Uint8", "Unordered")."Uint8", value, "Unordered").This function is not generic. The
.prototype.some is a distinct function that implements the same algorithm as Array.prototype.some as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
.prototype.sort is a distinct function that, except as described below, implements the same requirements as those of Array.prototype.sort as defined in .prototype.sort specification may be optimized with the knowledge that the
This function is not generic. The
Upon entry, the following steps are performed to initialize evaluation of the sort function. These steps are used instead of the entry steps in
The implementation-defined sort order condition for exotic objects is not applied by .prototype.sort.
The following version of .prototype.sort. It performs a numeric comparison rather than the string comparison used in sort method.
When the TypedArray
Because
Returns a new TypedArray object whose element type is the same as this TypedArray and whose ArrayBuffer is the same as the ArrayBuffer of this TypedArray, referencing the elements at begin, inclusive, up to end, exclusive. If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning.
This function is not generic. The
.prototype.toLocaleString is a distinct function that implements the same algorithm as Array.prototype.toLocaleString as defined in "length". The implementation of the algorithm may be optimized with the knowledge that the
This function is not generic.
If the ECMAScript implementation includes the ECMA-402 Internationalization API this function is based upon the algorithm for Array.prototype.toLocaleString that is in the ECMA-402 specification.
The initial value of the .prototype.toString Array.prototype.toString method defined in
The following steps are taken:
"value").The initial value of the @@iterator property is the same .prototype.values property.
prototype[@@toStringTag] is an
This property has the attributes { [[Enumerable]]:
The initial value of the name property of this function is "get [Symbol.toStringTag]".
Each TypedArray
extends clause of a class definition. Subclass constructors that intend to inherit the specified TypedArray behaviour must include a super call to the TypedArray %TypedArray%.prototype built-in methods.length property whose value is 3.This description applies only if the TypedArray function is called with no arguments.
"%TypedArrayPrototype%", 0).This description applies only if the TypedArray function is called with at least one argument and the Type of the first argument is not Object.
TypedArray called with argument length performs the following steps:
"%TypedArrayPrototype%", elementLength).The abstract operation AllocateTypedArray with arguments constructorName, newTarget, defaultProto and optional argument length is used to validate and create an instance of a TypedArray
The abstract operation AllocateTypedArrayBuffer with arguments O and length allocates and associates an ArrayBuffer with the TypedArray instance O. It performs the following steps:
This description applies only if the TypedArray function is called with at least one argument and the Type of the first argument is Object and that object has a [[TypedArrayName]] internal slot.
TypedArray called with argument typedArray performs the following steps:
"%TypedArrayPrototype%")."Unordered")."Unordered").This description applies only if the TypedArray function is called with at least one argument and the Type of the first argument is Object and that object does not have either a [[TypedArrayName]] or an [[ArrayBufferData]] internal slot.
TypedArray called with argument object performs the following steps:
"%TypedArrayPrototype%")."length")).This description applies only if the TypedArray function is called with at least one argument and the Type of the first argument is Object and that object has an [[ArrayBufferData]] internal slot.
TypedArray called with at least one argument buffer performs the following steps:
"%TypedArrayPrototype%").The abstract operation TypedArrayCreate with arguments constructor and argumentList is used to specify the creation of a new TypedArray object using a
The abstract operation TypedArraySpeciesCreate with arguments exemplar and argumentList is used to specify the creation of a new TypedArray object using a
Each TypedArray
name property whose value is the String value of the The value of TypedArray.BYTES_PER_ELEMENT is the
This property has the attributes { [[Writable]]:
The initial value of TypedArray.prototype is the corresponding TypedArray prototype intrinsic object (
This property has the attributes { [[Writable]]:
Each TypedArray prototype object:
The value of TypedArray.prototype.BYTES_PER_ELEMENT is the
This property has the attributes { [[Writable]]:
The initial value of a TypedArray.prototype.constructor is the corresponding %TypedArray% intrinsic object.
TypedArray instances are
Map objects are collections of key/value pairs where both the keys and values may be arbitrary ECMAScript language values. A distinct key value may only occur in one key/value pair within the Map's collection. Distinct key values are discriminated using the
Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structures used in this Map objects specification is only intended to describe the required observable semantics of Map objects. It is not intended to be a viable implementation model.
The Map
Map property of the extends clause of a class definition. Subclass constructors that intend to inherit the specified Map behaviour must include a super call to the Map Map.prototype built-in methods.When the Map function is called with optional argument, the following steps are taken:
"%MapPrototype%", « [[MapData]] »)."set")."0")."1").If the parameter iterable is present, it is expected to be an object that implements an @@iterator method that returns an iterator object that produces a two element
The Map
The initial value of Map.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
Map[@@species] is an
The value of the name property of this function is "get [Symbol.species]".
Methods that create derived collection objects should call @@species to determine the
The Map prototype object:
The following steps are taken:
The initial value of Map.prototype.constructor is the intrinsic object
The following steps are taken:
The value
The following steps are taken:
"key+value").When the forEach method is called with one or two arguments, the following steps are taken:
callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each key/value pair present in the map object, in key insertion order. callbackfn is called only for keys of the map which actually exist; it is not called for keys that have been deleted from the map.
If a thisArg parameter is provided, it will be used as the
callbackfn is called with three arguments: the value of the item, the key of the item, and the Map object being traversed.
forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn. Each entry of a map's [[MapData]] is only visited once. New keys added after the call to forEach begins are visited. A key will be revisited if it is deleted after it has been visited and then re-added before the forEach call completes. Keys that are deleted after the call to forEach begins and before being visited are not visited unless the key is added again before the forEach call completes.
The following steps are taken:
The following steps are taken:
The following steps are taken:
"key").The following steps are taken:
Map.prototype.size is an
The following steps are taken:
"value").The initial value of the @@iterator property is the same entries property.
The initial value of the @@toStringTag property is the String value "Map".
This property has the attributes { [[Writable]]:
Map instances are ordinary objects that inherit properties from the Map prototype. Map instances also have a [[MapData]] internal slot.
A Map Iterator is an object, that represents a specific iteration over some specific Map instance object. There is not a named
Several methods of Map objects return Iterator objects. The abstract operation CreateMapIterator with arguments map and kind is used to create such iterator objects. It performs the following steps:
The %MapIteratorPrototype% object:
"key", let result be e.[[Key]]."value", let result be e.[[Value]]."key+value".The initial value of the @@toStringTag property is the String value "Map Iterator".
This property has the attributes { [[Writable]]:
Map Iterator instances are ordinary objects that inherit properties from the
| Internal Slot | Description |
|---|---|
| [[Map]] | The Map object that is being iterated. |
| [[MapNextIndex]] |
The |
| [[MapIterationKind]] |
A String value that identifies what is to be returned for each element of the iteration. The possible values are: "key", "value", "key+value".
|
Set objects are collections of ECMAScript language values. A distinct value may only occur once as an element of a Set's collection. Distinct values are discriminated using the
Set objects must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structures used in this Set objects specification is only intended to describe the required observable semantics of Set objects. It is not intended to be a viable implementation model.
The Set
Set property of the extends clause of a class definition. Subclass constructors that intend to inherit the specified Set behaviour must include a super call to the Set Set.prototype built-in methods.When the Set function is called with optional argument iterable, the following steps are taken:
"%SetPrototype%", « [[SetData]] »)."add").The Set
The initial value of Set.prototype is the intrinsic
This property has the attributes { [[Writable]]:
Set[@@species] is an
The value of the name property of this function is "get [Symbol.species]".
Methods that create derived collection objects should call @@species to determine the
The Set prototype object:
The following steps are taken:
The following steps are taken:
The initial value of Set.prototype.constructor is the intrinsic object
The following steps are taken:
The value
The following steps are taken:
"key+value").For iteration purposes, a Set appears similar to a Map where each entry has the same value for its key and value.
When the forEach method is called with one or two arguments, the following steps are taken:
callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each value present in the set object, in value insertion order. callbackfn is called only for values of the Set which actually exist; it is not called for keys that have been deleted from the set.
If a thisArg parameter is provided, it will be used as the
callbackfn is called with three arguments: the first two arguments are a value contained in the Set. The same value is passed for both arguments. The Set object being traversed is passed as the third argument.
The callbackfn is called with three arguments to be consistent with the call back functions used by forEach methods for Map and Array. For Sets, each item value is considered to be both the key and the value.
forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
Each value is normally visited only once. However, a value will be revisited if it is deleted after it has been visited and then re-added before the forEach call completes. Values that are deleted after the call to forEach begins and before being visited are not visited unless the value is added again before the forEach call completes. New values added after the call to forEach begins are visited.
The following steps are taken:
The initial value of the keys property is the same values property.
For iteration purposes, a Set appears similar to a Map where each entry has the same value for its key and value.
Set.prototype.size is an
The following steps are taken:
"value").The initial value of the @@iterator property is the same values property.
The initial value of the @@toStringTag property is the String value "Set".
This property has the attributes { [[Writable]]:
Set instances are ordinary objects that inherit properties from the Set prototype. Set instances also have a [[SetData]] internal slot.
A Set Iterator is an ordinary object, with the structure defined below, that represents a specific iteration over some specific Set instance object. There is not a named
Several methods of Set objects return Iterator objects. The abstract operation CreateSetIterator with arguments set and kind is used to create such iterator objects. It performs the following steps:
The %SetIteratorPrototype% object:
"key+value", thenThe initial value of the @@toStringTag property is the String value "Set Iterator".
This property has the attributes { [[Writable]]:
Set Iterator instances are ordinary objects that inherit properties from the
| Internal Slot | Description |
|---|---|
| [[IteratedSet]] | The Set object that is being iterated. |
| [[SetNextIndex]] |
The |
| [[SetIterationKind]] |
A String value that identifies what is to be returned for each element of the iteration. The possible values are: "key", "value", "key+value". "key" and "value" have the same meaning.
|
WeakMap objects are collections of key/value pairs where the keys are objects and values may be arbitrary ECMAScript language values. A WeakMap may be queried to see if it contains a key/value pair with a specific key, but no mechanism is provided for enumerating the objects it holds as keys. If an object that is being used as the key of a WeakMap key/value pair is only reachable by following a chain of references that start within that WeakMap, then that key/value pair is inaccessible and is automatically removed from the WeakMap. WeakMap implementations must detect and remove such key/value pairs and any associated resources.
An implementation may impose an arbitrarily determined latency between the time a key/value pair of a WeakMap becomes inaccessible and the time when the key/value pair is removed from the WeakMap. If this latency was observable to ECMAScript program, it would be a source of indeterminacy that could impact program execution. For that reason, an ECMAScript implementation must not provide any means to observe a key of a WeakMap that does not require the observer to present the observed key.
WeakMap objects must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of key/value pairs in the collection. The data structure used in this WeakMap objects specification are only intended to describe the required observable semantics of WeakMap objects. It is not intended to be a viable implementation model.
WeakMap and WeakSets are intended to provide mechanisms for dynamically associating state with an object in a manner that does not “leak” memory resources if, in the absence of the WeakMap or WeakSet, the object otherwise became inaccessible and subject to resource reclamation by the implementation's garbage collection mechanisms. This characteristic can be achieved by using an inverted per-object mapping of weak map instances to keys. Alternatively each weak map may internally store its key to value mappings but this approach requires coordination between the WeakMap or WeakSet implementation and the garbage collector. The following references describe mechanism that may be useful to implementations of WeakMap and WeakSets:
Barry Hayes. 1997. Ephemerons: a new finalization mechanism. In Proceedings of the 12th ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications (OOPSLA '97), A. Michael Berman (Ed.). ACM, New York, NY, USA, 176-183, http://doi.acm.org/10.1145/263698.263733.
Alexandra Barros, Roberto Ierusalimschy, Eliminating Cycles in Weak Tables. Journal of Universal Computer Science - J.UCS, vol. 14, no. 21, pp. 3481-3497, 2008, http://www.jucs.org/jucs_14_21/eliminating_cycles_in_weak
The WeakMap
WeakMap property of the extends clause of a class definition. Subclass constructors that intend to inherit the specified WeakMap behaviour must include a super call to the WeakMap WeakMap.prototype built-in methods.When the WeakMap function is called with optional argument iterable, the following steps are taken:
"%WeakMapPrototype%", « [[WeakMapData]] »)."set")."0")."1").If the parameter iterable is present, it is expected to be an object that implements an @@iterator method that returns an iterator object that produces a two element