Skip to content

Incorrect code: chapter "Arrays In-Depth", lesson "Adding Array Elements" #21

Description

@elHornair

The code shown in the explanation video is not in fact immutable.

Incorrect code:

console.log([
  ...drinks.splice(0, index),
  'Mojito',
  ...drinks.splice(index - 1),// side note: the -1 index correction is only needed as a result of the first splice mutating the original array
]);

Correct code:

console.log([
  ...[...drinks].splice(0, index),
  'Mojito',
  ...[...drinks].splice(index),
]);

Explanation:
As splice mutates the original array, before the spread operator spreads it, the original array gets mutated nevertheless. Solution: copy original array with spread operator, splice it, then spread the result.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions