Basic Javascript - Use Recursion to Create a Range of Numbers

Hi there, recursion is hard to understand. I solved the exercise but I’m not happy with my solution and I would like to know how you will solve same exercise using recursion.

Problem: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers

My Solution:

function rangeOfNumbers(startNum, endNum) {
  if(startNum > endNum){
      return [];
  }else{
      const range = rangeOfNumbers(startNum + 1, endNum);
    	range.unshift(startNum);
    	startNum++;
    	return range;
  }
};

THanks!

What is

startNum++;

doing for you?

1 Like

Hi @JeremyLT ! Thanks for reply.
I added this increment operator after range.unshift() because I need to put the initial startNum value as first element of array. But I’m not sure if my solution is the best, I would like to read another solutions.

My bad. I tried again and I see the increment operator is unnecessary.

Thanks @JeremyLT

1 Like