The reverse() method reverses the order of the elements in an array.
Syntax
a.reverse()
Return value - The reversed array.
Examples
Example 1: Reverse a given string array
var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']
var reversed = array1.reverse();
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']
/* Careful: reverse is destructive. It also changes
the original array */
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']
Example 2: Reversing the integer elements in an array
const a = [1, 2, 3];
console.log(a); // [1, 2, 3]
a.reverse();
console.log(a); // [3, 2, 1]
Comments
Post a Comment
Leave Comment