keep in mind...
- unpacking of values into distinct variables
- used for so many things, can be confusing!
- can include fallback defaults - awesome!
Destructuring is a syntax that allows you to work with values from arrays, objects, maps, and sets in a way that allows for easier and more flexible representation of the data. A great explanation of why this is awesome can be found here from JS guru Wes Bos.
Array destructuring offers a quick way to work with values from an array. Notice how I can assign a, b, and c to the values contained in the names array through destructuring.
const names = ['nicolas', 'julia', 'catherine']; let a, b, c; [a, b, c] = names; console.log(b);
Object destructuring offers a quick way to unpack properties into distinct variables.
const kids = { julia: 'girl' , nicolas: 'boy' }; let { julia, nicolas } = kids; console.log(julia); console.log(nicolas);
A variable can be assigned a default, in the case that the value unpacked from your data element is undefined. I've used this, for example, in a script that passes variables to a modal popup window. Setting defaults minimizes the amount of information needed in the modal creation function, only sending what is necessary.
// we start with the obj, passed through the modal creation function const obj = { text: 'cool new modal' }; // we can add some defaults before we access the obj, in case this instance of our modal doesn't contain these values const { text = 'modal text', type = 'modal' } = obj; console.log('text is '+text); // contains the value passed by our obj via the modal creator console.log('type is '+type); // falls back to the default type we just created
Destructuring can also be used to swap values, which is a pretty cool feature! Swapping values like this used to involve temporary values, making this much cleaner.
let snowshoer = 'Nicolas'; let snowboarder = 'Julia'; [snowshoer, snowboarder] = [snowboarder, snowshoer]; console.log('our snowboarder is now '+snowboarder); console.log('our snowshoer is now '+snowshoer);
If you leave elements empty (indicated by just leaving a comma with nothing else), destructuring will skip over the null value.
const names = ['nicolas', 'julia', 'catherine']; let a, b, c; [, b, c] = names; console.log(b);
Using destructuring with the rest operator is another piece of es6 wizardry. Look how you can grab a couple of items in the array for named variables, then throw the rest of the items into an array.
const kids = ['nicolas', 'julia', 'catherine', 'sophia', 'william'] let captain, cocaptain, players; const team = [ captain, cocaptain, ...players ] = kids; console.log('cocaptain is '+cocaptain); console.log('players are '+players);