DEV Community

Cover image for JavaScript Spread Operator: Advanced Techniques and Best Practices

JavaScript Spread Operator: Advanced Techniques and Best Practices

Harish Kumar on June 05, 2024

The JavaScript spread operator (...) is a powerful feature introduced in ES6 that provides a concise and expressive way to work with arrays, object...
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You can use the spread operator with anything that is iterable, not just arrays. For example... a string (this is a much better way of splitting a string into characters than using .split('') - as it will deal a lot better with Unicode):

console.log([...'Hello 🤔'])  // [ "H", "e", "l", "l", "o", " ", "🤔" ]
console.log('Hello 🤔'.split('')  // [ "H", "e", "l", "l", "o", " ", "\ud83e", "\udd14" ]
Enter fullscreen mode Exit fullscreen mode

Generator functions are iterable by default, so this also works:

function *test() {
  yield 'first'
  yield 'second'
  yield 'third'
}
console.log([...test()]) // [ "first", "second", "third" ]
Enter fullscreen mode Exit fullscreen mode

It is even possible (with some effort) - to make this code work:

console.log(3[[...7]])  // [3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

For a more detailed explanation, see this article:

Collapse
 
oggo profile image
oggo

Cool! Could you explain the last one?

Collapse
 
oggo profile image
oggo

... i found it in your post! Really cool! Thanx!

Collapse
 
best_codes profile image
Best Codes

Wow, this is really cool!

Collapse
 
kentbrew profile image
Kent Brewster

Spread operator is also handy for converting a collection of HTML elements into an array:

// get me all the DIVs on this page that have IDs:
myDivsWithIds = [...document.getElementsByTagName('DIV')].filter((me)=> me.id);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
xi_sharky_ix profile image
shArky

Cool, you didn't forget to mention that the spread operator creates a shadow copy of an object.

Also look at the structuredClone function from the global scope.

And last but not least. As @jonrandy notes, I also add something (try it):

[...{[Symbol.iterator]: function*() { yield 1; yield 2; yield 3; }}]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
innocentdevii profile image
Dipesh Raichana • Edited

I was not able to understand one thing that why do you need spread operator for the following cases:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = [...numbers].map(num => num * 2);
console.log(doubledNumbers);

&
const numbers = [1, 2, 3];
function sum(a, b, c) {
return a + b + c;
}
console.log(sum(...numbers));

where you could simply pass numbers instead of ...numbers

In both cases, the output will remain same.

Collapse
 
kayla_wood_53f7bfff3e5d13 profile image
Kayla Wood

I had some crypto on a Bitcoin wallet that I thought was lost for good. I’d sent my laptop to a variety of top data recovery firms, but with no luck. After seeing a positive comment about ROOTKIT HACKER on “Morning Brew”, I decided to try to recover my wallet one last time. ROOTKIT HACKER was very responsive to emails, and recovered my wallet in just a few days. I was nervous about providing my wallet seed and passphrase, but there really was no need to be uneasy. ROOTKIT HACKER acted honorably and in accordance with our agreement. I would highly recommend using ROOTKIT HACKER services, even if you have nearly given up hope of recovering your wallet. Contact them on Email: rootkithacker1@outlook.com
WhatsApp: +1 (929) 447‑0339
They are Tested and trusted.

Collapse
 
efpage profile image
Eckehard

JSON.parse(JSON.stringify) does not work for DOM references. Use structuredClone instead

Collapse
 
kyle_albert_5eb090b7dba0d profile image
Kyle albert • Edited

One that I always end up using is.

const a = { ...(true &&  { b: 2 }) }
const c = { ...(false && { d: 2 }) }

a //{ b: 2 }
c // { }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️

You have the spread operator in the wrong place. Your code will cause a syntax error. I think you mean:

const a = { ...(true && { b: 2 }) }
const c = { ...(false && { d: 2 }) }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
best_codes profile image
Best Codes

Nice post! 😊

Collapse
 
harihargithub profile image
harihargithub

This useful post helped me refresh what I had studied..