DEV Community

Daniel Nakamashi
Daniel Nakamashi

Posted on

1 2

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 😃.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay