ultimatecourses / javascript-basics

🏆 Starter project for JavaScript Basics
https://ultimatecourses.com/learn/javascript-basics
83 stars 68 forks source link

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

Open elHornair opened 3 years ago

elHornair commented 3 years ago

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 commented 3 years ago

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.