0
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.

kamal kokne
  • 175
  • 10
  • 1
    notwithstanding the `return` bug in the answers given so far, testing `arr[0]` to get loop termination is _horrible_ - it'll break if any element of your array holds a falsey value (e.g. zero) – Alnitak Apr 25 '16 at 13:05
  • Thanks for pointing out. :) – kamal kokne Apr 25 '16 at 13:08

2 Answers2

1

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());
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

you forgot a return in your if... try this:

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

console.log(reverseArray(["A", "B", "C"]));
silly
  • 7,789
  • 2
  • 24
  • 37