I learned this last week, possibly highlighting my non-classical programming training. I have never come across this in all my years of JavaScript and apparently it is pervasive in other languages such as Java as well.
Incremental Operator ++
Many times I have seen or used the following method for incrementing an integer count
var marky = 0; console.log(++marky); console.log(marky);
This increments the integer marky by 1. not rocket science. In the image below you can see that the two console.log entries always return the same value
What I learned yesterday was using the ++ after the variable name also increases the variable – but only AFTER the value has been evaluated…
From this image you can see that the marky++ value and the marky value are not the same. The console.log(marky++); returns the existing marky value and then increments it.
var marky = 0; console.log(marky++); console.log(marky);
I have to ask myself “why would anyone do that?”. Why would I want to return a variable value and THEN increase it’s value, seems a little odd to me. I guess someone thought it was a good idea…..
Always makes me think “I wonder what else I don’t know? Probably best not think about that too much”….
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
You really should take my JavaScript class Mr. 😉
Yes sir…..
I hate these incrementors. They’re the cause of many difficult to find bugs. I’d rather go with X =+ 1. A lot easier to read.
You have to write X += 1.
X =+ 1 is more difficult to read.
X =- 1 VS. X = -1
I’ve found that this behavior, like 0-based indexing, is one of those C-language things that seems counter-intuitive at first, but has lots of clever little payoffs all the time.
Fwiw, as a long time C and C++ programmer, I use the post-increment far more often than the pre-increment. The reason why is simple. Since arrays are zero-based in C/C++, if I have code that says:
count = 0;
while (condition)
{
if (other-condition)
myarray[count++] = value;
…
}
then at the end, count is the number of elements filled in the array, while count-1 is the last element filled.
Thanks for the comments
you know as I am reading this it occurred to me that I use the post-increment all the time and never even realized it – muscle memory (facepalm)
for (i=0; i<10; i++)