A polyfill/shim for the new Array.toReversed function

Written by Richard Heyes, on 22nd July 2023

Here's a small shim that makes available to you the new Array.toReversed function. This function is more straight-forward to use in my opinion than the existing Array.reverse function because instead of reversing the array "in-place" it returns a new array to you and leaves the original array untouched.

    <script>
        //
        // Add the Array.toReversed function to the
        // Array object if it doesn't exist already.
        //
        // @return array A new array with the elements
        //               in reverse order
        //
        // Usage:
        //        myArray  = [0,1,2,3];
        //        myArray2 = myArray.toReversed(); // [3,2,1,0]
        //
        if (![].toReversed) {
            Array.prototype.toReversed = function ()
            {
                for (var i=(this.length - 1),arr=[]; i>=0; --i) {
                    arr.push(this[i]);
                }
                
                return arr;
            };
        }
    </script>
Simply add that to your page (for example in a "common functions" file) and if the function doesn't exist in the browser natively it will add it. You can then use the function as required without having to check if it exists or not.