What's the difference between Increment operator (++) and the operator + 1

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

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

console.log(rangeOfNumbers(1, 5));
  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Why if i use (++) the console would say “RangeError: Maximum call stack size exceeded” isn’t increment operator is the same with the operator + 1

Welcome to the forum.

Using + 1 just creates a formula that gets evaluated. It doesn’t affect the original.

let a = 1
console.log(a + 1) // 2
console.log(a)     // 1

The original is not changed.

The ++ operator adds 1 to the original, it changes the original.

There is the post increment version:

let a = 1
console.log(a++) // 1
console.log(a)   // 2

Because we used the post version, it evaluated (in this case to 1) first and then incremented.

There is also the pre increment version that will increment first and then evaluate.

let a = 1
console.log(++a) // 2
console.log(a)   // 2

That is the difference. The increment operator will change the original. It can also evaluate to a value.

Be careful with the increment operator. It’s good to avoid it in situations where it is not obvious what is happening - usually when you are using it in a formula or parameter list or something, where you have to stop and think how the increment affects the evaluation.

Back in the olden-days (I mean assembler language days), there was a difference in performance between:

num  = num + 1
num += 1
num++

I don’t think it matters much anymore.

Why if i use (++) the console would say “RangeError: Maximum call stack size exceeded” isn’t increment operator is the same with the operator + 1

Because you are changing the value of startNum.

2 Likes

Thanks for the answers!
Can you give me an explanation on what really happen with my code,i’m still confused on why is the error says “RangeError: Maximum call stack size exceeded”

I would suggest you log out startNum at the top of the function.

You would need to do a postfix prefix (edit not sure why I wrote postfix) increment so the value is incremented before it is used. And then because you changed the value you would need to decrement it for the unshift.

const range = rangeOfNumbers(++startNum, endNum);
range.unshift(--startNum);
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.