Refactor Array concat() Operations to Use the ES6 Spread Operator

Erik Aybar
InstructorErik Aybar
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

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.

egghead
egghead
~ 36 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today