freeCodeCamp Challenge Guide: Use Recursion to Create a Range of Numbers

Use Recursion to Create a Range of Numbers


Solutions

Solution 1 (Click to Show/Hide)
function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
  } else {
    var numbers = rangeOfNumbers(startNum, endNum - 1);
    numbers.push(endNum);
    return numbers;
  }
}
Solution 2 (Click to Show/Hide)
function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}
Solution 3 (Click to Show/Hide)
function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : [...rangeOfNumbers(startNum, endNum - 1), endNum ];
}
54 Likes