Beginner question. increment

Hello, everyone! Sorry for noob question here.

function test(number) {
  while( number < 5 ) {
    number++;
  }
  return number;
} 
alert(test(2));  // returns 5. 

My question is when we increment value and place + after the argument (number++) by the rule it should first return the old value and than add 1 to it. But why in the example above it return 5?

Consider the number 4. It’s less than 5 so it meets the condition of the while loop, and the 4 gets increased to a 5. When the condition is checked again, 5 is not less than 5, so the while loop ends, and the 5 is returned.

Hi @sportsbazar! It does return the old value, but only from the current expression:

var value = 0

console.log(value++) // -> 0
console.log(value)   // -> 1
console.log(++value) // -> 2
console.log(value)   // -> 2

So after that expression got evaluated, value has been incremented either way; and the final return value from the function will always be 5.

x-post

1 Like

Thank you!

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