Unable to reverse array

link to the code FumblingRaggedVaporware - Node.js Repl - Replit

code


const array1 = [1, 2, 3, 4, 5];
let i=0;
let j=array1.length;
function recRev(arr){
  if(i==j || i>j){
    console.log('arr after swapping is :: '+arr);
    return '';
  }
  [arr[i], arr[j]]= [arr[j], arr[i]];
  i++;
  j--;
  recRev(arr);
  
}

recRev(array1);
console.log(array1);

console


array after swapping is :: ,5,4,3,2,1
array after swapping is:: [ undefined, 5, 4, 3, 2, 1 ]

Why arr[0] is undefined …?

Because arrays are zero-indexed so the element at arr[arr.length] is always undefined

const arr = [1,2,3]; // array length is 3, so
console.log(arr[arr.length]) // undefined 

ooh its my bad it must be

let j=array1.length-1;