Search code examples
javascriptloopsincrementoperator-keywordoperands

increment operator vs. i + 1 in loop


let eachScore = [10, 20, 30, 40, 50];

let numOfScores = eachScore.length;

let roundNum = 0;

let msg = '';

// if i change (i + 1) to i++, the loop doesn't work as expected

for (i = roundNum; i < numOfScores; i++) {

  msg += 'Round' + (i + 1) + ': ' + eachScore[i] + '<br/>';

}

document.querySelector("#round").innerHTML = msg
<div id="round"></div>

This is the code I wrote. I understand why i++ doesn't work as expected.

The loop literally increments the i every time it sees i++, but it doesn't increment for (i + 1).

I don't see why i++ and (i + 1) aren't the same. Why (i + 1) doesn't increment just like i++ does?

I saw the definition of increment operator. It just says increment operator adds one to its operand and returns a value, which seems like it's saying i++ is the same as (i + 1)...


Solution

  • You are correct. MDN documentation for ++A says

    The increment operator (++) increments (adds one to) its operand and returns a value.

    which is unfortunate as it doesn't clarify what's going on and why use "pre" (or "post") to qualify "increment".

    To pre-increment a variable means to get the value of the variable from memory, add one to it, store the result back in memory and return the addition result as the result of the pre-increment operator. It's called "pre" increment because incrementation occurs before returning the updated value of the variable to the program.

    In contrast, to post increment a variable means to get the current value of the variable from memory, make a copy of it (perhaps in a CPU register), increment the value and save it back in memory - and then return the copied value the variable had before the addition took place. It called "post" increment because incrementation occurs after getting the value to return to the program.

    Of course, (i+1) just gets the value of i, adds one to it and returns the result of the expression without updating the value of i.


    A more precise version of the MDN article could include "l-value" in the glossary and describe the operator along the lines of:

    The increment operator (++) is a unary assignment operator that increments its operand in storage and returns a result. The operand must be an l-value.

    • If ++ is used as a prefix operator, the incremented value of the operand is returned as the result of the operation.

    • If ++ is used as a postfix operator, the value of the operand before being incremented is returned as the result of the operation.