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
}
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
}
But there is a better way.
function ([...items]) {
// mutate items here
return items
}
This way you have created a copy of the array in the function’s argument list 😃.
Top comments (0)