How to Reverse an Array in Javascript

In this tutorial, you will learn how to reverse an array in javascript. Reversing the order of items in an array is extremely easy and by doing that we are rearranging the items in an array from end to the beginning. This means that the last item will become the first item and the first item will become the last item.

To reverse the order of items in an array, we can make use of the built-in reverse() method and this method will work perfectly without any issue.

In the following example, we have one global array of numbers.  We will display all the items on the screen in a list format. Upon click of a button, we will reverse the order of the items.  Please have a  look over the code example and the steps given below.

HTML & CSS

  • We have 2 elements in the HTML file (button and ul).
  • The innerText for the button element is “Reverse Array”.
  • The ul element is empty for now and we will populate it dynamically using javascript.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  
  <button>Reverse Array</button>
  <ul></ul>

  <script src="script.js"></script>
</body>
</html>

Javascript

  • We have a global variable users and it holds an array of numbers.
  • We have the addUsers() method which is responsible for populating our ul element.
  • In addUsers() method, we are simply looping through the users array and creating a template string with a bunch of li elements.
  • We are displaying that list in the ul element.
  • We have selected the button element using the document.querySelector() method and attached a click event listener to it.
  • In the event handler function, we are reversing the order of items using the reverse() method, and then we are calling addUsers() method to update the list of the users.
let users = [1, 25, 36, 96, 58, 68];

function addUsers(){
    let template = users.map(user => `<li>${user}</li>`).join('\n');
    document.querySelector('ul').innerHTML = template;
}

addUsers();

document.querySelector('button').addEventListener('click', () => {
    users = users.reverse();
    addUsers();
});