Skip to content

Instantly share code, notes, and snippets.

@jaapz
Last active November 12, 2015 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaapz/a2a87f02825215106028 to your computer and use it in GitHub Desktop.
Save jaapz/a2a87f02825215106028 to your computer and use it in GitHub Desktop.
object destructuring in es6
// simple destructuring without default
let obj = {bananaphone: 'hello?'};
let {bananaphone} = obj;
console.log(bananaphone); // hello?
// destructuring with default
let {missingkey = 'hey?'} = obj;
console.log(missingkey); // hey?
// destructuring in function
function destructure({missingkey = 'hey?'} = {}) {
console.log(missingkey);
}
destructure(obj); // hey?
destructure({missingkey: 'hello'}); // hello
destructure(); // hey?
// previous function is the same as this
function destructure(options = {}) {
let {missingkey = 'hey?'} = options;
}
// and this (if no options object is provided)
function destructure(options) {
let {missingkey = 'hey?'} = options || {};
}
// destructure into a different named variable
function destructure({othername: missingkey = 'hey?'}) {
console.log(missingkey, othername);
}
destructure({missingkey: 'exists'}); // undefined, "othername"
destructure(); // undefined, "hey?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment