Don't forget to bookmark us! Press CTRL+D / CMD + D  |  

Ecma Script 6 Features Cheat Sheet40

We provide you with all the ES6 new features with comprehensible examples with comparision with ES5 version. This cheat sheet will help you know quickly get what you are looking for. You can even search for the particular function, try it.

No result found

 Constants

 Constants
ES 6 Version
1
2
  const PI = 3.141593;
3
  PI > 3.0;
ES 5 Version
1
2
  //  only in ES5 through the help of object properties
3
  //  and only in global context and not in a block scope
4
  Object.defineProperty(typeof global === "object" ? global : window, "PI", {
5
      value:        3.141593,
6
      enumerable:   true,
7
      writable:     false,
8
      configurable: false
9
  })
10
  PI > 3.0;

 Scoping

 Block-Scoped Variables
ES 6 Version
1
2
  for (let i = 0; i < a.length; i++) {
3
      let x = a[i];
4
      
5
  }
6
  for (let i = 0; i < b.length; i++) {
7
      let y = b[i];
8
      
9
  }
10
  
11
  let callbacks = [];
12
  for (let i = 0; i <= 2; i++) {
13
      callbacks[i] = function () { return i * 2; };
14
  }
15
  callbacks[0]() === 0;
16
  callbacks[1]() === 2;
17
  callbacks[2]() === 4;
ES 5 Version
1
2
  var i, x, y;
3
  for (i = 0; i < a.length; i++) {
4
      x = a[i];
5
      
6
  }
7
  for (i = 0; i < b.length; i++) {
8
      y = b[i];
9
      
10
  }
11
  
12
  var callbacks = [];
13
  for (var i = 0; i <= 2; i++) {
14
      (function (i) {
15
          callbacks[i] = function() { return i * 2; };
16
      })(i);
17
  }
18
  callbacks[0]() === 0;
19
  callbacks[1]() === 2;
20
  callbacks[2]() === 4;
 Block-Scoped Functions
ES 6 Version
1
2
  {
3
      function foo () { return 1; }
4
      foo() === 1;
5
      {
6
          function foo () { return 2; }
7
          foo() === 2;
8
      }
9
      foo() === 1;
10
  }
ES 5 Version
1
2
  //  only in ES5 with the help of block-scope emulating
3
  //  function scopes and function expressions
4
  (function () {
5
      var foo = function () { return 1; }
6
      foo() === 1;
7
      (function () {
8
          var foo = function () { return 2; }
9
          foo() === 2;
10
      })();
11
      foo() === 1;
12
  })();

 Arrow Functions

 Expression Bodies
ES 6 Version
1
2
  odds  = evens.map(v => v + 1);
3
  pairs = evens.map(v => ({ even: v, odd: v + 1 }));
4
  nums  = evens.map((v, i) => v + i);
ES 5 Version
1
2
  odds  = evens.map(function (v) { return v + 1; });
3
  pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
4
  nums  = evens.map(function (v, i) { return v + i; });
 Statement Bodies
ES 6 Version
1
2
  nums.forEach(v => {
3
     if (v % 5 === 0)
4
         fives.push(v);
5
  })
ES 5 Version
1
2
  nums.forEach(function (v) {
3
     if (v % 5 === 0)
4
         fives.push(v);
5
  });
 Lexical this
ES 6 Version
1
2
  this.nums.forEach((v) => {
3
      if (v % 5 === 0)
4
          this.fives.push(v);
5
  });
ES 5 Version
1
2
  //  variant 1
3
  var self = this;
4
  this.nums.forEach(function (v) {
5
      if (v % 5 === 0)
6
          self.fives.push(v);
7
  });
8
  
9
  //  variant 2
10
  this.nums.forEach(function (v) {
11
      if (v % 5 === 0)
12
          this.fives.push(v);
13
  }, this);
14
  
15
  //  variant 3 (since ECMAScript 5.1 only)
16
  this.nums.forEach(function (v) {
17
      if (v % 5 === 0)
18
          this.fives.push(v);
19
  }.bind(this));

 Extended Parameter Handling

 Default Parameter Values
ES 6 Version
1
2
  function f (x, y = 7, z = 42) {
3
      return x + y + z;
4
  }
5
  f(1) === 50;
ES 5 Version
1
2
  function f (x, y, z) {
3
      if (y === undefined)
4
          y = 7;
5
      if (z === undefined)
6
          z = 42;
7
      return x + y + z;
8
  };
9
  f(1) === 50;
 Rest Parameter
ES 6 Version
1
2
  function f (x, y, ...a) {
3
      return (x + y) * a.length;
4
  }
5
  f(1, 2, "hello", true, 7) === 9;
ES 5 Version
1
2
  function f (x, y) {
3
      var a = Array.prototype.slice.call(arguments, 2);
4
      return (x + y) * a.length;
5
  };
6
  f(1, 2, "hello", true, 7) === 9;
 Spread Operator
ES 6 Version
1
2
  var params = [ "hello", true, 7 ];
3
  var other = [ 1, 2, ...params ]; // [ 1, 2, "hello", true, 7 ]
4
  
5
  function f (x, y, ...a) {
6
      return (x + y) * a.length;
7
  }
8
  f(1, 2, ...params) === 9;
9
  
10
  var str = "foo";
11
  var chars = [ ...str ]; // [ "f", "o", "o" ]
ES 5 Version
1
2
  var params = [ "hello", true, 7 ];
3
  var other = [ 1, 2 ].concat(params); // [ 1, 2, "hello", true, 7 ]
4
  
5
  function f (x, y) {
6
      var a = Array.prototype.slice.call(arguments, 2);
7
      return (x + y) * a.length;
8
  };
9
  f.apply(undefined, [ 1, 2 ].concat(params)) === 9;
10
  
11
  var str = "foo";
12
  var chars = str.split(""); // [ "f", "o", "o" ]

 Template Literals

 String Interpolation
ES 6 Version
1
2
  var customer = { name: "Foo" };
