Last active
November 14, 2017 21:47
-
-
Save aderaaij/0630de0a09fb08ca0a08dca192e63151 to your computer and use it in GitHub Desktop.
If your function returns a type that can be destructured like an array or an object, you can destructure it on the fly. In case of on object you destructure by key, so the order of destructuring doesn't matter and you can ommit whatever you want. In case of destructuring an array it's position based, so leaving an empty place would be done by le…
This file contains hidden or 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 convertCurrency(amount) { | |
const converted = { | |
USD: amount * 0.76, | |
GBP: amount * 0.53, | |
AUD: amount * 1.01, | |
MEX: amount * 13.30 | |
}; | |
return converted; | |
} | |
// Destructure the returned object directly, order doesn't matter! | |
const { USD, MEX, AUD, GBP } = convertCurrency(100); | |
console.log(USD, MEX, AUD, GBP); | |
function returnArray() { | |
return ['hulk', 'thor', 'iron man', 'spider man', 'black widow']; | |
} | |
// Destructure returned array directly, naming is based on position. The `team` | |
// variable holds an array with everyone after the hulk and thor. | |
const [ hulk, thor, ...team ] = returnArray(); | |
console.log(hulk, thor, team); | |
// Here we add an object as default argument for the function and we immediately | |
// destructure the object that is passed into the function. This way the order | |
// doesn't matter anymore and you can ommit any value you don't need. | |
// When we don't pass in anything into the function we do want something to destructure | |
// on, that's why we have an empty object in the arguments. | |
function tipCalc({ total = 100, tip = 0.15, tax = 0.13 } = {}) { | |
return total + (tip * total) + (tax * total); | |
} | |
const bill = tipCalc({ tip: 0.20, total: 200 }); | |
console.log(bill); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment