ES6 – . . .



ES6 – . . .

0 0


ES6-features


On Github aackerman / ES6-features

ES6

ECMA-262 - the standard

TC39 - the committee

JavaScript - embedded in history

EcmaScript releases

  • 1: 1997
  • 2: 1998
  • 3: 1999
  • 4: (╯°□°)╯︵┻━┻
  • 5: 2005
  • 6: Forthcoming

Arrows Functions

function() {
  var self = this;
  $xhr = $.ajax({ ... })
  $xhr.then(function(){
    self.otherFunc();
  });
}

Old and busted

function() {
  var $xhr = $.ajax({ ... })
  $xhr.then((response) => {
    this.otherFunc(response);
  });
}

New hotness

() => {...}
x => x * x
  • Implicit return for an expression
  • Optional block for an expression
  • Optional parens for a single argument
  • Lexical this

[1,2,3].reduce((x, y) => x + y, 0); // 6

Simple reduce

String methods

String.prototype.startsWith

String.prototype.startsWith = function(s) {
  return this.indexOf(s) === 0;
};

String.prototype.endsWith

String.prototype.endsWith = function(s) {
  var t = String(s);
  var index = this.lastIndexOf(t);
  return index >= 0 && index === this.length - t.length;
};

String.prototype.contains

String.prototype.contains = function(s) {
  return this.indexOf(s) !== -1;
};

String.prototype.toArray

String.prototype.toArray = function() {
  return this.split('');
};

String.prototype.repeat

String.prototype.repeat = function(n) {
  var n = n || 1;
  return Array(n + 1).join(this);
}

String.fromCodePoint

String.fromCodePoint(0x41); // -> 'A'

polyfill here

String.prototype.codePointAt

Returns the code point for a given index of a string

polyfill here

Array methods

Array.from

Array.from = function(arrayLike) {
  return Array.prototype.slice.call(arrayLike);
}

Array.of

Array.of = function() {
  return Array.prototype.slice.call(arguments);
};

Array.prototype.find

Returns the first element that matches a predicate

Analogous to _.find

Array.prototype.findIndex

Returns the first index that matches a predicate or -1

Array.prototype.fill

Fill an array with a value based on a starting and ending index

Number additions

  • isFinite()
  • isInteger()
  • isSafeInteger()
  • isNaN()
  • EPSILON
  • MIN_SAFE_INTEGER
  • MAX_SAFE_INTEGER

Math additions

  • clz32c()
  • imulc()
  • signc()
  • log10()
  • log2()
  • log1p()
  • expm1()
  • cosh()
  • sinh()
  • tanh()
  • acosh()
  • asinh()
  • atanh()
  • hypot()
  • trunc()
  • fround()
  • cbrt()
const

Constants existed in C since 1972.

Finally making it to JS, 20 years after inception.

Static assignment, throws on an attempt to reassign.

let
  • Scoped to a single block
  • Must be declared before use
  • Cannot be declared multiple times in single block
  • Can be declared multiple times in single function
function add(x, y = 5){ return x + y }

Default Parameters

. . .

Rest Parameters

function() { var args = Array.prototype.slice.call(arguments); }

Old and busted

function (...args) { }

New hotness

args is a real JS Array and not an Array-like object

arguments object is not available along side rest parameters

. . .

Spread Operator

Used to spread an array into positional arguments

function f(x, y, z) {
  return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6

Class syntax

class Chicken {
  constructor() {
    this.wings = 2;
  }
  hasBones() {
    return true;
  }
}
  • Constructor initializers
  • Inheritance
  • Super calls
  • Static functions
  • Sugar on top of current sematics
  • Native built-ins can be extended

extends syntax

Allows extension of native built-ins

class MyArray extends Array {
  constructor() { constructor(...args) { super(...args); } }
}

Acts as a real Array with its length property updated accordingly when elements are added or removed

Object literal enhancements

var handler = function(){}
var obj = {
  // Shorthand for ‘handler: handler’
  handler,
  // no longer requires key or function key word
  // super calls
  toString() {
    return 'obj' + super.toString();
  }
}

Computer Property Names in Object literals

var x = 'z';
var foo = { [x]: 1 };
console.log(foo['z']); // 1

Destructuring

{ a, b } = { a: 'a', b: 'b', c: 'c', d: 'd'}

Can be deeply nested

Defines variables in current scope

Doesn't throw, can return undefined

[a] = []; // a == undefined

var a = 1;
var b = 3;

[a, b] = [b, a];

Simple swap operation with no temp variables

Map and Sets

Map

var m = new Map();
m.set('hello', 42);
m.get('hello'); // 42

Allows any type of object as a key

Set

var s = new Set();
s.add('hello').add('world');
s.has('hello') == true; // true
s.size == 2; // true
s.delete('world');
s.size == 1; // true
s.clear;

Sets have unique elements

WeakMap

var s = { foo: 'bar' }
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.get(s); // { extra: 42 }

Object-only keyed maps with weakly held references

If the external references fall out of scope, they fall out of the map

WeakSet

var ws = new WeakSet();
ws.add({ hello: 42 });
ws.size == undefined; // true

No external references mean it cannot be held in the set

Template strings

let x = 'multi-line';
`a real

${x} JS

string`

Multiline strings using `backticks`

Interpolation using ${variable} syntax

Sugar for string construction

Object.assign( target, ...sources )

Analogous to _.extend or $.extend

No recursive option :(

Object.is

Essentially triple equals with special handling for NaN and +0/-0

Object.is(NaN, NaN); // trueNaN === NaN // false

Native Promises

Smaller library dependencies

Libraries will still be used for sugar

let p = new Promise();
p.then((value) => {
  console.log(value);
}, (err) => {
  console.log(err);
})
p.fulfill('hello'); // hello

DOM promises are coming separately from ES6

ES6 Promises are a superset of DOM promises

Modules

// lib/math.js
export function sum(x, y) {
  return x + y;
}
export var pi = 3.141593;

A simple module that exports a function and a variable

export default

Sets the default import value

// hello.js
export default function() { console.log('hello') }
import hello from 'hello.js'
hello() // hello

export * from 'math';

Used to easily export everything from another library and provide extensions or overrides

Module loaders

System.import('lib/math').then(function(m) {
  alert("2π = " + m.sum(m.pi, m.pi));
});

Built-in async module loader, with promises

Proxies

Traps and runtime Meta-operations on objects

  • get
  • set
  • has
  • deleteProperty
  • apply
  • construct
  • getOwnPropertyDescriptor
  • defineProperty
  • getPrototypeOf
  • setPrototypeOf
  • enumerate
  • ownKeys
  • preventExtensions
  • isExtensible
var target = {};
var handler = {
  get: function (receiver, name) {
    return `Hello, ${name}!`;
  }
};

var p = new Proxy(target, handler);
p.world === 'Hello, world!';

What I didn't cover

  • Reflection API
  • Symbols
  • Array Comprehensions
  • Generators/yield
  • Iterators
  • Tail Calls
  • For...of loops
  • Unicode additions
  • Regexp 'u' and 'y' flags
  • Classes in-depth
  • >Modules in-depth

Using parts of ES6 right now

References