DEV Community

Abhi Raj
Abhi Raj

Posted on

JavaScript program to reverse an array using recursion

let arr = [1, 2, 3, 4, 5];

let reverseArray = (arr, left, right) => {
  if (left >= right) {
    console.log(arr);
    return;
  }

//swapping first element to last element
  [arr[left], arr[right]] = [arr[right], arr[left]];

//callling the function again
  reverseArray(arr, left + 1, right - 1);
};

reverseArray(arr, 0, arr.length - 1);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)