3
  var card = { amount: 7, product: "Bar", unitprice: 42 };
4
  var message = `Hello ${customer.name},
5
  want to buy ${card.amount} ${card.product} for
6
  a total of ${card.amount * card.unitprice} bucks?`;
ES 5 Version
1
2
  var customer = { name: "Foo" };
3
  var card = { amount: 7, product: "Bar", unitprice: 42 };
4
  var message = "Hello " + customer.name + ",\n" +
5
  "want to buy " + card.amount + " " + card.product + " for\n" +
6
  "a total of " + (card.amount * card.unitprice) + " bucks?";
 Custom Interpolation
ES 6 Version
1
2
  get`http://example.com/foo?bar=${bar + baz}&quux=${quux}`;
ES 5 Version
1
2
  get([ "http://example.com/foo?bar=", "&quux=", "" ],bar + baz, quux);
 Raw String Access
ES 6 Version
1
2
  function quux (strings, ...values) {
3
      strings[0] === "foo\n";
4
      strings[1] === "bar";
5
      strings.raw[0] === "foo\\n";
6
      strings.raw[1] === "bar";
7
      values[0] === 42;
8
  }
9
  quux`foo\n${ 42 }bar`
10
  
11
  String.raw`foo\n${ 42 }bar` === "foo\\n42bar";
ES 5 Version
1
2
  //  no equivalent in ES5

 Extended Literals

 Binary & Octal Literal
ES 6 Version
1
2
  0b111110111 === 503;
3
  0o767 === 503;
ES 5 Version
1
2
  parseInt("111110111", 2) === 503;
3
  parseInt("767", 8) === 503;
4
  0767 === 503; // only in non-strict, backward compatibility mode
 Unicode String & RegExp Literal
ES 6 Version
1
2
  "𠮷".length === 2;
3
  "𠮷".match(/./u)[0].length === 2;
4
  "𠮷" === "\uD842\uDFB7";
5
  "𠮷" === "\u{20BB7}";
6
  "𠮷".codePointAt(0) == 0x20BB7;
7
  for (let codepoint of "𠮷") console.log(codepoint);
ES 5 Version
1
2
  "𠮷".length === 2;
3
  "𠮷".match(/(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF][\uD800-\uDBFF][\uDC00-\uDFFF][\uD800-\uDBFF](?![\uDC00-\uDFFF])(?:[^\uD800-\uDBFF]^)[\uDC00-\uDFFF])/)[0].length === 2;
4
  "𠮷" === "\uD842\uDFB7";
5
  //  no equivalent in ES5
6
  //  no equivalent in ES5
7
  //  no equivalent in ES5

 Enhanced Regular Expression

 Regular Expression Sticky Matching
ES 6 Version
1
2
  let parser = (input, match) => {
3
      for (let pos = 0, lastPos = input.length; pos < lastPos; ) {
4
          for (let i = 0; i < match.length; i++) {
5
              match[i].pattern.lastIndex = pos;
6
              let found;
7
              if ((found = match[i].pattern.exec(input)) !== null) {
8
                  match[i].action(found);
9
                  pos = match[i].pattern.lastIndex;
10
                  break;
11
              }
12
          }
13
      }
14
  }
15
  
16
  let report = (match) => {
17
      console.log(JSON.stringify(match));
18
  };
19
  parser("Foo 1 Bar 7 Baz 42", [
20
      { pattern: /Foo\s+(\d+)/y, action: (match) => report(match) },
21
      { pattern: /Bar\s+(\d+)/y, action: (match) => report(match) },
22
      { pattern: /Baz\s+(\d+)/y, action: (match) => report(match) },
23
      { pattern: /\s*/y,         action: (match) => {}            }
24
  ]);
ES 5 Version
1
2
  var parser = function (input, match) {
3
      for (var i, found, inputTmp = input; inputTmp !== ""; ) {
4
          for (i = 0; i < match.length; i++) {
5
              if ((found = match[i].pattern.exec(inputTmp)) !== null) {
6
                  match[i].action(found);
7
                  inputTmp = inputTmp.substr(found[0].length);
8
                  break;
9
              }
10
          }
11
      }
12
  }
13
  
14
  var report = function (match) {
15
      console.log(JSON.stringify(match));
16
  };
17
  parser("Foo 1 Bar 7 Baz 42", [
18
      { pattern: /^Foo\s+(\d+)/, action: function (match) { report(match); } },
19
      { pattern: /^Bar\s+(\d+)/, action: function (match) { report(match); } },
20
      { pattern: /^Baz\s+(\d+)/, action: function (match) { report(match); } },
21
      { pattern: /^\s*/,         action: function (match) {}                 }
22
  ]);

 Enhanced Object Properties

 Property Shorthand
ES 6 Version
1
2
  var x = 0, y = 0;
3
  obj = { x, y };
ES 5 Version
1
2
  var x = 0, y = 0;
3
  obj = { x: x, y: y };
 Computed Property Names
ES 6 Version
1
2
  let obj = {
3
      foo: "bar",
4
      [ "baz" + quux() ]: 42
5
  };
ES 5 Version
1
2
  var obj = {
3
      foo: "bar"
4
  };
5
  obj[ "baz" + quux() ] = 42;
 Method Properties
ES 6 Version
1
2
  obj = {
3
      foo (a, b) {
4
          
5
      },
6
      bar (x, y) {
7
          
8
      },
9
      *quux (x, y) {
10
          
11
      }
12
  };
ES 5 Version
1
2
  obj = {
3
      foo: function (a, b) {
4
          
5
      },
6
      bar: function (x, y) {
7
          
8
      },
9
      //  quux: no equivalent in ES5
10
      
11
  };

 Destructuring Assignment

 Array Matching
ES 6 Version
1
2
  var list = [ 1, 2, 3 ];
3
  var [ a, , b ] = list;
4
  [ b, a ] = [ a, b ];
ES 5 Version
1
2
  var list = [ 1, 2, 3 ];
