Use recursion to create a range of numbers - Why doesn't this work? (endNum--)

Hello, my code is below, the part in bold is the focus of my question.

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

If I change endNum-- to endNum - 1 it works, but otherwise it doesn’t. Is there a functional difference between “endNum–” and “endNum - 1”? I thought they were the same thing.

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Yes there is a difference.

The postfix operator minus minus decrements endNum the variable so that endNum becomes a different number after this command completes

endNum - 1

This one evaluates to a value of endNum minus 1 but it doesn’t modify endNum unless you use an assignment operator to set endNum to this new value like endNum = endNum - 1 but that is not what you are doing.

Ah, I understand it now, thanks a lot!

1 Like

Also, I would look up the difference between pre and post fix notation