Reverse an array without mutating it in JavaScript
Beginner · 3 min read
Reversing a list is easy in JavaScript: call reverse(). Newest messages first, a countdown instead of a count-up, a route home that is the route out backwards. The catch is that reverse() doesn't give you a reversed copy. It flips the array you already have, and that can quietly break any other code using it.
In this tutorial you will reverse an array, see why const backwards = xs.reverse() is usually a bug, and then reverse one safely so the original keeps its order. You should know arrays and ===. Copies and mutating are explained below.
Mutating, and "the same array"
A method that changes the array you call it on is said to mutate it. reverse mutates. It also returns the very same array, not a new one.
=== on two arrays asks "are these the same array in memory?". Two names can point at one array, and then a change through either name shows up through both:
const a = [1, 2];
const b = a;
b.push(3);
console.log(a); // [ 1, 2, 3 ]
console.log(a === b); // true
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
19 reverse changes the array it is called on
easyReverse an array, then reverse one without disturbing the original. Then explain why const backwards = xs.reverse() is usually a bug.
Stuck? Three hints, smallest first
- 1.
reversemutates and returns the same array, not a copy. - 2. So the "copy" and the original are one object, and both look reversed.
- 3.
[...xs].reverse(),xs.slice().reverse()orxs.toReversed()all leave the input alone.
Step 1: reverse reverses
console.log([1, 2, 3].reverse()); // [ 3, 2, 1 ]
So far, so good.
Step 2: the line that looks right
Now keep the original and store the reversed version in a new variable:
const original = [1, 2, 3];
const backwards = original.reverse();
console.log(backwards); // [ 3, 2, 1 ]
console.log(original); // [ 3, 2, 1 ]
console.log(backwards === original); // true
backwards is reversed, as expected. But original is reversed too. There is only one array: reverse flipped it in place and handed back that same array, so both names point at it.
This bug hides well, because the line reads correctly. Later code that expects original in its first order gets the flipped one. If the line runs again, for example each time a page redraws, the list flips back and forth.
Step 3: copy first, then reverse
The fix is to make a copy and reverse the copy. The spread syntax [...safe] makes a new array with the same items.
const safe = [1, 2, 3];
const safeCopy = [...safe].reverse();
console.log(safeCopy); // [ 3, 2, 1 ]
console.log(safe); // [ 1, 2, 3 ]
reverse still mutates, but it mutates the copy, which nobody else is using.
Step 4: slice() works too
slice() with no arguments also copies a whole array, and you will see it in older code:
const a = [1, 2, 3];
const b = a.slice().reverse();
console.log(b); // [ 3, 2, 1 ]
console.log(a); // [ 1, 2, 3 ]
Step 5: toReversed, the built-in copy
Newer JavaScript engines have toReversed(), which returns a reversed copy and never touches the original.
const nums = [1, 2, 3];
console.log(nums.toReversed()); // [ 3, 2, 1 ]
console.log(nums); // [ 1, 2, 3 ]
It is recent, so the answer panel checks that it exists before using it. On an older engine, [...xs].reverse() does the same job.
Step 6: reversing text
Strings don't have a reverse method. Spread the string into an array of characters, reverse that, and join it back.
console.log([...'Lagos'].reverse().join('')); // 'sogaL'
Here mutating is harmless, because the array made by [...'Lagos'] is brand new and only lives for this one line.
A rule of thumb
Methods named with a plain command verb, like reverse, sort, fill and splice, change the array. The copying versions have a to in front: toReversed, toSorted, toSpliced. When in doubt, copy first.
The full solution
The panel reverses one array directly and shows the original flipped too, then reverses a copy and shows the original untouched. Press Run to compare.
const original = [1, 2, 3];
const backwards = original.reverse(); // same array, now reversed
const safe = [1, 2, 3];
const safeCopy = [...safe].reverse();
const hasToReversed = typeof Array.prototype.toReversed === 'function';
const builtIn = hasToReversed ? [1, 2, 3].toReversed() : [3, 2, 1];
console.log('backwards :', backwards);
console.log('original :', original, '<- reversed as well, because it is the same array');
console.log('same object?', backwards === original);
console.log('--- with a copy ---');
console.log('safeCopy :', safeCopy);
console.log('safe :', safe, '<- untouched');
console.log('toReversed available?', hasToReversed, '->', builtIn);
console.log('reversing text needs an array first:', [...'Lagos'].reverse().join(''));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('reverse reverses', [1, 2, 3].reverse(), [3, 2, 1]);
test('and returns the very same array', (() => { const a = [1, 2]; return a.reverse() === a; })(), true);
test('so the original is reversed too', original, [3, 2, 1]);
test('a spread copy protects it', safe, [1, 2, 3]);
test('while still giving the reversed order', safeCopy, [3, 2, 1]);
test('slice() works the same way', (() => { const a = [1, 2, 3]; a.slice().reverse(); return a; })(), [1, 2, 3]);
test('toReversed is the built-in copy', builtIn, [3, 2, 1]);
test('reversing twice restores the order', [1, 2, 3].reverse().reverse(), [1, 2, 3]);
test('a string has to become an array first', [...'Lagos'].reverse().join(''), 'sogaL');
The bug is subtle because the line reads correctly. const backwards = xs.reverse() does produce a reversed array — it just also reverses xs, so any later code that expected the original order gets the new one. In a render function that runs twice, the array flips back and forth.
sort has the same shape and exercise 25 covers it. The rule of thumb: if a method's name is a verb in the imperative (sort, reverse, fill, splice), assume it mutates; the copying versions are named with a to prefix or a past participle (toSorted, toReversed, sorted in other languages).
Common mistakes
- Writing
const backwards = xs.reverse(). It reversesxsas well. Use[...xs].reverse()orxs.toReversed(). - Reversing inside a function that was handed an array. The caller's array gets flipped. Copy first inside the function.
- Calling
'text'.reverse(). Strings have noreverse. Go through an array:[...text].reverse().join('').
Try it yourself
- Write
reversed(xs)that returns a reversed copy, and show the input is unchanged. - Reverse
['a', 'b', 'c']twice withreverse(). What do you get, and is it still the same array? - Print a countdown from 5 to 1 by reversing
[1, 2, 3, 4, 5]without changing it.