This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

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

    Erik AybarErik Aybar

    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.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss