Quick Tip — Increment(++) and Decrement ( — )operators
Understanding POST and PRE increment operators
I was recently helping someone on a project and there was an issue with the incorrect item in an array being accessed. It all came down to using the increment ++ operator.
I’m sure many beginners and experienced coders alike have experienced an issue with these at some points so I thought a quick explanation would be useful.
The examples are in javascript but they *should* translate to most languages!
So what is the increment operator. Well it normally looks like this ++
and comes after (or before) some kind of numerical value. The idea being that the value is incremented by 1. So 1 would become 2 for example.
The confusion often arises around when this is applied. Take the following example:
let x = 1;
let y = 0;
y = x++;
console.log("x = " , x);
console.log("y = ", y);
You might expect this to output the following:
x = 2
y = 2
But in actual fact it will output x = 2, y=1
. As the ++
operator comes after x
the increment happens post evaluation. So y
is assigned the value of x
and then x
is incremented. Similarly:
let x = 1;
let y = 1;
y = x--;
y
would still be equal to 1 in this example and then x
would be equal to 0. Again as this is a post-decrement value.
Pre-increment and pre-decrement are the opposite. The value is incremented or decremented and then the value of the expression is returned.
let x = 1;
let y = 0;
y = ++x;
So in this example y
and x
would now both be equal to 2. x
is incremented by 1 making it 2 and is then assigned to y
let x = 1;
let y = 1;
y = --x
And finally for the decrement example, both the values of x
and y
will now be equal to 0. e.g 1–1 = 0, then the resulting value is assigned to y
.
I hope you find this tip useful and it helps you avoid any “gotchas” in the future. If you did please consider giving this story a clap and following Room Y. If you’d like to see more of this kind of content then please leave a comment below.