revision:
The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
To reverse the elements in an array without mutating the original array, use toReversed().
reverse()
Parameters: none
const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // Expected output: "array1:" Array ["one", "two", "three"] const reversed = array1.reverse(); console.log('reversed:', reversed); // Expected output: "reversed:" Array ["three", "two", "one"] // Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // Expected output: "array1:" Array ["three", "two", "one"]
see console.log
<div> <p id="'rever-1"></p> <p id="'rever-2"></p> <p id="'rever-3"></p> </div> <script> const items = [1, 2, 3]; console.log(items); // [1, 2, 3] items.reverse(); console.log(items); // [3, 2, 1] </script>
<div> <p id="rever-4"></p> <p id="rever-5"></p> <p id="rever-6"></p> </div> <script> const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // Expected output: "array1:" Array ["one", "two", "three"] document.getElementById("rever-4").innerHTML = "array 1 : " + array1; const reversed = array1.reverse(); console.log('reversed:', reversed); // Expected output: "reversed:" Array ["three", "two", "one"] // Careful: reverse is destructive -- it changes the original array. document.getElementById("rever-5").innerHTML = "reversed : " + reversed; console.log('array1:', array1); // Expected output: "array1:" Array ["three", "two", "one"] document.getElementById("rever-6").innerHTML = "array 1 : " + array1; </script>
<div> <p id="rever-7"></p> <p id="rever-8"></p> <p id="rever-9"></p> <p id="rever-10"></p> </div> <script> const numbers = [3, 2, 4, 1, 5]; document.getElementById("rever-7").innerHTML = "numbers : " + numbers; document.getElementById("rever-8").innerHTML = "numbers[0] : " + numbers[0]; const reversed_2 = numbers.reverse(); // numbers and reversed are both in reversed order [5, 1, 4, 2, 3] reversed[0] = 5; console.log(numbers[0]); // 5 document.getElementById("rever-9").innerHTML = "reversed numbers : " + reversed_2; document.getElementById("rever-10").innerHTML = "numbers[0] : " + numbers[0]; </script>
<div> <p id="rever-11"></p> <p id="rever-12"></p> <p id="rever-13"></p> <p id="rever-14"></p> </div> <script> const fruits = [" Banana", " Orange", " Apple", " Mango"]; document.getElementById("rever-11").innerHTML= "original array : " + fruits; document.getElementById("rever-12").innerHTML = "reversed array : " + fruits.reverse(); </script>