Take a look at the code below.
At first glance, this looks good. We’re not using let
, and we’re not mutating on the original array using something like push
. But take a look at the console.log
statement. It turns out that the sort
method does not create a copy of the original array. Instead, it both mutates on the original array and returns its own array from the method call.
And there are a handful of old Array-methods that do this. Be careful with push
, shift
, unshift
, pop
, reverse
, splice
, sort
, and fill
. Fortunately, most often we can simply avoid calling these methods at all, to stay out of trouble.
However, there are cases, like using sort
, where we have to use a method that mutates the original array, in lack of better options. Array destructuring to the rescue! Whenever these occasions arise, make sure to manually copy the array first, before performing an operation on it. It’s as simple as this.
That [...grades]
makes the entire difference.