DEV Community

Cover image for 3 Weird Things You (Probably) Didn't Know You Can Do With The JavaScript Spread Operator 🥳

3 Weird Things You (Probably) Didn't Know You Can Do With The JavaScript Spread Operator 🥳

Harrison Reid on January 30, 2020

If you find this post useful, you can sign up to my mailing list, check out the other posts on my blog, or follow me on twitter. I've also got a co...
Collapse
 
sidvishnoi profile image
Sid Vishnoi • Edited

As spread operator acts as if we used String[Symbol.iterator], it is better to use spread operator instead of regular String.prototype.split to split given string into characters when the string may involve Unicode characters. It's not foolproof, but better.
For example,

"😂👻".split("") // (4) ["�", "�", "�", "�"] <- wut?
[..."😂👻"] //  2) ["😂", "👻"]
Enter fullscreen mode Exit fullscreen mode

So, if you get asked to reverse a string with JS in an interview, following might be treated as too naive:

function reverse(str) {
  return str.split('').reverse().join('');
}
reverse('foo') // "oof"
reverse('𝄞') // "��"
Enter fullscreen mode Exit fullscreen mode

Following is slightly better:

function reverse(str) {
  return [...str].reverse().join('');
}
reverse('foo') // "oof"
reverse('𝄞') // "𝄞"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ludamillion profile image
Luke Inglis

You might think this should result in an error, but it actually doesn't.

JavaScript's unofficial motto.

Collapse
 
harrison_codes profile image
Harrison Reid

😂

Collapse
 
vijayakumarrg profile image
Vijaya Kumar Reddy Gajjala

Hi Harrison.

It is very nice article which highlights some of the unknown uses of spread operator. Thanks for this.

I think there is a typo in the code at 'const fruitsObject = { ...fruitsObject }'. Should it be const fruitsObject = { ...fruitsArray } ? Please check.

Thanks again
Vijay

Collapse
 
harrison_codes profile image
Harrison Reid

Right you are! Thanks for picking up on that, I’ve updated the post 😊.

Thanks for reading!

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Thanks for the post Harrison, but there is a part of me that would prefer an object which is missing a property, to instead contain something explicit, like null or better yet a failover. With that said, my way or this way we would still be checking downstream that something is not here OR is null or failover. But mine would not need gork time, maybe 🤷‍♂️ (I'd do something else wierd instead)

Collapse
 
harrison_codes profile image
Harrison Reid

Absolutely - I tend to agree that while there are some cases where this pattern is useful, it’s often better to keep a consistent object schema, and explicitly set the missing properties to null.

As with all things (especially somewhat obscure patterns), use with caution!

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

It's a hobby to know strange JavaScript, I can relate.

I am also interested in the obscure, checkout my labeled loops post, it's right up there in the do not do this camp.

Collapse
 
js_bits_bill profile image
JS Bits Bill

Amazing article, thank you!

Personally, with the first example, I would also recommend using parens to help understand the order of operations.

const userInfo = {
  ...(firstName && { firstName }),
  ...(lastName && { lastName }),
  ...(address && { address }),
  ...(phoneNumber && { phoneNumber })
}

Otherwise looking at ...firstName && { firstName }, was throwing me off thinking firstName was first being spread!

Collapse
 
thibpat profile image
Thibaut Patel

Thanks for sharing the article Harrison!
One small comment: in your last example the object should start with the key zero for the character 'a' instead of one.

Collapse
 
harrison_codes profile image
Harrison Reid

Good catch! Thanks for pointing that out - I’ve updated the post 🍻

Collapse
 
thibpat profile image
Thibaut Patel

Thanks for updating, and thanks for just writing this! I didn't know about the first pattern 🙏

Collapse
 
anwar_nairi profile image
Anwar

String spreading is on fire! Thank you for sharing these interestings facts about this operator :)

Collapse
 
harrison_codes profile image
Harrison Reid

Thanks for reading! 😊

Collapse
 
kylefilegriffin profile image
Kyle Griffin

spreading a string into an array sounds like it could be a good approach to set text sarcastically and then duct tape the array back into a string again.