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...
For further actions, you may consider blocking this person and/or reporting abuse
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,
So, if you get asked to reverse a string with JS in an interview, following might be treated as too naive:
Following is slightly better:
JavaScript's unofficial motto.
😂
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
Right you are! Thanks for picking up on that, I’ve updated the post 😊.
Thanks for reading!
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)
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!
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.
Amazing article, thank you!
Personally, with the first example, I would also recommend using parens to help understand the order of operations.
Otherwise looking at
...firstName && { firstName },
was throwing me off thinkingfirstName
was first being spread!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.
Good catch! Thanks for pointing that out - I’ve updated the post 🍻
Thanks for updating, and thanks for just writing this! I didn't know about the first pattern 🙏
String spreading is on fire! Thank you for sharing these interestings facts about this operator :)
Thanks for reading! 😊
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.