Last active
November 12, 2015 09:50
-
-
Save jaapz/a2a87f02825215106028 to your computer and use it in GitHub Desktop.
object destructuring in es6
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
// 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