3
  var a = list[0], b = list[2];
4
  var tmp = a; a = b; b = tmp;
 Object Matching, Shorthand Notation
ES 6 Version
1
2
  var { op, lhs, rhs } = getASTNode();
ES 5 Version
1
2
  var tmp = getASTNode();
3
  var op  = tmp.op;
4
  var lhs = tmp.lhs;
5
  var rhs = tmp.rhs;
 Object Matching, Deep Matching
ES 6 Version
1
2
  var { op: a, lhs: { op: b }, rhs: c } = getASTNode();
ES 5 Version
1
2
  var tmp = getASTNode();
3
  var a = tmp.op;
4
  var b = tmp.lhs.op;
5
  var c = tmp.rhs;
 Object And Array Matching, Default Values
ES 6 Version
1
2
  var obj = { a: 1 };
3
  var list = [ 1 ];
4
  var { a, b = 2 } = obj;
5
  var [ x, y = 2 ] = list;
ES 5 Version
1
2
  var obj = { a: 1 };
3
  var list = [ 1 ];
4
  var a = obj.a;
5
  var b = obj.b === undefined ? 2 : obj.b;
6
  var x = list[0];
7
  var y = list[1] === undefined ? 2 : list[1];
 Parameter Context Matching
ES 6 Version
1
2
  function f ([ name, val ]) {
3
      console.log(name, val);
4
  }
5
  function g ({ name: n, val: v }) {
6
      console.log(n, v);
7
  }
8
  function h ({ name, val }) {
9
      console.log(name, val);
10
  }
11
  f([ "bar", 42 ]);
12
  g({ name: "foo", val:  7 });
13
  h({ name: "bar", val: 42 });
ES 5 Version
1
2
  function f (arg) {
3
      var name = arg[0];
4
      var val  = arg[1];
5
      console.log(name, val);
6
  };
7
  function g (arg) {
8
      var n = arg.name;
9
      var v = arg.val;
10
      console.log(n, v);
11
  };
12
  function h (arg) {
13
      var name = arg.name;
14
      var val  = arg.val;
15
      console.log(name, val);
16
  };
17
  f([ "bar", 42 ]);
18
  g({ name: "foo", val:  7 });
19
  h({ name: "bar", val: 42 });
 Fail-Soft Destructuring
ES 6 Version
1
2
  var list = [ 7, 42 ];
3
  var [ a = 1, b = 2, c = 3, d ] = list;
4
  a === 7;
5
  b === 42;
6
  c === 3;
7
  d === undefined;
ES 5 Version
1
2
  var list = [ 7, 42 ];
3
  var a = typeof list[0] !== "undefined" ? list[0] : 1;
4
  var b = typeof list[1] !== "undefined" ? list[1] : 2;
5
  var c = typeof list[2] !== "undefined" ? list[2] : 3;
6
  var d = typeof list[3] !== "undefined" ? list[3] : undefined;
7
  a === 7;
8
  b === 42;
9
  c === 3;
10
  d === undefined;

 Modules

 Value Export/Import
ES 6 Version
1
2
  //  lib/math.js
3
  export function sum (x, y) { return x + y };
4
  export var pi = 3.141593;
5
  
6
  //  someApp.js
7
  import * as math from "lib/math";
8
  console.log("2π = " + math.sum(math.pi, math.pi));
9
  
10
  //  otherApp.js
11
  import { sum, pi } from "lib/math";
12
  console.log("2π = " + sum(pi, pi));
ES 5 Version
1
2
  //  lib/math.js
3
  LibMath = {};
4
  LibMath.sum = function (x, y) { return x + y };
5
  LibMath.pi = 3.141593;
6
  
7
  //  someApp.js
8
  var math = LibMath;
9
  console.log("2π = " + math.sum(math.pi, math.pi));
10
  
11
  //  otherApp.js
12
  var sum = LibMath.sum, pi = LibMath.pi;
13
  console.log("2π = " + sum(pi, pi));
 Default & Wildcard
ES 6 Version
1
2
  //  lib/mathplusplus.js
3
  export * from "lib/math";
4
  export var e = 2.71828182846;
5
  export default (x) => Math.exp(x);
6
  
7
  //  someApp.js
8
  import exp, { pi, e } from "lib/mathplusplus";
9
  console.log("e^{π} = " + exp(pi));
ES 5 Version
1
2
  //  lib/mathplusplus.js
3
  LibMathPP = {};
4
  for (symbol in LibMath)
5
      if (LibMath.hasOwnProperty(symbol))
6
          LibMathPP[symbol] = LibMath[symbol];
7
  LibMathPP.e = 2.71828182846;
8
  LibMathPP.exp = function (x) { return Math.exp(x) };
9
  
10
  //  someApp.js
11
  var exp = LibMathPP.exp, pi = LibMathPP.pi, e = LibMathPP.e;
12
  console.log("e^{π} = " + exp(pi));

 Classes

 Class Definition
ES 6 Version
1
2
  class Shape {
3
      constructor (id, x, y) {
4
          this.id = id;
5
          this.move(x, y);
6
      }
7
      move (x, y) {
8
          this.x = x;
9
          this.y = y;
10
      }
11
  }
ES 5 Version
1
2
  var Shape = function (id, x, y) {
3
      this.id = id;
4
      this.move(x, y);
5
  };
6
  Shape.prototype.move = function (x, y) {
7
      this.x = x;
8
      this.y = y;
9
  };
 Class Inheritance
ES 6 Version
1
2
  class Rectangle extends Shape {
3
      constructor (id, x, y, width, height) {
4
          super(id, x, y);
5
          this.width  = width;
6
          this.height = height;
7
      }
8
  }
9
  class Circle extends Shape {
10
      constructor (id, x, y, radius) {
11
          super(id, x, y);
12
          this.radius = radius;
13
      }
14
  }
ES 5 Version
1
2
  var Rectangle = function (id, x, y, width, height) {
3
      Shape.call(this, id, x, y);
4
      this.width  = width;
5
      this.height = height;
6
  };
7
  Rectangle.prototype = Object.create(Shape.prototype);
8
  Rectangle.prototype.constructor = Rectangle;
9
  var Circle = function (id, x, y, radius) {
10
      Shape.call(this, id, x, y);
11
      this.radius = radius;
12
  };
13
  Circle.prototype = Object.create(Shape.prototype);
14
  Circle.prototype.constructor = Circle;
 Class Inheritance, From Expressions
ES 6 Version
1
2
  var aggregation = (baseClass, ...mixins) => {
3
      let base = class _Combined extends baseClass {
4
          constructor (...args) {
5
              super(...args);
6
              mixins.forEach((mixin) => {
7
                  mixin.prototype.initializer.call(this);
8
              });
9
          }
10
      };
11
      let copyProps = (target, source) => {
12
          Object.getOwnPropertyNames(source)
13
              .concat(Object.getOwnPropertySymbols(source))
14
              .forEach((prop) => {
15
              if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
16
                  return
17
              Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))
18
          })
19
      }
20
      mixins.forEach((mixin) => {
21
          copyProps(base.prototype, mixin.prototype);
22
          copyProps(base, mixin);
23
      });
24
      return base;
25
  };
26
  
27
  class Colored {
28
      initializer ()     { this._color = "white"; }
29
      get color ()       { return this._color; }
30
      set color (v)      { this._color = v; }
31
  }
32
  
33
  class ZCoord {
34
      initializer ()     { this._z = 0; }
35
      get z ()           { return this._z; }
36
      set z (v)          { this._z = v; }
37
  }
38
  
39
  class Shape {
40
      constructor (x, y) { this._x = x; this._y = y; }
41
      get x ()           { return this._x; }
42
      set x (v)          { this._x = v; }
43
      get y ()           { return this._y; }
44
      set y (v)          { this._y = v; }
45
  }
46
  
47
  class Rectangle extends aggregation(Shape, Colored, ZCoord) {}
48
  
49
  var rect = new Rectangle(7, 42);
50
  rect.z     = 1000;
51
  rect.color = "red";
52
  console.log(rect.x, rect.y, rect.z, rect.color);
ES 5 Version
1
2
  var aggregation = function (baseClass, mixins) {
3
      var base = function () {
4
          baseClass.apply(this, arguments);
5
          mixins.forEach(function (mixin) {
6
              mixin.prototype.initializer.call(this);
7
          }.bind(this));
8
      };
9
      base.prototype = Object.create(baseClass.prototype);
10
      base.prototype.constructor = base;
11
      var copyProps = function (target, source) {
12
          Object.getOwnPropertyNames(source).forEach(function (prop) {
13
              if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
14
                  return
15
              Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))
16
          })
17
      }
18
      mixins.forEach(function (mixin) {
19
          copyProps(base.prototype, mixin.prototype);
20
          copyProps(base, mixin);
21
      });
22
      return base;
23
  };
24
  
25
  var Colored = function () {};
26
  Colored.prototype = {
27
      initializer: function ()  { this._color = "white"; },
28
      getColor:    function ()  { return this._color; },
29
      setColor:    function (v) { this._color = v; }
30
  };
31
  
32
  var ZCoord = function () {};
33
  ZCoord.prototype = {
34
      initializer: function ()  { this._z = 0; },
35
      getZ:        function ()  { return this._z; },
36
      setZ:        function (v) { this._z = v; }
37
  };
38
  
39
  var Shape = function (x, y) {
40
      this._x = x; this._y = y;
41
  };
42
  Shape.prototype = {
43
      getX: function ()  { return this._x; },
44
      setX: function (v) { this._x = v; },
45
      getY: function ()  { return this._y; },
46
      setY: function (v) { this._y = v; }
47
  }
48
  
49
  var _Combined = aggregation(Shape, [ Colored, ZCoord ]);
50
  var Rectangle = function (x, y) {
51
      _Combined.call(this, x, y);
52
  };
53
  Rectangle.prototype = Object.create(_Combined.prototype);
54
  Rectangle.prototype.constructor = Rectangle;
55
  
56
  var rect = new Rectangle(7, 42);
57
  rect.setZ(1000);
58
  rect.setColor("red");
59
  console.log(rect.getX(), rect.getY(), rect.getZ(), rect.getColor());
 Base Class Access
ES 6 Version
1
2
  class Shape {
3
      
4
      toString () {
5
          return `Shape(${this.id})`
6
      }
7
  }
8
  class Rectangle extends Shape {
9
      constructor (id, x, y, width, height) {
10
          super(id, x, y);
11
          
12
      }
13
      toString () {
14
          return "Rectangle > " + super.toString();
15
      }
16
  }
17
  class Circle extends Shape {
18
      constructor (id, x, y, radius) {
19
          super(id, x, y);
20
          
21
      }
22
      toString () {
23
          return "Circle > " + super.toString();
24
      }
25
  }
ES 5 Version
1
2
  var Shape = function (id, x, y) {
3
      
4
  };
5
  Shape.prototype.toString = function (x, y) {
6
      return "Shape(" + this.id + ")"
7
  };
8
  var Rectangle = function (id, x, y, width, height) {
9
      Shape.call(this, id, x, y);
10
      
11
  };
12
  Rectangle.prototype.toString = function () {
13
      return "Rectangle > " + Shape.prototype.toString.call(this);
14
  };
15
  var Circle = function (id, x, y, radius) {
16
      Shape.call(this, id, x, y);
17
      
18
  };
19
  Circle.prototype.toString = function () {
20
      return "Circle > " + Shape.prototype.toString.call(this);
21
  };
 Static Members
ES 6 Version
1
2
  class Rectangle extends Shape {
3
      
4
      static defaultRectangle () {
5
          return new Rectangle("default", 0, 0, 100, 100);
6
      }
7
  }
8
  class Circle extends Shape {
9
      
10
      static defaultCircle () {
11
          return new Circle("default", 0, 0, 100);
12
      }
13
  }
14
  var defRectangle = Rectangle.defaultRectangle();
15
  var defCircle    = Circle.defaultCircle();
ES 5 Version
1
2
  var Rectangle = function (id, x, y, width, height) {
3
      
4
  };
5
  Rectangle.defaultRectangle = function () {
6
      return new Rectangle("default", 0, 0, 100, 100);
7
  };
8
  var Circle = function (id, x, y, width, height) {
9
      
10
  };
11
  Circle.defaultCircle = function () {
12
      return new Circle("default", 0, 0, 100);
13
  };
14
  var defRectangle = Rectangle.defaultRectangle();
15
  var defCircle    = Circle.defaultCircle();
 Getter/Setter
ES 6 Version
1
2
  class Rectangle {
3
      constructor (width, height) {
4
          this._width  = width;
5
          this._height = height;
6
      }
7
      set width  (width)  { this._width = width;               }
8
      get width  ()       { return this._width;                }
9
      set height (height) { this._height = height;             }
10
      get height ()       { return this._height;               }
11
      get area   ()       { return this._width * this._height; }
12
  };
13
  var r = new Rectangle(50, 20);
14
  r.area === 1000;
ES 5 Version
1
2
  var Rectangle = function (width, height) {
3
      this._width  = width;
4
      this._height = height;
5
  };
6
  Rectangle.prototype = {
7
      set width  (width)  { this._width = width;               },
8
      get width  ()       { return this._width;                },
9
      set height (height) { this._height = height;             },
10
      get height ()       { return this._height;               },
11
      get area   ()       { return this._width * this._height; }
12
  };
13
  var r = new Rectangle(50, 20);
14
  r.area === 1000;

 Symbol Type

 Symbol Type
ES 6 Version
1
2
  Symbol("foo") !== Symbol("foo");
3
  const foo = Symbol();
4
  const bar = Symbol();
5
  typeof foo === "symbol";
6
  typeof bar === "symbol";
7
  let obj = {};
8
  obj[foo] = "foo";
9
  obj[bar] = "bar";
10
  JSON.stringify(obj); // {}
11
  Object.keys(obj); // []
12
  Object.getOwnPropertyNames(obj); // []
13
  Object.getOwnPropertySymbols(obj); // [ foo, bar ]
ES 5 Version
1
2
  // no equivalent in ES5
 Global Symbols
ES 6 Version
1
2
  Symbol.for("app.foo") === Symbol.for("app.foo")
3
  const foo = Symbol.for("app.foo");
4
  const bar = Symbol.for("app.bar");
5
  Symbol.keyFor(foo) === "app.foo";
6
  Symbol.keyFor(bar) === "app.bar";
7
  typeof foo === "symbol";
8
  typeof bar === "symbol";
9
  let obj = {};
10
  obj[foo] = "foo";
11
  obj[bar] = "bar";
12
  JSON.stringify(obj); // {}
13
  Object.keys(obj); // []
14
  Object.getOwnPropertyNames(obj); // []
15
  Object.getOwnPropertySymbols(obj); // [ foo, bar ]
ES 5 Version
1
2
  // no equivalent in ES5

 Iterators

 Iterator & For-Of Operator
ES 6 Version
1
2
  let fibonacci = {
3
      [Symbol.iterator]() {
4
          let pre = 0, cur = 1;
5
          return {
6
             next () {
7
                 [ pre, cur ] = [ cur, pre + cur ];
8
                 return { done: false, value: cur };
9
             }
10
          };
11
      }
12
  }
13
  
14
  for (let n of fibonacci) {
15
      if (n > 1000)
16
          break;
17
      console.log(n);
18
  }
ES 5 Version
1
2
  var fibonacci = {
3
      next: (function () {
4
          var pre = 0, cur = 1;
5
          return function () {
6
              tmp = pre;
7
              pre = cur;
8
              cur += tmp;
9
              return cur;
10
          };
11
      })()
12
  };
13
  
14
  var n;
15
  for (;;) {
16
      n = fibonacci.next();
17
      if (n > 1000)
18
          break;
19
      console.log(n);
20
  }

 Generators

 Generator Function, Iterator Protocol
ES 6 Version
1
2
  let fibonacci = {
3
      *[Symbol.iterator]() {
4
          let pre = 0, cur = 1;
5
          for (;;) {
6
              [ pre, cur ] = [ cur, pre + cur ];
7
              yield cur;
8
          }
9
      }
10
  }
11
  
12
  for (let n of fibonacci) {
13
      if (n > 1000)
14
          break;
15
      console.log(n);
16
  }
ES 5 Version
1
2
  var fibonacci = {
3
      next: (function () {
4
          var pre = 0, cur = 1;
5
          return function () {
6
              tmp = pre;
7
              pre = cur;
8
              cur += tmp;
9
              return cur;
10
          };
11
      })()
12
  };
13
  
14
  var n;
15
  for (;;) {
16
      n = fibonacci.next();
17
      if (n > 1000)
18
          break;
19
      console.log(n);
20
  }
 Generator Function, Direct Use
ES 6 Version
1
2
  function* range (start, end, step) {
3
      while (start < end) {
4
          yield start;
5
          start += step;
6
      }
7
  }
8
  
9
  for (let i of range(0, 10, 2)) {
10
      console.log(i); // 0, 2, 4, 6, 8
11
  }
ES 5 Version
1
2
  function range (start, end, step) {
3
      var list = [];
4
      while (start < end) {
5
          list.push(start);
6
          start += step;
7
      }
8
      return list;
9
  }
10
  
11
  var r = range(0, 10, 2);
12
  for (var i = 0; i < r.length; i++) {
13
      console.log(r[i]); // 0, 2, 4, 6, 8
14
  }
 Generator Matching
ES 6 Version
1
2
  let fibonacci = function* (numbers) {
3
      let pre = 0, cur = 1;
4
      while (numbers-- > 0) {
5
          [ pre, cur ] = [ cur, pre + cur ];
6
          yield cur;
7
      }
8
  };
