Prefix vs Postfix operators. What's the difference?

Prefix vs Postfix operators. What's the difference?

Β·

2 min read

If you're like me, you've probably had this question for a while and seen answers along the lines of, "Prefix returns the new value while postfix returns the old one". But then that leaves you even more confused when you try to apply it in your code. Well, I've finally figured out the difference and, at the end of this article, you will too.

First off, I'll be using JavaScript language but note that this applies to many other programming languages as well.

The increment and decrement operators increase or decrease the value of a variable by one. There are two forms by which this operator can be applied to a variable.

  1. Prefix form.
  2. Postfix form.

With prefix form, the operator is placed before the variable (eg ++i), while with postfix, it is placed after the variable (eg i++). Both forms increment the value of i by one but we see a difference when we try to use the returned value IN THE SAME STATEMENT where it was incremented.

Take a look at the following lines of code:

let i = 5;
let num;

num = ++i * 2;     //i = 6
alert(num);
let i = 5;
let num;

num = i++ * 2;.    //i = 5
alert(num);

In the first prefix example, i is incremented and its new value of 6 is multiplied by 2 to give 12. Meanwhile, in the postfix form, the value of i is also incremented but since the multiplication operator is applied in the same statement where i was incremented, the old value of 5 is used to perform the operation.

With this, we can see that when we increment a value and perform an action with it in the same statement, prefix form will use the new incremented value but postfix will use the old value.

The same also applies with the decrement operator.

let v = 7;
alert (v--);     //alerts 7
let v = 7;
alert (--v);.    //alerts 6

Hopefully, this has cleared up all your issues with prefix and postfix forms. Have fun coding!

Β