Recursive function issue with printing an array

Tell us what’s happening:

In this exercise, when executing rangeOfNumbers(1, 5) it shows an array [1, 2, 3, 4, 5]. The second argument (endNum - 1) means endNum becomes 4 before it is pushed in the array, so shouldn’t it print [1, 2, 3, 4]? Why does it print the 5 too?

Your code so far


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


Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

endNum becomes 4

This is incorrect. The subtraction operator - does not reassign the value stored to endNum, it simply returns the result of subtracting 1 from endNum. This operator -- would reassign and subtract, as well as this one -=.

Open up your browser console and run the following to see.

var myNum = 5;
console.log(myNum - 1); // output: 4
console.log(myNum); // output: 5