❌ If you see code like this:
const identity = 'Julia Coding Unicorn';
const result = identity.split(' ');
const name = result[0];
const occupation = result[1];
const creature = result[2];
✅ You can refactor it to:
const identity = 'Julia Coding Unicorn';
const [ name, occupation, creature ] = identity.split(' ');
🦄 With destructuring, you can find Head and Tail:
const [head, ...tail] = [1, 2, 3, 4, 5]; // head = 1; tail = [2, 3, 4, 5]
🦄 Await for promises:
const [user, account] = await Promise.all(
[
fetch('/user'),
fetch('/account')
]
)
🦄 Match regular expressions:
const regex = /(\d{4})-(\d{2})-(\d{2})/
const [ , year, month, day] = re.exec('𝟸0𝟸0-𝟷0-𝟷𝟻'); // [0] is the full match, skip it
🦄 And even swap variables:
[x, y] = [y, x];
✋ But destructuring is not always a good fit.
❌ Hipsters use it to capitalize strings:
function capitalize([ first, ...rest ]) {
return [ first.toUpperCase(), ...rest ].join('');
}
✅ But classic solutions never go out of style:
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
Destructuring can simplify your code or make it more complicated. New ES6 features are not meant to replace good classics. New != better. Sometimes typing an array index [0]
is all you need.
Discussion (7)
I thought the hipster way to capitalize was something like this:
:)
Good Article! Saved for future reference
You should do your self a favor and go to the original sources.
Nicely explained! 💯
Love the concise style and easy to follow examples
it is so short because this is just copied and paste Instagram content...
I'm besides that they are just a rip off of a way better MDN article:
hacks.mozilla.org/2015/05/es6-in-d...
Nice toth like cover image. Totally relevant for that article but yeah if you target the young male demographic and single unhappy men then you nailed that cover image!
If you copy and paste example at least leave a reference to the original...
If you forgot here you go: hacks.mozilla.org/2015/05/es6-in-d...
or just copy and pasting stackoverflow code:
stackoverflow.com/questions/102606... These hipsters on stackoverflow...
oh, wait your from IG where adding a 5 to an array means it is your work sorry for that.