Recursion separating return statement from array push

Hi
Can someone please explain why I need to separate the push function call on the array from the return statement in order for the below code to pass the test? I find recursion quite a challenge. I’d really appreciate why I have to change it to the below in order for it to work? What am I actually returning when it is failing? Thanks

works

function rangeOfNumbers(startNum, endNum) {
if(endNum<startNum){
  return [];
}else{
  const array = rangeOfNumbers(startNum, endNum-1);
  array.push(endNum);
  return array;
}

}

Does not work


function rangeOfNumbers(startNum, endNum) {
if(endNum<startNum){
return [];
}else{
const array = rangeOfNumbers(startNum, endNum-1);
return array.push(endNum);
}

}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Safari/537.36.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

This is because push returns the new array length:

Thanks @JeremyLT, recursion messes with my head, just got confused, yeh i dont return the updated array with this just the length!

1 Like