93 of 264 menu

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

array.reverse();

Example

Let's reverse an array:

let arr = ['a', 'b', 'c']; arr.reverse(); console.log(arr);

The code execution result:

['c', 'b', 'a']

Example

And now let's write the reversed array into a new variable:

let arr = ['a', 'b', 'c']; let res = arr.reverse(); console.log(res);

The code execution result:

['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:

let str = '123456789'; let arr1 = str.split(''); let arr2 = arr1.reverse(); let res = arr2.join(''); console.log(res);

The code execution result:

'987654321'

Example . Usage

Let's simplify the solution of the previous problem - let's merge all the commands into a chain:

let str = '123456789'; let res = str.split('').reverse().join(''); console.log(res);

The code execution result:

'987654321'

See also

  • the split method
    that splits a string into an array by the specified separator
  • the join method
    that concatenate an array into a string by the specified separator
byenru