JS Problems geeksforgeeks Exercises and Solutions for Beginners

# How to Reverse an Array In-Place and Out-of-Place in JavaScript 📌[All Method]️

The blog is about How to Reverse an Array In-Place and Out-of-Place in JavaScript & provides a lot of information to the novice user and the more seasoned user. After completing this guide, you will know how to face these kind problem.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Reverse an Array In-Place and Out-of-Place in JavaScript. Question:”What should you do if you run into code errors?” Answer:”By following this blog, you can find a solution.”

I remember that I used to Google this question quite a bit because it would come up repeatedly during work. Let’s take this time to understand and remember how JavaScript handles its reversals.

## In-Place Reversal: `reverse()`

``````const arr1 = [1, 2, 3];
const arr2 = arr1.reverse();

console.log(arr1); // [ 3, 2, 1 ]
console.log(arr2); // [ 3, 2, 1 ]
``````

Using `reverse()` by itself will mutate, or modify, the original array.

## Out-of-Place Reversal: `slice()` and `reverse()`

``````const arr1 = [1, 2, 3];
const arr2 = arr1.slice().reverse();

console.log(arr1); // [ 1, 2, 3 ]
console.log(arr2); // [ 3, 2, 1 ]
``````

Using `slice()` with no arguments will default to `slice(0)`, which returns the array from element `0` to the end of the array.

In other words, `slice()` returns a copy of the array while `reverse()` mutates the copied array.

## Out-of-Place Reversal: `slice()` and `reverse()`

``````const arr1 = [1, 2, 3];
const arr2 = arr1.slice().reverse();
``````

Using `slice()` with no arguments will default to `slice(0)`, which returns the array from element `0` to the end of the array.

In other words, `slice()` returns a copy of the array while `reverse()` mutates the copied array.

## Out-of-Place Reversal: `spread` and `reverse()`

``````const arr1 = [1, 2, 3];
const arr2 = [...arr1].reverse();
``````

In ES6, we can use the spread operator to create a new array that we eventually reverse. The general idea is the same as the method above.

## Out-of-Place Reversal: `reduceRight()`

``````const arr1 = [1, 2, 3];
const arr2 = arr1.reduceRight((acc, value) => {
return [...acc, value];
}, []);
``````

We use `reduceRight()` to apply a function to some accumulator `acc` and each `value` of an array, from right to left.

## Out-of-Place Reversal: Recursion

``````const reverse = ([head, ...tail]) => {
if (tail.length === 0) return [head];
else return [...reverse(tail), head];
};
const arr1 = [1, 2, 3];
const arr2 = reverse(arr1);
``````

## Out-of-Place Reversal: Good ol’ `for` loop

``````const arr1 = [1, 2, 3];
let arr2 = [];
for (let i = arr1.length - 1; i >= 0; i--) {
arr2.push(arr1[i]);
}
``````

Now you learned, How you can use & How to Reverse an Array In-Place and Out-of-Place in JavaScript.
If you need assistance at any stage, please feel free to contact me.