DEV Community

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

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