Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to reverse an array in JavaScript

Reversing an array is a common programming task that you will encounter in your coding journey. In this blog post, we'll dive into the world of JavaScript and learn how to reverse an array using various methods. We'll start with the basics and then move on to some more advanced techniques. Whether you're a beginner or an experienced programmer, this post will serve as a comprehensive guide to help you understand and implement array reversal in JavaScript.

What is an Array?

Before we dive into the topic of reversing arrays, it's essential to understand what an array is. An array is a data structure that stores a collection of values, also known as elements. These elements can be of any data type, such as strings, numbers, objects, or even other arrays. Arrays are ordered, meaning that you can access each element using an index (a numerical value representing the element's position in the array).

In JavaScript, you can create an array using the square bracket notation. Here's an example:

let fruits = ['apple', 'banana', 'cherry'];

In this example, we have an array called fruits, which contains three string elements. You can access each element using its index, like this:

console.log(fruits[0]); // Output: apple

Now that we have a basic understanding of arrays let's move on to the main topic - reversing an array.

Method 1: Using the reverse() method

The easiest way to reverse an array in JavaScript is to use the built-in reverse() method. This method reverses the order of the elements in the original array and returns a reference to the modified array. Here's an example:

let numbers = [1, 2, 3, 4, 5];
numbers.reverse();

console.log(numbers); // Output: [5, 4, 3, 2, 1]

It's important to note that the reverse() method modifies the original array. If you want to reverse the array without changing the original array, you can create a copy of the array first, and then reverse it. You can use the slice() method to create a shallow copy of the array:

let originalNumbers = [1, 2, 3, 4, 5];
let reversedNumbers = originalNumbers.slice().reverse();

console.log(originalNumbers); // Output: [1, 2, 3, 4, 5]
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]

Method 2: Using a loop

Another way to reverse an array is to use a loop. This method can be helpful if you want more control over the array reversal process, or if you're working in an environment where the reverse() method is not available. Here's how you can reverse an array using a loop:

function reverseArray(arr) {
  let result = [];

  for (let i = arr.length - 1; i >= 0; i--) {
    result.push(arr[i]);
  }

  return result;
}

let originalNumbers = [1, 2, 3, 4, 5];
let reversedNumbers = reverseArray(originalNumbers);

console.log(originalNumbers); // Output: [1, 2, 3, 4, 5]
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]

In this example, we've created a function called reverseArray() that takes an array as an input and returns a new array containing the reversed elements. We're using a for loop to iterate through the elements of the input array in reverse order, starting from the last element (at index arr.length - 1) and going down to the first element (at index 0). Inside the loop, we're using the push() method to add each element to the result array. After the loop is done, we return the result array.

It's important to note that this method does not modify the original array, so you can use it if you want to keep the original array unchanged.

Method 3: Using the reduce() method

The reduce() method is another powerful built-in JavaScript method that you can use to reverse an array. This method is used to apply a function to each element in the array, accumulating the result in a single value. Here's how you can use the reduce() method to reverse an array:

function reverseArray(arr) {
  return arr.reduce((accumulator, currentValue) => {
    accumulator.unshift(currentValue);
    return accumulator;
  }, []);
}

let originalNumbers = [1, 2, 3, 4, 5];
let reversedNumbers = reverseArray(originalNumbers);

console.log(originalNumbers); // Output: [1, 2, 3, 4, 5]
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]

In this example, we've created a function called reverseArray() that takes an array as an input and returns a new array containing the reversed elements. We're using the reduce() method to iterate through the elements of the input array and apply a function that takes two arguments: the accumulator and the current value.

The accumulator is an array that we're building up as we go through the elements of the input array. The current value is the current element in the input array. Inside the function, we're using the unshift() method to add the current value to the beginning of the accumulator array. This way, the elements of the input array are added to the accumulator in reverse order.

Finally, we return the accumulator array as the result of the reduce() method. Just like the loop method, this method does not modify the original array.

Conclusion

In this blog post, we've explored three different methods to reverse an array in JavaScript: using the reverse() method, using a loop, and using the reduce() method. Each method has its pros and cons, so you can choose the one that best fits your needs.

As a beginner, it's essential to understand these methods and practice implementing them in your code. As you gain more experience, you'll be able to decide which method is most suitable for a particular situation. Happy coding!