Search code examples
javascriptrecursionarray-reverse

Why this code is returning undefined?


var rarr = [];
var reverseArray = function(arr) {
  if(arr[0]) {
     rarr.push(arr[arr.length-1]);
     arr.pop();
     reverseArray(arr);
  } else {
    return rarr;
  }
}

console.log(reverseArray(["A", "B", "C"]));

While debugging value of rarr is ['C','B','A'] at the end, instead it is returning undefined. Thanks in advance.


Solution

  • While debugging value of rarr is ['C','B','A'] at the end, instead it is returning undefined

    You are not returning the value that will be returned by recursive calls

    replace

    reverseArray(arr);
    

    with

    return reverseArray(arr);
    

    Or simply

    console.log(["A", "B", "C"].reverse());