ES6 Support In Chromium

This is a list of ECMAScript6 features allowed in Chromium code.

This is not a status list of v8's support for language features.

TBD: Do we need to differentiate per-project?

TBD: Cross-platform build support? As in: transpilers?

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.

Some descriptions and Usage examples are from kangax and http://es6-features.org/

Allowed Features

The following features are allowed in Chromium development.

=> (Arrow Functions)

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:

Note: => does not work in iOS9. Don‘t use it in code that runs on Chrome for iOS. There’s a presubmit that should warn you about this.

Discussion thread


Promise

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} */
var 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);

Documentation: link link

Discussion Notes: Feature already extensively used prior to creation of this document.


Classes

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: let 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() {
    var 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

Note: Not fully supported in iOS9. Don't use it in code that runs on Chrome for iOS, unless you can verify it works. TODO: Remove this note once support for iOS9 is dropped.


Map

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:

var map = new Map();
map.size === 0;  // true
map.get('foo');  // undefined

var 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

Documentation: link link

Discussion Notes: Feature already extensively used prior to creation of this document.


Set

An object that lets you store unique values of any type, whether primitive values or object references.

Usage Example:

var set = new Set();

set.add(123);
set.size();  // 1
set.has(123);  // true

set.add(123);
set.size();  // 1

Documentation: link link

Discussion Notes: Feature already extensively used prior to creation of this document.


let (Block-Scoped Variables)

let declares a variable within the scope of a block. This differs from var, which uses function level scope.

Usage Example:

// Scope.
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

Note: let is not fully supported in iOS9. Don't use it in code that runs on Chrome for iOS, until support for iOS9 is dropped.


const (Block-Scoped Constants)

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.

Also note that in Chrome, const is block scoped 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

Note: const not fully supported in iOS9. Don't use it in code that runs on Chrome for iOS, until support for iOS9 is dropped.


Array Static & Prototype Methods

Usage Example:

// Static methods
let a1 = Array.from(document.querySelectorAll('div'));
let 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

Note: Array.prototype.values is not implemented in Chrome and should not be used. If the code in question is Closure compiled, a compile-time error will be thrown.


Number Properties

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


Object Static Methods

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


for...of Loops

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 (let n of fibonacci) {
  console.log(n);  // 1, 1, 2, 3, ...
}

Documentation: link1 link2

Discussion Notes / Link to Thread: link


Template Literals

Expression interpolation for Strings, with the ability to access raw template pieces.

Usage Example:

// Simple example
let greeting = 'hello';
let myName = {first: 'Foo', last: 'Bar'};
let from = 1900;
let 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:


Banned Features

The following features are banned for Chromium development.

Features To Be Discussed

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.

Block Scope Functions

Usage Example:

{
  function foo() {
    return 1;
  }
  // foo() === 1
  {
    function foo() {
      return 2;
    }
    // foo() === 2
  }
  // foo() === 1
}

Documentation: link

Discussion Notes / Link to Thread:


Default Function Parameters

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.

Documentation: link link

Discussion Notes / Link to Thread:


Rest Parameters

Aggregation of function arguments into one Array variable.

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:


Spread Operators

Spreading the elements from an iterable collection into individual literals as function parameters.

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:


Object Literal Extensions

Convenient new ways for object property definition.

Usage Example:

// Computed property name
var prop = 'foo';
var o = {
  [prop]: 'hey',
  ['b' + 'ar']: 'there',
};
console.log(o);  // {foo: 'hey', bar: 'there'}

// Shorthand property
var foo = 1;
var bar = 2;
var o = {foo, bar};
console.log(o);  // {foo: 1, bar: 2}

// Method property
var 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

Documentation: link link

Discussion Notes / Link to Thread:


Binary & Octal Literals

Usage Example:

0b111110111 === 503;
0o767 === 503;

Documentation: link

Discussion Notes / Link to Thread:


/u Unicode Regex Literal

Usage Example:

'𠮷'.match(/./u)[0].length === 2;

Documentation: link

Discussion Notes / Link to Thread:


\u{} Unicode String

Usage Example:

'\u{1d306}' == '\ud834\udf06';  // true

Documentation: link

Discussion Notes / Link to Thread:


/y Regex Sticky Matching

Keep 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:


Destructuring Assignment

Flexible destructuring of collections or parameters.

Usage Example:

// Array
var [a, , b] = [1, 2, 3];  // a = 1, b = 3

// Object
var {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});

Documentation: link

Discussion Notes / Link to Thread:


Modules

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';

Documentation: link

Discussion Notes / Link to Thread:


Symbol Type

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
let 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:


String Static & Prototype methods

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:


Iterators

Usage Example:

let 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:


Generators

Special iterators with specified pausing points.

Usage Example:

function* range(start, end, step) {
  while (start < end) {
    yield start;
    start += step;
  }
}

for (let i of range(0, 10, 2)) {
  console.log(i);  // 0, 2, 4, 6, 8
}

Documentation: link

Discussion Notes / Link to Thread:


WeakMap

WeakMap does not prevent garbage collection if nothing else refers to an object within the collection.

Usage Example:

var key = {};
var weakmap = new WeakMap();

weakmap.set(key, 123);

weakmap.has(key) && weakmap.get(key) === 123;  // true

Documentation: link

Discussion Notes / Link to Thread:


WeakSet

WeakSet does not prevent garbage collection if nothing else refers to an object within the collection.

Usage Example:

var obj1 = {};
var weakset = new WeakSet();

weakset.add(obj1);
weakset.add(obj1);

weakset.has(obj1);  // true

Documentation: link

Discussion Notes / Link to Thread:


Typed Arrays

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:


Proxy

Hooking into runtime-level object meta-operations.

Usage Example:

var 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:


Reflection

Make calls corresponding to the object meta-operations.

Usage Example:

let 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:


Math Methods

A lot of new Math methods.

Usage Example:

// See Doc

Documentation: link

Discussion Notes / Link to Thread: