The reverse()
function in JavaScript is commonly used to reverse an array. However, there is a new function called the toReversed()
, which may be more suitable depending on the situation. Your code might have unexpected results if you use reverse()
without knowing its effects.
The main difference is that the reverse()
function changes the original array. For example, we are going to reverse the following array using the reverse function:
reverse():
const arr = [1,2,3];
arr.reverse();
console.log(arr); // [3,2,1]
As you can see, the original array has mutated because the reverse()
returns a reference to the original array. Now let's use the toReversed()
. This function returns a copy of the original array and doesn't change it:
toReversed():
const arr = [1,2,3];
arr.toReversed();
console.log(arr); // [1,2,3]
The next difference we must know is that empty slots remain empty in the reverse()
function, while in toReversed()
empty slots become undefined.
reverse():
const arr = [1,2,3];
delete arr[0];
arr.reverse();
console.log(arr); // [3, 2, empty]
toReversed():
const arr = [1,2,3];
delete arr[0];
const arr2 = arr.toReversed();
console.log(arr2) // [3, 2, undefined]
Top comments (0)