DEV Community

Daniel Nakamashi
Daniel Nakamashi

Posted on

Easier way to get a copy of array as argument

Have you ever created a function where you receive an array as argument and created a copy of it because you didn’t want to touch the original one?

If so, you probably did something like this:

function (items) {
  const newItems = [...items]
  // mutate newItems here
  return newItems
}
Enter fullscreen mode Exit fullscreen mode

The sad thing about this code is that after you had a hard time thinking about a cool name for the argument, you have to ditch it and work with a not so cool variable name 🙁.

You could create another name for the argument and then use your cool name in the variable you will work with 🤔.

function (itemsArg) {
  const items = [...itemsArg]
  // mutate items here
  return items
}
Enter fullscreen mode Exit fullscreen mode

But there is a better way.

function ([...items]) {
  // mutate items here
  return items
}
Enter fullscreen mode Exit fullscreen mode

This way you have created a copy of the array in the function’s argument list 😃.

Oldest comments (0)