← Back to the exercise

Destructuring, Spread, and Rest

The answer to the exercise in Destructuring, Spread, and Rest.

push changed the array in place, and the function handed the same show back, so original and updated were one object. Spreading the show into a new object, and the old genres into a new array, gives the caller something of its own and leaves original.genres alone.

function addGenre(show, genre) {
  return { ...show, genres: [...show.genres, genre] }; // was: show.genres.push(genre)
}

const original = { title: "Severance", genres: ["Drama"] };
const updated = addGenre(original, "Thriller");

console.log("original: " + original.genres);
console.log("updated:  " + updated.genres);