Not Sexy
var sumSquares = [1,2,3].map(function(x) {
return x * x;
}).reduce(function(a, b) {
return a + b;
});
console.log(sumSquares); // 14
Sexy
let sumSquares = [1,2,3].map((x)=> x*x)
.reduce((a, b)=> a + b); // no explicit return
console.log(sumSquares); // 14
Not Sexy
function F(t) {
setTimeout(function() {
log(this.t);
}.bind(this));
}
F.call({t:100});
Sexy
function F(t) {
setTimeout(()=> {
log(this.t);
});
}
F.call({t:100});
Math.max(3,5,2); // 5
What about an array? Not sexy.
Math.max.apply(null, [3,5,2]); // 5
Sexy
Math.max(...[3,5,2]); // 5
Not Sexy
function fn(first/*, rest */) {
var rest = [].slice.call(arguments, 1);
console.log(first); // "a"
console.log(rest); // [1, 2, 3]
}
fn('a', 1, 2, 3);
Sexy
function fn(first, ...rest) {
console.log(first); // "a"
console.log(rest); // [1, 2, 3]
}
fn('a', 1, 2, 3);
Not Sexy
var array = ['foo','bar','qux'];
var a = array[1];
var b = array[2];
console.log(a); // "bar"
console.log(b); // "qux"
Sexy
let [,a,b] = ['foo','bar','qux'];
console.log(a); // "bar"
console.log(b); // "qux"
let {parse, stringify} = JSON;
parse('{"a":"b"}') // {a: "b"}
stringify({a:'b'}) // "{\"a\":\"b\"}"
Sexy
function* count(start) {
let i = start || 0;
while(true) {
yield i++;
}
}
function* take(iterable, numToTake) {
var i = 0;
for (var taken of iterable) {
if (i++ === numToTake) {
return;
}
yield taken;
}
}
for (var i of take(count(10), 5)) {
console.log(i); // 10, 11, 12, 13, 14
}
Not Sexy
var x = 2, y = 3;
var equation = x + ' + ' + y + ' = ' + (x + y);
console.log(equation); // "2 + 3 = 5"
Sexy
let x = 2, y = 3;
let equation = `${x} + ${y} = ${x + y}`
console.log(equation); // "2 + 3 = 5"
let dob = '09/21/1991', seperator = '/';
let parts = dob.match(new RegExp(`[^${seperator}]\+`, 'gi'));
console.log(parts); // ["09", "21", "1991"]
var nums = [1,2,3];
// Not Sexy
console.log(nums[nums.length - 1]); // 3
// Proxy sexiness juice
function smartArray(arr) {
return Proxy(arr,
{get: function(p,x) {
if (Number(x) < 0) {
return p[p.length + Number(x)];
}
return p[x];
}}
);
}
let nums = smartArray([1,2,3]);
console.log(nums[0]); // 1
// Sexy
console.log(nums[-1]); // 3
Not Sexy
var salesContact;
if (company && company.employees && company.employees.sales && company.employees.sales.contact) {
salesContact = company.employees.sales.contact;
}
Sexy
var Obj = Function();
var nullProxy = Proxy(
{toString: ()=> 'nullProxy'},
{get: (t,p) => t[p] || new Obj() }
);
Obj.prototype = nullProxy;
var company = Object.create(nullProxy /*, data */);
// Sexy
var salesContact = company.employees.sales.contact;
console.log(company); // 'nullproxy'
Popular features
[ x for (x of a) if (x.color === ‘blue’) ]
let cubed = 2 ** 3
$ node --harmony
node --v8-options
https://github.com/google/traceur-compiler
https://github.com/addyosmani/es6-tools
http://kangax.github.io/compat-table/es6/
https://github.com/lukehoban/es6features
https://github.com/JustinDrake/node-es6-examples
https://github.com/miguelmota/es6-examples/
Find me in the internetz