How to write a code that is more efficient?

Tell us what’s happening:
I was trying to solve challenge “Use Recursion to Create a Range of Numbers” which I did solve, but when I looked at my solution and the solutions given in the on help page I found that I am writing some seriously complicated and inefficient code(which I even find hard to explain). How can improve that?

Your code so far


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

Your browser information:

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Remove the duplicate code. Specifically, the following two lines:

  numbers.unshift(startNum);
  return numbers;

It is worth keeping in mind that visually compact code is not always the most efficient code. In general, recursion will be slower than a loop. It’s just sometimes the easiest way to solve certain problems (though any recursion problem can be done with a loop and vice versa).