Recursion to get Range of Numbers

Recursion is a technique to reuturn a function as a loop until it meet a condition. So instead of loop such as for, map, etc we will simply return a function until it is meet with a condition to break the loop.

function rangeOfNumbers(startNum, endNum) {

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

rangeOfNumbers(1,5)
///(5) [1, 2, 3, 4, 5]

Leave a Reply

Your email address will not be published.