Add and Remove Array Items with JavaScript concat() and slice() to Avoid Mutation

Erik Aybar
InstructorErik Aybar

Share this video with your friends

Send Tweet

In this video we'll learn how to perform common add and remove array operations such as append, prepend, insert, and remove. We'll look at the dangers of mutation that can be caused by using mutative array methods such as Array.prototype.push and learn how to instead leverage non-mutative array methods such as Array.prototype.concat and Array.prototype.slice when working with arrays.

Frank Schiller
Frank Schiller
~ 3 years ago

Hey Erik, great demonstration on how to use concat and slice to not mutate arrays! I have a question about the end of the video with removeAt. How come the final console.log doesn’t display [A, C]? My reasoning is that since the index is set to 1 in the console log, wouldn’t that cause an additional item to be removed after the slice on the left side (array.slice(0, index))?

Erik Aybar
Erik Aybarinstructor
~ 3 years ago

Thank you Frank! In this example, the "index" being passed in is 1 which corresponds to 'B'.

The first array.slice(0, index) results in everything up to but not including "B" for the "left" side. The second array.slice(index + 1) results in everything after 'B' for the "right" side.

I hope that helps clarify.

Example:

const letters = ['A', 'B', 'C', 'D'];
// Index of 'B'
const index = 1;

[].concat(
  // Left: Up to, but not including 'B'
  letters.slice(0, index),
  // Right: Start one index after 'B' and take everything until the end
  letters.slice(index + 1)
);
// => ['A', 'C', 'D']

The MDN docs cover more details with examples on Array.prototype.slice.

Frank Schiller
Frank Schiller
~ 3 years ago

That helped clear things up for me, thank you for replying so quickly and providing docs for further research! I believe I had myself confused with the syntax of splice() specifically when there is no "end" parameter provided. Thanks again!