The recursive range function does not work

I am trying to teach myself recursion by recursively performing a range function. I can not understand why the code below does not work?

Iterative version:

function rangeList(num, num2) { var arr = []; for (var i = num; i < num2; i++) { arr.push(i); } return arr; } 

Recursive version:

 function rangeRecursive(num, num2) { return (num2 > num) ? rangeRecursive(num2 - 1).concat(num2) : [] } console.log(rangeList(1, 7)); // returns [1, 2, 3, 4, 5, 6] console.log(rangeRecursive(1, 7)); // returns [7] 
+6
source share
2 answers

This does not work because you are missing a parameter in a recursive call

It should be like

 function rangeRecursive(num, num2) { return (num2 >= num) ? rangeRecursive(num /*this was missing*/, num2 - 1).concat(num2) : [] } 

Also pay attention to the changed condition on the ternary, otherwise it stops at 1 and does not contact it. Either you can use >= or the following

 return num2 > num ? rangeRecursive(num, num2 - 1).concat(num2) : [num] 
+5
source

You are missing a parameter in your recursive function. It should be like this:

 function rangeRecursive(num, num2) { return num2 > num ? rangeRecursive(num, num2 - 1).concat(num2) : [num] } 
+1
source

All Articles