My favorite ES6

A few ways ES6 removes boilerplate code.

A few of my favorite ES6 features that help me write less boilerplate code.

Property shortcuts

1
2
3
4
5
6
const name = 'joe'
const age = 21
exports = {
name: name,
age: age
}
1
2
3
4
5
6
7
// es6
const name = 'joe'
const age = 21
exports = {
name,
age
}

Read http://es6-features.org/#PropertyShorthand

Destructuring

1
2
3
4
// es5
const path = require('path')
const join = path.join
const relative = path.relative
1
2
// es6
const {join, relative} = require('path')

Read http://es6-features.org/#ObjectMatchingShorthandNotation and Parameter destructuring.

Default values

1
2
3
4
5
6
7
8
// es5
function f (x, y, z) {
if (y === undefined)
y = 7;
if (z === undefined)
z = 42;
return x + y + z;
};
1
2
3
4
// es6
function f (x, y = 7, z = 42) {
return x + y + z
}

Read http://es6-features.org/#DefaultParameterValues

Separate arguments

1
2
3
4
5
// ES5: need all arguments after "y"
function f(x, y) {
var a = Array.prototype.slice.call(arguments, 2);
...
};

We could use a utility library

1
2
3
4
5
6
const _ = require('lodash')
function f(x, y) {
// need all arguments after "y"
var a = _.toArray(arguments).slice(2);
...
};

But the best is ES6 "rest" operator

1
2
3
4
5
// ES6
function f(x, y, ...a) {
// a is an array of arguments after "y"
...
};

Read http://es6-features.org/#RestParameter

Computed keys

1
2
3
4
// es5
var foo = '...'; // dynamic
var o = {};
o[foo] = 42;
1
2
3
4
5
// es6
var foo = '...';
var o = {
[foo]: 42
}

Read http://es6-features.org/#ComputedPropertyNames

Arrow functions

1
2
3
numbers.map(function (v) { return v + 1 })
// es6
numbers.map(v => v + 1)

For clarity I prefer Ramda functions

1
2
3
var R = require('ramda')
var add1 = R.add(1)
numbers.map(add1)

But arrow functions make tiny "curried" functions so simple, especially for making callbacks

1
2
3
4
5
6
7
8
const foo = options => value => {
// do something with options, value
}
const options = {...}
promise()
// "value" argument will be passed from previous promise
.then(foo(options))
// foo(options) "waits" for "value" argument