This doc extends the style guide by specifying which new features of ES2015 and beyond are allowed in Chromium.
You can propose changing the status of a feature by sending an email to chromium-dev@chromium.org. Include a short blurb on what the feature is and why you think it should or should not be allowed, along with links to any relevant previous discussion. If the list arrives at some consensus, send a codereview to change this file accordingly, linking to your discussion thread.
This is a list of ECMAScript 6 a.k.a. ES2015 features allowed in Chromium code.
This is not a status list of V8's support for language features.
Some descriptions and usage examples were taken from kangax and http://es6-features.org/
The following features are allowed in Chromium development.
Arrow functions provide a concise syntax to create a function, and fix a number of difficulties with this
(e.g. eliminating the need to write const self = this
). Particularly useful for nested functions or callbacks.
Prefer arrow functions over .bind(this)
.
Arrow functions have an implicit return when used without a body block.
Usage Example:
// General usage, eliminating need for .bind(this). setTimeout(() => { this.doSomething(); }, 1000); // no need for .bind(this) or const self = this. // Another example... window.addEventListener('scroll', (event) => { this.doSomething(event); }); // no need for .bind(this) or const self = this. // Implicit return: returns the value if expression not inside a body block. () => 1 // returns 1. () => {1} // returns undefined - body block does not implicitly return. () => {return 1;} // returns 1.
Documentation: link
Discussion Notes / Link to Thread: link
The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never.
Usage Example:
/** @type {!Promise} */ const fullyLoaded = new Promise(function(resolve) { function isLoaded() { return document.readyState == 'complete'; } if (isLoaded()) { resolve(); } else { document.onreadystatechange = function() { if (isLoaded()) resolve(); }; } }); // ... some time later ... fullyLoaded.then(startTheApp).then(maybeShowFirstRun);
Discussion Notes: Feature already extensively used prior to creation of this document.
Hooking into runtime-level object meta-operations.
Usage Example:
const keyTracker = new Proxy({}, { keysCreated: 0, get (receiver, key) { if (key in receiver) { console.log('key already exists'); } else { ++this.keysCreated; console.log(this.keysCreated + ' keys created!'); receiver[key] = true; } }, }); keyTracker.key1; // '1 keys created!' keyTracker.key1; // 'key already exists' keyTracker.key2; // '2 keys created!'
Documentation: link
Discussion Notes / Link to Thread: link
OOP-style and boilerplate-free class syntax, including inheritance, super()
, static members, and getters and setters.
Usage Example:
class Shape { constructor(x, y) { this.x = x; this.y = y; } } // Note: const Shape = class {...}; is also valid. class Rectangle extends Shape { constructor(x, y, width, height) { super(id, x, y); this.width = width; this.height = height; } static goldenRectangle() { const PHI = (1 + Math.sqrt(5)) / 2; return new Rectangle(0, 0, PHI, 1); } }
Documentation: link
Discussion Notes / Link to Thread: https://groups.google.com/a/chromium.org/d/msg/chromium-dev/S1h-0m2ohOw/jyaiMGDlCwAJ
A simple key/value map in which any value (both objects and primitive values) may be used as either a key or a value.
Usage Example:
const map = new Map(); map.size === 0; // true map.get('foo'); // undefined const key = 54; map.set(key, 123); map.size === 1; // true map.has(key); // true map.get(key); // 123 map.delete(key); map.has(key); // false map.size === 0; // true
Discussion Notes: Feature already extensively used prior to creation of this document.
An object that lets you store unique values of any type, whether primitive values or object references.
Usage Example:
const set = new Set(); set.add(123); set.size(); // 1 set.has(123); // true set.add(123); set.size(); // 1
Discussion Notes: Feature already extensively used prior to creation of this document.
Constants (also known as “immutable variables”) are variables which cannot be re-assigned new content. Note that if the value is an object, the object itself is still mutable.
const
is block-scoped, just like let
.
Usage Example:
const gravity = 9.81; gravity = 0; // TypeError: Assignment to constant variable. gravity === 9.81; // true const frobber = {isFrobbing: true}; frobber = {isFrobbing: false}; // TypeError: Assignment to constant variable. frobber.isFrobbing = false; // Works.
Documentation: link
See also: Object.freeze()
Discussion Notes / Link to Thread: link
let
declares a variable within the scope of a block, like const
. This differs from var
, which uses function-level scope.
Usage Example:
function varTest() { var x = 1; if (true) { var x = 2; // Same variable! console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; if (true) { let x = 2; // Different variable. console.log(x); // 2 } console.log(x); // 1 } // Redeclaration throws. function f() { var a = 'hello'; var a = 'hola'; // No error! let b = 'world'; let b = 'mundo; // TypeError Identifier 'b' has already been declared. }
Documentation: link
Discussion Notes / Link to Thread: link
Usage Example:
// Static methods const a1 = Array.from(document.querySelectorAll('div')); const a2 = Array.of(7); // Prototype methods ['a', 'b', 'c', 'd'].copyWithin(2, 0); // Returns ['a', 'b', 'a', 'b'] [2, 4, 6, 8].find(i => i == 6); // Returns 6 [2, 4, 6, 8].findIndex(i => i == 6); // Returns 2 [2, 4, 6, 8].fill(1); // Returns [1, 1, 1, 1] [2, 4, 6, 8].keys(); // Returns an Array iterator [2, 4, 6, 8].entries(); // Returns an Array iterator
Documentation: link
Discussion Notes / Link to Thread: link
Usage Example:
// Number.isFinite // Number.isInteger // Number.isSafeInteger // Number.isNaN // Number.EPSILON // Number.MIN_SAFE_INTEGER // Number.MAX_SAFE_INTEGER
Documentation: link
Discussion Notes / Link to Thread: link
Usage Example:
// Object.assign var o = Object.assign({a:true}, {b:true}, {c:true}); // {a: true, b: true, c: true} 'a' in o && 'b' in o && 'c' in o; // true // Object.setPrototypeOf Object.setPrototypeOf({}, Array.prototype) instanceof Array; // true // Object.is Object.is(null, null) // true Object.is(NaN, NaN) // true Object.is(-0, +0) // false, btw: -0 === +0 is true
Documentation: link
Discussion Notes / Link to Thread: link
Convenient operator to iterate over all values in an iterable collection. This differs from for...in
, which iterates over all enumerable properties of an object.
Usage Example:
// Given an iterable collection of Fibonacci numbers... for (const n of fibonacci) { console.log(n); // 1, 1, 2, 3, ... }
Discussion Notes / Link to Thread: link
Expression interpolation for Strings, with the ability to access raw template pieces.
Usage Example:
// Simple example const greeting = 'hello'; const myName = {first: 'Foo', last: 'Bar'}; const from = 1900; const to = 2000; var message = `${greeting}, I am ${myName.first}${myName.last}, and I am ${to - from} years old`; // message == 'hello,\nI am FooBar,\nand I am 100 years old'
Documentation: link
Discussion Notes / Link to Thread:
Spreading the elements from an iterable collection into individual literals as function parameters.
This only applies to arrays and not objects.
Usage Example:
// Spreading an Array var params = ['hello', true, 7]; var other = [1, 2, ...params]; // [1, 2, 'hello', true, 7] // Spreading a String var str = 'foo'; var chars = [...str]; // ['f', 'o', 'o']
Documentation: link
Discussion Notes / Link to Thread: link
Aggregation of function arguments into one Array variable.
This only applies to arrays and function parameters, and not objects.
Usage Example:
function usesRestParams(a, b, ...theRest) { console.log(a); // 'a' console.log(b); // 'b' console.log(theRest); // [1, 2, 3] } usesRestParams('a', 'b', 1, 2, 3);
Documentation: link
Discussion Notes / Link to Thread: link
Flexible destructuring of collections or parameters.
Usage Example:
// Array const [a, , b] = [1, 2, 3]; // a = 1, b = 3 // Object const {width, height} = document.body.getBoundingClientRect(); // width = rect.width, height = rect.height // Parameters function f([name, val]) { console.log(name, val); // 'bar', 42 } f(['bar', 42, 'extra 1', 'extra 2']); // 'extra 1' and 'extra 2' are ignored. function g({name: n, val: v}) { console.log(n, v); // 'foo', 7 } g({name: 'foo', val: 7}); function h({name, val}) { console.log(name, val); // 'bar', 42 } h({name: 'bar', val: 42});
Mixing with Rest Parameters
Using rest parameters while destructuring objects is not supported by iOS 10 and requires setting the closure arg language_in
to ECMASCRIPT_2018
.
const {one, ...rest} = {one: 1, two: 2, three: 3};
Using rest parameters while destructuring arrays, on the other hand, is supported by iOS 10 and ECMASCRIPT_2017
.
const [one, ...rest] = [1, 2, 3];
Documentation: link
Discussion Notes / Link to Thread: link
Support for exporting/importing values from/to modules without global namespace pollution.
Usage Example:
// lib/rect.js export function getArea() {...}; export {width, height, unimportant}; // app.js import {getArea, width, height} from './lib/rect.js';
Documentation: link
Discussion Notes / Link to Thread: Dynamic Import link are not allowed yet, see separate entry in the Features To Be Discussed section.
Convenient new ways for object property definition.
Usage Example:
// Computed property name const prop = 'foo'; const o = { [prop]: 'hey', ['b' + 'ar']: 'there', }; console.log(o); // {foo: 'hey', bar: 'there'} // Shorthand property const foo = 1; const bar = 2; const o = {foo, bar}; console.log(o); // {foo: 1, bar: 2} // Method property const clearSky = { // Basically the same as clouds: function() { return 0; }. clouds() { return 0; }, color() { return 'blue'; }, }; console.log(clearSky.color()); // 'blue' console.log(clearSky.clouds()); // 0
Discussion Notes / Link to Thread: https://groups.google.com/a/chromium.org/d/msg/chromium-dev/RqOdTlxuGVg/M7I0CTryDQAJ
Note: clang-format has some issues formatting complex computed property names.
The following features are banned for Chromium development.
The following features are currently disallowed. See the top of this page on how to propose moving a feature from this list into the allowed or banned sections.
Usage Example:
{ function foo() { return 1; } // foo() === 1 { function foo() { return 2; } // foo() === 2 } // foo() === 1 }
Documentation: link
Discussion Notes / Link to Thread:
Initialize parameters with default values if no value or undefined
is passed.
Usage Example:
/** * @param {!Element} element An element to hide. * @param {boolean=} animate Whether to animatedly hide |element|. */ function hide(element, animate=true) { function setHidden() { element.hidden = true; } if (animate) element.animate({...}).then(setHidden); else setHidden(); } hide(document.body); // Animated, animate=true by default. hide(document.body, false); // Not animated.
Discussion Notes / Link to Thread:
Usage Example:
0b111110111 === 503; 0o767 === 503;
Documentation: link
Discussion Notes / Link to Thread:
/u
Unicode Regex LiteralUsage Example:
'𠮷'.match(/./u)[0].length === 2;
Documentation: link
Discussion Notes / Link to Thread:
\u{}
Unicode StringUsage Example:
'\u{1d306}' == '\ud834\udf06'; // true
Documentation: link
Discussion Notes / Link to Thread:
/y
Regex Sticky MatchingKeep the matching position sticky between matches and this way support efficient parsing of arbitrarily long input strings, even with an arbitrary number of distinct regular expressions.
Usage Example:
var re = new RegExp('yy', 'y'); re.lastIndex = 3; var result = re.exec('xxxyyxx')[0]; result === 'yy' && re.lastIndex === 5; // true
Documentation: link
Discussion Notes / Link to Thread:
Dynamic import() introduces a new function-like form of import that returns a promise for the module namespace object of the requested module.
Usage Example:
// lib/rect.js export function getArea() {...}; export {width, height, unimportant}; // app.js if (calculateArea) { import('./lib/rect.js').then(rect => { rect.getArea(...); }); }
Documentation: link
Discussion Notes / Link to Thread:
Unique and immutable data type to be used as an identifier for object properties.
Usage Example:
const foo = Symbol(); const bar = Symbol(); typeof foo === 'symbol'; // true typeof bar === 'symbol'; // true const obj = {}; obj[foo] = 'foo'; obj[bar] = 'bar'; JSON.stringify(obj); // {} Object.keys(obj); // [] Object.getOwnPropertyNames(obj); // [] Object.getOwnPropertySymbols(obj); // [foo, bar]
Documentation: link
Discussion Notes / Link to Thread:
Usage Example:
// String.raw // String.fromCodePoint // String.prototype.codePointAt // String.prototype.normalize // String.prototype.repeat // String.prototype.startsWith // String.prototype.endsWith // String.prototype.includes
Documentation: link
Discussion Notes / Link to Thread:
Usage Example:
const fibonacci = { [Symbol.iterator]() { let pre = 0, cur = 1; return { next () { [pre, cur] = [cur, pre + cur]; return {done: false, value: cur}; } }; } };
Documentation: link
Discussion Notes / Link to Thread:
Special iterators with specified pausing points.
Usage Example:
function* range(start, end, step) { while (start < end) { yield start; start += step; } } for (const i of range(0, 10, 2)) { console.log(i); // 0, 2, 4, 6, 8 }
Documentation: link
Discussion Notes / Link to Thread:
WeakMap does not prevent garbage collection if nothing else refers to an object within the collection.
Usage Example:
const key = {}; const weakmap = new WeakMap(); weakmap.set(key, 123); weakmap.has(key) && weakmap.get(key) === 123; // true
Documentation: link
Discussion Notes / Link to Thread:
WeakSet does not prevent garbage collection if nothing else refers to an object within the collection.
Usage Example:
const obj1 = {}; const weakset = new WeakSet(); weakset.add(obj1); weakset.add(obj1); weakset.has(obj1); // true
Documentation: link
Discussion Notes / Link to Thread:
A lot of new typed Arrays...
Usage Example:
new Int8Array(); new UInt8Array(); new UInt8ClampedArray(); // ... You get the idea. Click on the Documentation link below to see all.
Documentation: link
Discussion Notes / Link to Thread:
Make calls corresponding to the object meta-operations.
Usage Example:
const obj = {a: 1}; Object.defineProperty(obj, 'b', {value: 2}); obj[Symbol('c')] = 3; Reflect.ownKeys(obj); // ['a', 'b', Symbol(c)]
Documentation: link
Discussion Notes / Link to Thread:
A lot of new Math methods.
Usage Example:
// See Doc
Documentation: link
Discussion Notes / Link to Thread:
This is a list of ECMAScript 7 a.k.a. ES2016 features allowed in Chromium code.
The following features are allowed in Chromium development.
The following features are banned for Chromium development.
The following features are currently disallowed. See the top of this page on how to propose moving a feature from this list into the allowed or banned sections.
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Usage Example:
var array1 = [1, 2, 3]; console.log(array1.includes(2)); // expected output: true var pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // expected output: true console.log(pets.includes('at')); // expected output: false
Documentation: link
Discussion Notes / Link to Thread:
This is a list of ECMAScript 8 a.k.a. ES2017 features allowed in Chromium code.
The following features are allowed in Chromium development.
The await expression causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.
Usage Example:
function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveAfter2Seconds(10); console.log(x); // 10 } f1();
Documentation: link
Discussion Notes / Link to Thread: link
The following features are banned for Chromium development.
The following features are currently disallowed. See the top of this page on how to propose moving a feature from this list into the allowed or banned sections.
The padStart() and padEnd() methods pad the current string with another string (multiple times, if needed) until the resulting string reaches the given length.
Usage Example:
const str1 = '5'; console.log(str1.padStart(2, '0')); // expected output: "05" const fullNumber = '2034399002125581'; const last4Digits = fullNumber.slice(-4); const maskedNumber = last4Digits.padStart(fullNumber.length, '*'); console.log(maskedNumber); // expected output: "************5581"
Documentation: link
Discussion Notes / Link to Thread:
The Object.values() method returns an array of a given object‘s own enumerable property values, and Object.entries() method returns an array of a given object’s own enumerable property [key, value] pairs.
Usage Example:
const object1 = { a: 'somestring', b: 42, c: false }; console.log(Object.values(object1)); // expected output: Array ["somestring", 42, false] const object2 = { foo: 'bar', baz: 42 }; console.log(Object.entries(object2)[1]); // expected output: Array ["baz", 42]
Discussion Notes / Link to Thread:
The optional chaining operator makes it easy to chain multiple functions / property accesses that may return null or undefined.
Usage Example:
// Before: const currentKeyboard = keyboards.getCurrentKeyboard(); const keys = currentKeyboard && currentKeyboard.getKeys(); const enterKey = keys && keys.getEnterKey(); // After: const enterKey = keyboards.getCurrentKeyboard()?.getKeys()?.getEnterKey();
Documentation: link
Discussion Notes / Link to Thread: link