In this video, we take a quick look at refactoring usages of Array.prototype.concat to make use of the ES6 array spread operator. For example, we can refactor towards simple append and prepend statements such as [...array, value]
or [value, ...array]
or combine multiple spread operations to achieve insert via [...leftSide, value, ...rightSide]
.
Bonus tip: [...someArray]
can be used to quickly make a shallow copy of an array to avoid mutation for many common array operations.
Instructor: [00:00] We're going to take a look at cleaning all this up and replacing these concats with the ES6 array spread operator, which can make these a little bit easier to read, depending on the circumstance. The way that's going to look is we're going to spread this out and put the value at the end for append.
[00:18] The concat's going to be very similar, except we're going to put the value at the beginning. For these operations here, what we can do is remove this new array with a concat. We're going to wrap this. We're going to return the array directly, take this array that slice is returning and spread it out. Same thing down here.
[00:48] We're back to, as we expect. We can do the same for remove, replacing concat with the spread operator. We have these two arrays that we're spreading out.