DEV Community

Cover image for The difference between x++ and ++x
Basti Ortiz
Basti Ortiz

Posted on

The difference between x++ and ++x

The laziness and practicality of a programmer

Let's face it. Programmers are paid to type some magic into a screen that eventually becomes something that works. Since an entire work day mostly consists of reading and typing, it naturally follows that syntax must be shortened to increase productivity and readability... or for the sake of saving a few more keystrokes because typing is tiring.

This is why we have increment/decrement operators.

// Suppose we have a variable that stores a number
let someNum = 0;

// Practicality Level 1
someNum = someNum + 1;

// Practicality Level 2
someNum += 1;

// Practicality Level 9000+
someNum++;

// Wait... or should I use...?
++someNum;

Enter fullscreen mode Exit fullscreen mode

Ah, now we have come face to face with the issue at hand: what is the difference between someNum++ and ++someNum?

Prefix vs. Postfix

  • Prefix: ++someNum
  • Postfix: someNum++

At first glance, it may seem like a syntactic preference; similar to that of generators, where you can define one by writing function* generator() {} or function *generator() {}. Contrary to intuition, there are subtle differences in how each works, specifically in what each returns.

DISCLAIMER: For the rest of the article, I shall only use increment operators for the sake of brevity. It should be implied from here on out that what is true for increment operators is also true for decrement operators.

Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.

  • The prefix increment returns the value of a variable after it has been incremented.
  • On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.
// Prefix increment
let prefix = 1;
console.log(++prefix); // 2
console.log(prefix); // 2

// Postfix increment
let postfix = 1;
console.log(postfix++); // 1
console.log(postfix); // 2
Enter fullscreen mode Exit fullscreen mode

To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.

When do I use one over the other?

It really depends on you, the programmer. At the end of the day, all we really want from the increment operator is to increment a variable by 1. If you are still concerned about their differences, there are some cases when one can be used over the other to write simpler code. For example, consider the following situation.

A button with an ID of counter counts how many times it has been pressed. It changes the innerHTML of a span with an ID of displayPressCount according to the number of times the button has been pressed. The common approach is to attach a click listener that increments some global variable.

// Global variable that counts how many times the button has been pressed
let numberOfPresses = 0;

// Stores necessary HTML elements
const button = document.getElementById('counter');
const span = document.getElementById('displayPressCount');

// Event handler
function clickHandler() {
  // Increment counter
  numberOfPresses++;
  span.innerHTML = numberOfPresses;
}

// Attach click listener to button
button.addEventListener('click', clickHandler);
Enter fullscreen mode Exit fullscreen mode

Now, let's switch our focus to the clickHandler. Notice how the increment operator takes up a whole new line of code in the function? Recalling what the prefix increment returns can help us shorten the function.

// Event handler
function clickHandler() {
  // Increment counter
  span.innerHTML = ++numberOfPresses;
}
Enter fullscreen mode Exit fullscreen mode

Voila! It has been shortened! If we want to go crazier, we can even use arrow functions. The entire script now looks like this.

// Global variable that counts how many times the button has been pressed
let numberOfPresses = 0;

// Stores necessary HTML elements
const button = document.getElementById('counter');
const span = document.getElementById('displayPressCount');

// Attach click listener to button
button.addEventListener('click',
  () => (span.innerHTML = ++numberOfPresses)
);
Enter fullscreen mode Exit fullscreen mode

Things to Remember

The prefix and postfix increment both increase the value of a number by 1. The only difference between the two is their return value. The former increments (++) first, then returns the value of x, thus ++x. The latter returns the value of x first, then increments (++), thus x++.

Now go and spread your newfound knowledge to the world!

Top comments (50)

Collapse
 
fxedel profile image
Felix Edelmann • Edited

Nice explanation! However, I'm not happy with the last line of your last code example:

button.addEventListener('click', () => span.innerHTML = ++numberOfPresses); 
Enter fullscreen mode Exit fullscreen mode

The occurrence of both => and = make the expression somehow difficult to read.

One could use parentheses to emphasize the assignment:

button.addEventListener('click', () => (span.innerHTML = ++numberOfPresses)); 
Enter fullscreen mode Exit fullscreen mode

Or maybe one could spend a new line:

button.addEventListener('click',
  () => (span.innerHTML = ++numberOfPresses)
);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
somedood profile image
Basti Ortiz

I totally agree with you there. I don't have the best code formatting skills, so that's nice of you to bring up. I'll go edit the format right now. Thanks for the suggestion!

Collapse
 
jonasroessum profile image
Jonas Røssum

I suggest using prettier, since it is have become a well accepted and easily readable code format.

You can try it out here:
prettier.io/playground/

Thread Thread
 
somedood profile image
Basti Ortiz

As nice as a standardized code format sounds, I just can't agree with some of them. I'm looking at you, "Standard" JS. I prefer to have my own coding style. I think of coding as an "art form", where my coding style is my "signature".

Don't let that discourage you from using Prettier, though. I totally agree with its objective to standardize code formats for the sake of productivity and readability.

Thread Thread
 
jonasroessum profile image
Jonas Røssum

Oh man, I also despited Standard when I first tried it! What a frustrating experience I.

For some reason though, my experience with prettier has been almost the opposite. I think it's partly due to it having sane and very readable defaults and partly because I've set it up to match my personal code style (e.g. no semi-colons).

I've discovered how having automatic formatting in my editor is priceless for productivity! No more fiddling with indents and line breaks. Recently I've found myself using Format On Save in Visual Studio Code more often, as it just makes having clean code that much easier.

Thread Thread
 
somedood profile image
Basti Ortiz

To me, I primarily disagreed with how Standard JS treats semicolons. I mean just look at this absurdity! I don't like how it is being too clever with the format.

;[1, 2, 3].forEach(bar)
;(function () {
  window.alert('ok')
}())
;`hello`.indexOf('o')

Of course, this is an extreme example. Even their documentation discourages lines of code that begin with [, (, and the like. Nonetheless, I just feel strange when they have the audacity to call it "Standard" JS in the face of some weird syntax that is too clever.

Thread Thread
 
canlitvizlemeli profile image
Canlı Tv İzlemeli

I tried this method on tv izle my platform and I was very successful. Thank you.

Collapse
 
codevault profile image
Sergiu Mureşan • Edited

Great explanation! I found it quite difficult to explain this feature (albeit in C) in a video or post and you've done a really good job at it!

If you have ever joined programming Facebook groups you will see one question related to this topic pop up quite often:

// What will the value of x be after executing these statements?
let x = 1;
x = x++ + ++x + x++;

The answer: depends. In JavaScript I get 7, probably because they are evaluated from left to right (and because it is an interpreted environment) but in C or Java you can get some really unexpected results and in most languages it is undefined behaviour.

Collapse
 
ivanovicdanijel profile image
danijel

Undefined behaviour!?
In Java,
x = 1 + 3 + 3 = 7
What is undefined?

Collapse
 
codevault profile image
Sergiu Mureşan

Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

In Java they are also evaluated from left to right (unless you have a x += 1 instead of x++) then it gets confusing.

This answer goes more in-depth about undefined behaviour in C/C++

Thread Thread
 
ivanovicdanijel profile image
danijel

Thanks a lot!;)

Collapse
 
xowap profile image
Rémy 🤖

I think that the length of this article for something seemingly so simple is the proof that using ++ should be forbidden (by example, it does not exist in Python).

Here's another article on an alternate method:


To increment a variable, simply use the following syntax:

i += 1

Here's an example on how to use in a for loop:

const stuff = ['a', 'b', 'c', 'd'];

for (let i = 0; i < stuff.length; i += 1) {
    console.log(stuff[i]);
}

Pitfalls: none

When to use this method: well anytime you need to increment by one.

Collapse
 
fpuffer profile image
Frank Puffer

No. The += operator is used to add any number to a given variable. Increment is more elementary than addition. When used in programming, it normally has a completely different semantics than addition. Therefore it does make sense if a language has a special operator for it. It makes the language more expressive and the code at least potentially more readable.

The complications addressed in this thread do not result from the existence of the increment operator itself but from the fact that there are two of them in certain languages.

Collapse
 
xowap profile image
Rémy 🤖

Well good point on increment theoretically being a different operation than addition, however in practice I think in terms of produced bugs.

If you do stuff like

const a = ['a', 'b', 'c'];
let i = 0;

while (a[i] !== undefined) {
    doStuff(a[i++]);
}

At the moment you start digging into it and do some quick copy/pasta for debugging purposes:

const a = ['a', 'b', 'c'];
let i = 0;

while (a[i] !== undefined) {
    doStuff(a[i++]);
    console.log(a[i++]);
}

You're done because you've created a bug.

So I know you're going to explain to me all the rules to follow not to create bugs and the rigorous way you have to work with ++. However if you just don't use it then you don't need to use those rules and that's many less issues to load your head with. Also it's pretty easy to forbid it in the linter so you also help juniors not making mistakes.

Unlike what you said, the real issue is not that you can do both operations but rather that you're playing with side-effects. Neither of those operators are good.

In case you're curious about how it goes under the hood, I've compiled two example functions. A first one which does a ++:

char get_next_char_pp(char* str, int i) {
    return str[++i];
}

The produced ASM is the following

get_next_char_pp:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     DWORD PTR [rbp-12], esi
        add     DWORD PTR [rbp-12], 1
        mov     eax, DWORD PTR [rbp-12]
        movsx   rdx, eax
        mov     rax, QWORD PTR [rbp-8]
        add     rax, rdx
        movzx   eax, BYTE PTR [rax]
        pop     rbp
        ret

Now using the += 1 method:

char get_next_char_add(char *str, int i) {
    i += 1;
    return str[i];
}
get_next_char_add:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     DWORD PTR [rbp-12], esi
        add     DWORD PTR [rbp-12], 1
        mov     eax, DWORD PTR [rbp-12]
        movsx   rdx, eax
        mov     rax, QWORD PTR [rbp-8]
        add     rax, rdx
        movzx   eax, BYTE PTR [rax]
        pop     rbp
        ret

As you can see, CPU-wise it is totally identical. The compiler actually just splits your line in two implicitly. And as the Zen of Python says: Explicit is better than implicit.

Hence my strong advocacy against the ++ operator in any language. It is a useless and harmful operator, source of headaches and bugs.

Thread Thread
 
fpuffer profile image
Frank Puffer

Yes, the main issue is mutability. The ++ operator is actually a hidden assignment. In most modern languages there are few use cases for incrementing variables, mainly because they provide better ways for looping over collections. However I sometimes have to maintain legacy C code where I don't want to miss ++ in for loops.

I believe that += is only slightly better when it comes to copy/paste errors. You can also do this (at least in C++ and Java - not sure about JS):

while ( ... ) {
    doStuff(a[i += 1]);
    console.log(a[i += 1]);
}

But it looks weird and will hopefully be noticed soon.

Collapse
 
awwsmm profile image
Andrew (he/him)

Additionally, there can be a performance difference between prefix and postfix in some languages. If it doesn't matter to you which one is used, prefix (++i) should be your default. Reference

Collapse
 
somedood profile image
Basti Ortiz • Edited

Someone should make a jsPerf for that. Although I doubt a significant performance difference, it is nonetheless interesting (and exciting) to see the results.

Collapse
 
fabioemsm profile image
Fábio Moreira

It may have, performance implications in some languages. Think of these operators as functions (functors, I believe) as for ++x you'd something like:
public int ++operator (int &x) {
x = x + 1;
return x;
}
And for x++ you have something like
public int operator++ (int &x) {
int tmp = x;
x = x + 1;
return tmp;
}

As you can see, from the second example above, there is one more instruction needed to store the previous value of x and then return it.
But I don't think there is a major impact unless you use it extensively, also todays compilers may or may not predict and optimize the end result.
PS: the examples above only work in languages that have the concept of functors (function operators) like C++ does.

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

One other critical difference in some languages, including C and C++: ++x is one less compiled instruction than x++. That can add up to a notable performance difference in some applications, especially loops. I imagine that would be true of most languages with increment operators.

Yes, your compiler will sometimes optimize that anyway, but it depends on which optimizations you've opted in to, as well as other circumstances. As pythonic as the saying may be, "explicit is better than implicit" is true as a generally universal rule, especially wherever performance is concerned.

Collapse
 
lisabenmore profile image
Lisa Benmore

Great breakdown of the differences! One additional use-case to mention where prefix vs postfix makes a world of difference is when you're passing it into a function. For instance a recursive function where we're using incrementation as a condition:

function count (limit, current = 0) {
  console.log(current);
  if (current < limit) return count(limit, ++current);
  else return current;
}
count(10);
Enter fullscreen mode Exit fullscreen mode

The above will console out 0-10 and return 10. However, if we were to use postfix, we'd have to increment before our if/else statement or else it would be an infinite loop where current is always equal to zero. Obviously, this function is only as an example and wouldn't be very useful in practice, but it was a similar case where I really learned the difference between x++ and ++x ;)

Collapse
 
medhair profile image
medhair

Le pays du Bosphore et plus particulièrement la ville d’Istanbul offrent les conditions parfaites pour une greffe de cheveux turquie

Collapse
 
paul202183 profile image
paul202183

Thank you for sharing your knowledge with this informative post about one of the intricacies of JavaScript. Well-written explanation.luxury replica watches

Collapse
 
floppleus profile image
Roger Flopple

Thank you very much for your great information. It really makes me happy and I am satisfied with the arrangement of your post captain marvel sweater. You are really a talented person I have ever seen. I will keep following you forever.

Collapse
 
knownigeria_ng profile image
KnowNigeria • Edited

Thank you very much for your great information. It really makes me happy and I am satisfied with the arrangement of your post Davido & Offset. You are really a talented person I have ever seen. I will keep following you forever.

Collapse
 
riyasrawther profile image
Riyas Rawther
void main() {
  int y;

  //Prefix  (e.g ++a)
  y =1; 
  print (++y); // Prints the previous (1) value, then adds 1 to it. Output is 2
  print (++y); // Previous value is 2 and adds 1 to it. Output is 3
  print (++y); // Previous value is 3 and adds 1 to it. Output is 4
  //note: The first value will be the initial number + 1. Then incements with 1 each time when it called.
  //Prefix 

  // example
  for (int i = 0; i < 5; ++i){
 print('The values are: ${i}'); 
   // note that the first number will be 0
   // to start from 1 change the ${i} to ${i+1}
 }

}
Collapse
 
trakode profile image
Trakode • Edited

Thank you,

Really very well explained, I'm going to get inspired to explain this to my group on Trakode

Why not in a video conference!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.