Increment a Number with JavaScript (V2)

Tell us what’s happening:
Describe your issue in detail here.
See code below. myVar++ evaluates at 88, which makes sense.

If everything to the “right” of the equal sign is evaluated first, why does myVar = myVar++ evaluate as 87, when using the Post Fix increment operator? Shouldn’t it evaluate as 88?

Your code so far
let myVar = 87;
myVar = myVar++; // Evaluates as 87
myVar++; // Evaluates at 88

Your browser information:
Chrome

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

Challenge:
Increment a Number with JavaScript

Link to the challenge:

MDN: Pre vs Post increment

Bottom line: Pre increment returns value AFTER incrementing. Post increment returns value BEFORE incrementing.

1 Like

It is best to avoid code where the difference between prefix and postfix incrementing matters.

In this case, it’s a bit bizarre to use an assignment operator in conjunction with an incrementor.

bbsmooth, I get the difference between Pre and Post. I just don’t understand why using the assignment operator with increment results in a 87, whereas when you leave out the assignment operator, and just use the variable + increment operator you get 88. Thanks for the reply!

JeremyLT, I get it, and agree. Will log this one under one of those things you just have to keep an out for when coding. Thanks!

… Because of the difference between pre and post incrementing.

The incrementing operator is a function with a return value. Everything’s a function, operators are just a little less clear about the fact that they are functions.

The return value depends upon if pre or post incrementing is used.

function preincriment(variable) {
  variable.value = variable.value + 1;
  return variable.value;
}

function postincriment(variable) {
  const oldValue = variable.value;
  variable.value = variable.value + 1;
  return oldValue;
}

This makes sense, thanks JeremeyLT!

1 Like

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