Reversing an array in JavaScript can be done in several ways depending on the specific use case. Below, I’ll show all major types of examples

 

. Using the Built-in .reverse() Method

This is the simplest and most direct way.

javascript

let arr = [1, 2, 3, 4, 5]; arr.reverse(); console.log(arr); // [5, 4, 3, 2, 1]

⚠️ This method mutates the original array.


🔁 2. Using the Spread Operator & .reverse() (Non-mutating)

To avoid changing the original array:

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = [...arr].reverse(); console.log(reversed); // [5, 4, 3, 2, 1] console.log(arr); // [1, 2, 3, 4, 5] — unchanged

🔁 3. Using a for Loop

Manual reverse using a classic for loop:

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = []; for (let i = arr.length - 1; i >= 0; i--) { reversed.push(arr[i]); } console.log(reversed); // [5, 4, 3, 2, 1]

🔁 4. Using a while Loop

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = []; let i = arr.length - 1; while (i >= 0) { reversed.push(arr[i]); i--; } console.log(reversed); // [5, 4, 3, 2, 1]

🔁 5. Using Recursion

A functional way to reverse an array:

javascript

function reverseArray(arr) { if (arr.length === 0) return []; return [arr.pop()].concat(reverseArray(arr)); } let arr = [1, 2, 3, 4, 5]; console.log(reverseArray([...arr])); // [5, 4, 3, 2, 1]

🔁 This also mutates the original if not cloned with [...arr].


🔁 6. Using reduceRight()

A more functional-style approach:

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = arr.reduceRight((acc, curr) => { acc.push(curr); return acc; }, []); console.log(reversed); // [5, 4, 3, 2, 1]

🔁 7. Swapping Elements In-Place

This doesn't use extra space and is optimal for large arrays:

javascript

let arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length / 2; i++) { let temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } console.log(arr); // [5, 4, 3, 2, 1]

Summary Table:

MethodMutates?Extra SpaceNotes
.reverse()Simple, in-place
[...arr].reverse()Clones, safer
for/while loopGood for manual control
Recursion✅ or ❌Elegant but less efficient
reduceRight()Functional-style
In-place swapOptimal for performance


No comments:

Post a Comment

Best for you