DEV Community

Muhammad
Muhammad

Posted on • Updated on

What is the best example to learn the ES6 spread operator (...) ?

The following example taken from MDN is the best example I ever found to learn the spread operator as of 21 March 2023:-

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
brense profile image
Rense Bakker

You can use spread operator for a lot more:

function sum(...numbers){
  return numbers.reduce((total, next) => total += next, 0)
}

sum(1, 2, 3, 4) // add as many numbers as you want
Enter fullscreen mode Exit fullscreen mode

And you can use it to destruct or combine objects as well:

const user = {
  name: 'foobar'
}

// destructing:
const { name } = user
console.log(name)

const anotherObj = {
  email: 'foo@bar.baz'
}

// combining objects:
const combinedUser = { ...user, ...anotherObj }
console.log(combinedUser)

const someArray = [1, 2, 3]
const anotherArray = [4, 5]

// combine array:
const combinedArray = [ ...someArray, ...anotherArray ]
console.log(combinedArray)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mbshehzad profile image
Muhammad

Thank you a lot for it brother !