reverse method
The reverse method reverses
the order of elements in an array. The
method modifies the original array
(it will become reversed) and returns
the reversed array as well (you can
use both).
Syntax
javascriptarray.reverse();
Example
Let's reverse an array:
javascriptlet arr = ['a', 'b', 'c'];
arr.reverse();
console.log(arr);
The code execution result:
javascript['c', 'b', 'a']
Example
And now let's write the reversed array into a new variable:
javascriptlet arr = ['a', 'b', 'c'];
let res = arr.reverse();
console.log(res);
The code execution result:
javascript['c', 'b', 'a']
Example . Usage
Let's reverse the characters of a
string. To do this, we split the
string into an array using
split
using the separator '' (this
separator will put each character
of the string into individual array
element), reverse this array with
reverse and then merge the
reversed array back with
join:
javascriptlet str = '123456789';
let arr1 = str.split('');
let arr2 = arr1.reverse();
let res = arr2.join('');
console.log(res);
The code execution result:
javascript'987654321'
Example . Usage
Let's simplify the solution of the previous problem - let's merge all the commands into a chain:
javascriptlet str = '123456789';
let res = str.split('').reverse().join('');
console.log(res);
The code execution result:
javascript'987654321'