aderaaij
11/13/2017 - 8:34 PM

ES6 - Destructuring a function

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 leaving an empty position in the destructuring as well.

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);