Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
elHornair opened this issue Apr 25, 2021 · 1 comment

Comments

@elHornair
Copy link

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.

@elHornair
Copy link
Author

Update

Just realised that there is a much simpler way to do it:

console.log([...drinks.slice(0, index), 'Pizza', ...drinks.slice(index)]);

Opposed to splice, slice is immutable. I'm assuming this is what you wanted to do in the first place and the error is only a typo. Beware that the index correction (-1) is now not needed anymore though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant