Colin G
Colin G

Reputation: 165

Array reverse behavior in different browsers

Run the following in the console of Firefox: Array.reverse([0,1]);

Result: [1,0]

Run it again in Chrome:

Array.reverse is not a function

The whole point of me trying this was that I wanted to reverse an array into a copy of itself so that it would not change the original. My question: which browser has the correct behavior?

Seems to me that, since reverse() is supposed to be on Array.prototype, Firefox is wrong. However, Firefox's behavior is more useful. So is this a Firefox bug?

Upvotes: 2

Views: 701

Answers (2)

ZER0
ZER0

Reputation: 25322

Firefox introduced years ago Array's generics method, in JS 1.6, but as mentioned in the linked page:

"These are not part of ECMAScript standards and they are not supported by non-Gecko browsers."

And:

Array generics are non-standard, deprecated and will get removed in the near future.

Therefore you should avoid them.

More important, it doesn't solve your issue. You said that you want to avoid to change the original, but Array.reverse(arr) is equivalent to arr.reverse(), so you mutate anyway the original array.

If you want to avoid that, you should create a copy of it. If you just need a shallow copy, you can do:

let arr = [0, 1];
let reversed = [...arr].reverse();

console.log(arr, reversed); // [0, 1], [1, 0]

Upvotes: 4

Jack Bashford
Jack Bashford

Reputation: 44125

Array.prototype.reverse is not a static method in Chrome (and some other browsers, e.g. Safari). You should do it like this:

console.log([0, 1].reverse());

Upvotes: 0

Related Questions