05 Destructuring - Gilian/001-ES6-By-Wes GitHub Wiki

Destructuring

In ES6 you can destructure many types like objects, arrays and even functions to get all values into a variable.

Objects

Problem: when you have an object and you want to get specific values you often repeat code:

const person = {
    first: 'Wes',
    last: 'Bos',
    country: 'Canada',
    city: 'Hamilton',
    twitter: '@wesbos'
};

// Now you can use {} for objects to get destructured
const { first, last, twitter } = person;

// You can rename the variables on the run
const { twitter: tweet, facebook: fb } = wes.links.social;

// If you need default values which are not given by the object
const settings = { width: 300, color: 'black' }  // height, fontSize
const { width = 100, height = 100, color = 'blue', fontSize = 25} = settings;

Arrays

Destructure arrays is the same as destructuring objects but you can get the rest of the array by using "…". When you want to get all elements in a string and put them into variables you could do this: (you need a good seperator of course)

// You use [] when destructuring arrays
const data = 'Basketball, Sports, 90210, 23, wes, bos, cool';
const [itemName, category, sku, inventory] = data.split(',');

// You can put the rest of the values into an extra variable by using "..."
const team = ['Wes', 'Harry', 'Sarah', 'Keegan', 'Riker'];
const [captain, assistant, ...players] = team;

// And you can now swap variables very easily
[data, data2] = [data2, data]

Functions

When destructuring functions you can set objects as arguments so the order doesen't matter and you can easily set defaults:

// if there is no parameters passed at all you need to set the destructuring object to „= {}“ so the object gets a default itself and uses all defaults
function tipCalc({ total = 100, tip = 0.15, tax = 0.13 } = {}) {
    return total + (tip * total) + (tax * total);
}

const bill = tipCalc({ tip: 0.20, total: 200 });