9
  
10
  for (let n of fibonacci(1000))
11
      console.log(n);
12
  
13
  let numbers = [ ...fibonacci(1000) ];
14
  
15
  let [ n1, n2, n3, ...others ] = fibonacci(1000);
ES 5 Version
1
2
  //  no equivalent in ES5
 Generator Control-Flow
ES 6 Version
1
2
  //  generic asynchronous control-flow driver
3
  function async (proc, ...params) {
4
      let iterator = proc(...params);
5
      return new Promise((resolve, reject) => {
6
          let loop = (value) => {
7
              let result;
8
              try {
9
                  result = iterator.next(value);
10
              }
11
              catch (err) {
12
                  reject(err);
13
              }
14
              if (result.done)
15
                  resolve(result.value);
16
              else if (   typeof result.value      === "object"
17
                       && typeof result.value.then === "function")
18
                  result.value.then((value) => {
19
                      loop(value);
20
                  }, (err) => {
21
                      reject(err);
22
                  });
23
              else
24
                  loop(result.value);
25
          }
26
          loop();
27
      });
28
  }
29
  
30
  //  application-specific asynchronous builder
31
  function makeAsync (text, after) {
32
      return new Promise((resolve, reject) => {
33
          setTimeout(() => resolve(text), after);
34
      });
35
  }
36
  
37
  //  application-specific asynchronous procedure
38
  async(function* (greeting) {
39
      let foo = yield makeAsync("foo", 300)
40
      let bar = yield makeAsync("bar", 200)
41
      let baz = yield makeAsync("baz", 100)
42
      return `${greeting} ${foo} ${bar} ${baz}`
43
  }, "Hello").then((msg) => {
44
      console.log("RESULT:", msg); // "Hello foo bar baz"
45
  })
ES 5 Version
1
2
  //  no equivalent in ES5
 Generator Methods
ES 6 Version
1
2
  class Clz {
3
      * bar () {
4
          
5
      }
6
  };
7
  let Obj = {
8
      * foo () {
9
          
10
      }
11
  };
ES 5 Version
1
2
  //  no equivalent in ES5

 Map/Set & WeakMap/WeakSet

 Set Data-Structure
ES 6 Version
1
2
  let s = new Set();
3
  s.add("hello").add("goodbye").add("hello");
4
  s.size === 2;
5
  s.has("hello") === true;
6
  for (let key of s.values()) // insertion order
7
      console.log(key);
ES 5 Version
1
2
  var s = {};
3
  s["hello"] = true; s["goodbye"] = true; s["hello"] = true;
4
  Object.keys(s).length === 2;
5
  s["hello"] === true;
6
  for (var key in s) // arbitrary order
7
      if (s.hasOwnProperty(key))
8
          console.log(s[key]);
 Map Data-Structure
ES 6 Version
1
2
  let m = new Map();
3
  let s = Symbol();
4
  m.set("hello", 42);
5
  m.set(s, 34);
6
  m.get(s) === 34;
7
  m.size === 2;
8
  for (let [ key, val ] of m.entries())
9
      console.log(key + " = " + val);
ES 5 Version
1
2
  var m = {};
3
  // no equivalent in ES5
4
  m["hello"] = 42;
5
  // no equivalent in ES5
6
  // no equivalent in ES5
7
  Object.keys(m).length === 2;
8
  for (key in m) {
9
      if (m.hasOwnProperty(key)) {
10
          var val = m[key];
11
          console.log(key + " = " + val);
12
      }
13
  }
 Weak-Link Data-Structures
ES 6 Version
1
2
  let isMarked     = new WeakSet();
3
  let attachedData = new WeakMap();
4
  
5
  export class Node {
6
      constructor (id)   { this.id = id;                  }
7
      mark        ()     { isMarked.add(this);            }
8
      unmark      ()     { isMarked.delete(this);         }
9
      marked      ()     { return isMarked.has(this);     }
10
      set data    (data) { attachedData.set(this, data);  }
11
      get data    ()     { return attachedData.get(this); }
12
  }
13
  
14
  let foo = new Node("foo");
15
  
16
  JSON.stringify(foo) === '{"id":"foo"}';
17
  foo.mark();
18
  foo.data = "bar";
19
  foo.data === "bar";
20
  JSON.stringify(foo) === '{"id":"foo"}';
21
  
22
  isMarked.has(foo)     === true
23
  attachedData.has(foo) === true
24
  foo = null  /* remove only reference to foo */
25
  attachedData.has(foo) === false
26
  isMarked.has(foo)     === false
ES 5 Version
1
2
  // no equivalent in ES5

 Typed Arrays

 Typed Arrays
ES 6 Version
1
2
  //  ES6 class equivalent to the following C structure:
3
  //  struct Example { unsigned long id; char username[16]; float amountDue; };
4
  class Example {
5
      constructor (buffer = new ArrayBuffer(24)) {
6
          this.buffer = buffer;
7
      }
8
      set buffer (buffer) {
9
          this._buffer    = buffer;
10
          this._id        = new Uint32Array (this._buffer,  0,  1);
11
          this._username  = new Uint8Array  (this._buffer,  4, 16);
12
          this._amountDue = new Float32Array(this._buffer, 20,  1);
13
      }
14
      get buffer ()     { return this._buffer;       }
15
      set id (v)        { this._id[0] = v;           }
16
      get id ()         { return this._id[0];        }
17
      set username (v)  { this._username[0] = v;     }
18
      get username ()   { return this._username[0];  }
19
      set amountDue (v) { this._amountDue[0] = v;    }
20
      get amountDue ()  { return this._amountDue[0]; }
21
  }
22
  
23
  let example = new Example()
24
  example.id = 7
25
  example.username = "John Doe"
26
  example.amountDue = 42.0
ES 5 Version
1
2
  //  no equivalent in ES5
3
  //  (only an equivalent in HTML5)

 New Built-In Methods

 Object Property Assignment
ES 6 Version
1
2
  var dest = { quux: 0 };
3
  var src1 = { foo: 1, bar: 2 };
4
  var src2 = { foo: 3, baz: 4 };
5
  Object.assign(dest, src1, src2);
6
  dest.quux === 0;
7
  dest.foo  === 3;
8
  dest.bar  === 2;
9
  dest.baz  === 4;
ES 5 Version
1
2
  var dest = { quux: 0 };
3
  var src1 = { foo: 1, bar: 2 };
4
  var src2 = { foo: 3, baz: 4 };
5
  Object.keys(src1).forEach(function(k) {
6
      dest[k] = src1[k];
7
  });
8
  Object.keys(src2).forEach(function(k) {
9
      dest[k] = src2[k];
10
  });
11
  dest.quux === 0;
12
  dest.foo  === 3;
13
  dest.bar  === 2;
14
  dest.baz  === 4;
 Array Element Finding
ES 6 Version
1
2
  [ 1, 3, 4, 2 ].find(x => x > 3); // 4
3
  [ 1, 3, 4, 2 ].findIndex(x => x > 3); // 2
ES 5 Version
1
2
  [ 1, 3, 4, 2 ].filter(function (x) { return x > 3; })[0]; // 4
3
  // no equivalent in ES5
 String Repeating
ES 6 Version
1
2
  " ".repeat(4 * depth);
3
  "foo".repeat(3);
ES 5 Version
1
2
  Array((4 * depth) + 1).join(" ");
3
  Array(3 + 1).join("foo");
 String Searching
ES 6 Version
1
2
  "hello".startsWith("ello", 1); // true
3
  "hello".endsWith("hell", 4);   // true
4
  "hello".includes("ell");       // true
5
  "hello".includes("ell", 1);    // true
6
  "hello".includes("ell", 2);    // false
ES 5 Version
1
2
  "hello".indexOf("ello") === 1;    // true
3
  "hello".indexOf("hell") === (4 - "hell".length); // true
4
  "hello".indexOf("ell") !== -1;    // true
5
  "hello".indexOf("ell", 1) !== -1; // true
6
  "hello".indexOf("ell", 2) !== -1; // false
 Number Type Checking
ES 6 Version
1
2
  Number.isNaN(42) === false;
3
  Number.isNaN(NaN) === true;
4
  
5
  Number.isFinite(Infinity) === false;
6
  Number.isFinite(-Infinity) === false;
7
  Number.isFinite(NaN) === false;
8
  Number.isFinite(123) === true;
ES 5 Version
1
2
  var isNaN = function (n) {
3
      return n !== n;
4
  };
5
  var isFinite = function (v) {
6
      return (typeof v === "number" && !isNaN(v) && v !== Infinity && v !== -Infinity);
7
  };
8
  isNaN(42) === false;
9
  isNaN(NaN) === true;
10
  
11
  isFinite(Infinity) === false;
12
  isFinite(-Infinity) === false;
13
  isFinite(NaN) === false;
14
  isFinite(123) === true;
 Number Safety Checking
ES 6 Version
1
2
  Number.isSafeInteger(42) === true;
3
  Number.isSafeInteger(9007199254740992) === false;
ES 5 Version
1
2
  function isSafeInteger (n) {
3
      return (
4
             typeof n === 'number'
5
          && Math.round(n) === n
6
          && -(Math.pow(2, 53) - 1) <= n
7
          && n <= (Math.pow(2, 53) - 1)
8
      );
9
  }
10
  isSafeInteger(42) === true;
11
  isSafeInteger(9007199254740992) === false;
 Number Comparison
ES 6 Version
1
2
  console.log(0.1 + 0.2 === 0.3); // false
3
  console.log(Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON); // true
ES 5 Version
1
2
  console.log(0.1 + 0.2 === 0.3); // false
3
  console.log(Math.abs((0.1 + 0.2) - 0.3) < 2.220446049250313e-16); // true
 Number Truncation
ES 6 Version
1
2
  console.log(Math.trunc(42.7)) // 42
3
  console.log(Math.trunc( 0.1)) // 0
4
  console.log(Math.trunc(-0.1)) // -0
ES 5 Version
1
2
  function mathTrunc (x) {
3
      return (x < 0 ? Math.ceil(x) : Math.floor(x));
4
  }
5
  console.log(mathTrunc(42.7)) // 42
6
  console.log(mathTrunc( 0.1)) // 0
7
  console.log(mathTrunc(-0.1)) // -0
 Number Sign Determination
ES 6 Version
1
2
  console.log(Math.sign(7))   // 1
3
  console.log(Math.sign(0))   // 0
4
  console.log(Math.sign(-0))  // -0
5
  console.log(Math.sign(-7))  // -1
6
  console.log(Math.sign(NaN)) // NaN
ES 5 Version
1
2
  function mathSign (x) {
3
      return ((x === 0 || isNaN(x)) ? x : (x > 0 ? 1 : -1));
4
  }
5
  console.log(mathSign(7))   // 1
6
  console.log(mathSign(0))   // 0
7
  console.log(mathSign(-0))  // -0
8
  console.log(mathSign(-7))  // -1
9
  console.log(mathSign(NaN)) // NaN

 Promises

 Promise Usage
ES 6 Version
1
2
  function msgAfterTimeout (msg, who, timeout) {
3
      return new Promise((resolve, reject) => {
4
          setTimeout(() => resolve(`${msg} Hello ${who}!`), timeout);
5
      });
6
  }
7
  msgAfterTimeout("", "Foo", 100).then((msg) =>
8
      msgAfterTimeout(msg, "Bar", 200)
9
  ).then((msg) => {
10
      console.log(`done after 300ms:${msg}`);
11
  });
ES 5 Version
1
2
  function msgAfterTimeout (msg, who, timeout, onDone) {
3
      setTimeout(function () {
4
          onDone(msg + " Hello " + who + "!");
5
      }, timeout);
6
  }
7
  msgAfterTimeout("", "Foo", 100, function (msg) {
8
      msgAfterTimeout(msg, "Bar", 200, function (msg) {
9
          console.log("done after 300ms:" + msg);
10
      });
11
  });
 Promise Combination
ES 6 Version
1
2
  function fetchAsync (url, timeout, onData, onError) {
3
      
4
  }
5
  let fetchPromised = (url, timeout) => {
6
      return new Promise((resolve, reject) => {
7
          fetchAsync(url, timeout, resolve, reject);
8
      });
9
  }
10
  Promise.all([
11
      fetchPromised("http://backend/foo.txt", 500),
12
      fetchPromised("http://backend/bar.txt", 500),
13
      fetchPromised("http://backend/baz.txt", 500)
14
  ]).then((data) => {
15
      let [ foo, bar, baz ] = data;
16
      console.log(`success: foo=${foo} bar=${bar} baz=${baz}`);
17
  }, (err) => {
18
      console.log(`error: ${err}`);
19
  });
ES 5 Version
1
2
  function fetchAsync (url, timeout, onData, onError) {
3
      
4
  }
5
  function fetchAll (request, onData, onError) {
6
      var result = [], results = 0;
7
      for (var i = 0; i < request.length; i++) {
8
          result[i] = null;
9
          (function (i) {
10
              fetchAsync(request[i].url, request[i].timeout, function (data) {
11
                  result[i] = data;
12
                  if (++results === request.length)
13
                      onData(result);
14
              }, onError);
15
          })(i);
16
      }
17
  }
18
  fetchAll([
19
      { url: "http://backend/foo.txt", timeout: 500 },
20
      { url: "http://backend/bar.txt", timeout: 500 },
21
      { url: "http://backend/baz.txt", timeout: 500 }
22
  ], function (data) {
23
      var foo = data[0], bar = data[1], baz = data[2];
24
      console.log("success: foo=" + foo + " bar=" + bar + " baz=" + baz);
25
  }, function (err) {
26
      console.log("error: " + err);
27
  });

 Meta-Programming

 Proxying
ES 6 Version
1
2
  let target = {
3
      foo: "Welcome, foo"
4
  };
5
  let proxy = new Proxy(target, {
6
      get (receiver, name) {
7
          return name in receiver ? receiver[name] : `Hello, ${name}`;
8
      }
9
  });
10
  proxy.foo   === "Welcome, foo";
11
  proxy.world === "Hello, world";
ES 5 Version
1
2
  // no equivalent in ES5
 Reflection
ES 6 Version
1
2
  let obj = { a: 1 };
3
  Object.defineProperty(obj, "b", { value: 2 });
4
  obj[Symbol("c")] = 3;
5
  Reflect.ownKeys(obj); // [ "a", "b", Symbol(c) ]
ES 5 Version
1
2
  var obj = { a: 1 };
3
  Object.defineProperty(obj, "b", { value: 2 });
4
  // no equivalent in ES5
5
  Object.getOwnPropertyNames(obj); // [ "a", "b" ]

 Internationalization & Localization

 Collation
ES 6 Version
1
2
  // in German,  "ä" sorts with "a"
3
  // in Swedish, "ä" sorts after "z"
4
  var list = [ "ä", "a", "z" ];
5
  var l10nDE = new Intl.Collator("de");
6
  var l10nSV = new Intl.Collator("sv");
7
  l10nDE.compare("ä", "z") === -1;
8
  l10nSV.compare("ä", "z") === +1;
9
  console.log(list.sort(l10nDE.compare)); // [ "a", "ä", "z" ]
10
  console.log(list.sort(l10nSV.compare)); // [ "a", "z", "ä" ]
ES 5 Version
1
2
  // no equivalent in ES5
 Number Formatting
ES 6 Version
1
2
  var l10nEN = new Intl.NumberFormat("en-US");
3
  var l10nDE = new Intl.NumberFormat("de-DE");
4
  l10nEN.format(1234567.89) === "1,234,567.89";
5
  l10nDE.format(1234567.89) === "1.234.567,89";
ES 5 Version
1
2
  // no equivalent in ES5
 Currency Formatting
ES 6 Version
1
2
  var l10nUSD = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
3
  var l10nGBP = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" });
4
  var l10nEUR = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
5
  l10nUSD.format(100200300.40) === "$100,200,300.40";
6
  l10nGBP.format(100200300.40) === "£100,200,300.40";
7
  l10nEUR.format(100200300.40) === "100.200.300,40 €";
ES 5 Version
1
2
  // no equivalent in ES5
 Date/Time Formatting
ES 6 Version
1
2
  var l10nEN = new Intl.DateTimeFormat("en-US");
3
  var l10nDE = new Intl.DateTimeFormat("de-DE");
4
  l10nEN.format(new Date("2015-01-02")) === "1/2/2015";
5
  l10nDE.format(new Date("2015-01-02")) === "2.1.2015";
ES 5 Version
1
2
  // no equivalent in ES5

Alternative URLs

An alternative base URL is a domain you own (or subdomain) which points to your website.


Ecma Script 6 Features
https://ohmycheatsheet.com/ecma-script-6-features/
Ecma Script 6 Features Cheat Sheet 2020
https://ohmycheatsheet.com/ecma-script-6-features-cheat-sheet-2020/
Es6
https://ohmycheatsheet.com/es6/
Es6 Cheat Sheet
https://ohmycheatsheet.com/es6-cheat-sheet/
Ecma Script 6
https://ohmycheatsheet.com/ecma-script-6/
Ecma Script 6 Cheat Sheet
https://ohmycheatsheet.com/ecma-script-6-cheat-sheet/
Ecma Script 2015
https://ohmycheatsheet.com/ecma-script-2015/
Ecma Script 2015 Cheat Sheet
https://ohmycheatsheet.com/ecma-script-2015-cheat-sheet/
Try HTML/CSS