JavaScript AcademyProfessional Engineering

Learning object 16 of 100

Array operation explorer

Apply one array operation to an array and see what it returns, what the array looks like afterwards, and whether the original was changed.

Loading…

What it shows

Some array methods change (mutate) the array they are called on: push, pop, shift, unshift, splice, sort and reverse. Others return something new and leave the original alone: slice, concat, map, filter and the newer toReversed and toSorted. Knowing which is which prevents a whole family of bugs where shared data changes unexpectedly.

Guided experiment

  1. Apply .push("kiwi"). Why is the returned value a number?
  2. Compare .slice(1, 3) with .splice(1, 1). Which one changed the array?
  3. Apply .reverse() and then .toReversed() to the same starting array.

Predict

What does ["a", "b"].push("c") return?

Related

Lessons: Lesson 27: Adding and removing elements, Lesson 30: Building collection-based applications

Projects: Project 9: Shopping Cart Price Calculator

Source: web/assets/js/objects/object-016.js in the companion repository.