Last active
July 27, 2017 21:57
-
-
Save neo/dec6dfe28f1511fb71fa093b3571c25e to your computer and use it in GitHub Desktop.
Key ES2015 Features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function takesNamedParameters({ id, name } = {}) { | |
console.log(id, name); | |
} | |
// Rest parameters | |
function variadic(a, b, ...theArgs) { | |
return Array.isArray(theArgs); // true | |
} | |
let ary = [1, 2, 3, 4]; | |
// Default function parameters | |
function takesIndividualArguments(a = 0, b = 0, c = 0, d = 0) { | |
console.log(a, b, c, d); | |
} | |
// Spread operator | |
takesIndividualArguments(...ary); | |
// Object initializer | |
function returnsAnObject(id, name) { | |
// instead of { id: id, name: name } | |
return { id, name }; // from variables to object properties | |
} | |
// Object destructuring | |
let { name } = { id: 0, name: 'Neo' }; // from (only selected) object properties to variables | |
// Object.assign | |
function complex(options = {}) { | |
let defaults = { | |
// ... | |
}; | |
let settings = Object.assign({}, defaults, options); // merge and overwrite properties from right to left | |
} | |
// Array destructuring | |
let [a, , b, ...rest] = [1, 2, 3, 4, 5]; | |
console.log(a, b, rest); // 1 3 [4, 5] | |
for (let number of ary) { | |
console.log(number); | |
} | |
// MDN: Map, Set, WeakMap and WeakSet | |
// Make plain objects iterable | |
Object.prototype[Symbol.iterator] = function () { | |
let i = 0; | |
let done = false; | |
let keys = Object.keys(this); | |
let next = () => { | |
if (i >= keys.length) done = true; | |
return { done, value: this[keys[i++]] }; | |
}; | |
return { next }; | |
}; | |
let obj = returnsAnObject(0, 'Neo'); | |
// Ex.1 with a iterable object | |
for (let i of obj) { | |
console.log(i); | |
} | |
// Ex.2 with a iterable object | |
[...obj]; // [0, 'Neo'] | |
// Ex.3 with a iterable object | |
[_id, _name] = obj; | |
console.log(_id, _name); | |
// Make plain objects iterable | |
Object.prototype[Symbol.iterator] = function* () { | |
let keys = Object.keys(this); | |
for (let key of keys) { | |
yield this[key]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment