The two sides of the incremental operator in JavaScript ++

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

j1

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.

j2

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

8 thoughts on “The two sides of the incremental operator in JavaScript ++

  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.

  2. 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.

  3. 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++)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s