The difference between x++ and ++x (2024)

The difference between x++ and ++x (1)

The difference between x++ and ++x (2)

Basti Ortiz

Posted on

The difference between x++ and ++x (3) The difference between x++ and ++x (4) The difference between x++ and ++x (5) The difference between x++ and ++x (6) The difference between x++ and ++x (7)

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 numberlet someNum = 0;// Practicality Level 1someNum = someNum + 1;// Practicality Level 2someNum += 1;// Practicality Level 9000+someNum++;// Wait... or should I use...?++someNum;

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

  • 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 incrementlet prefix = 1;console.log(++prefix); // 2console.log(prefix); // 2// Postfix incrementlet postfix = 1;console.log(postfix++); // 1console.log(postfix); // 2

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

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 pressedlet numberOfPresses = 0;// Stores necessary HTML elementsconst button = document.getElementById('counter');const span = document.getElementById('displayPressCount');// Event handlerfunction clickHandler() { // Increment counter numberOfPresses++; span.innerHTML = numberOfPresses;}// Attach click listener to buttonbutton.addEventListener('click', clickHandler);

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 handlerfunction clickHandler() { // Increment counter span.innerHTML = ++numberOfPresses;}

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 pressedlet numberOfPresses = 0;// Stores necessary HTML elementsconst button = document.getElementById('counter');const span = document.getElementById('displayPressCount');// Attach click listener to buttonbutton.addEventListener('click', () => (span.innerHTML = ++numberOfPresses));

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)

Subscribe

The difference between x++ and ++x (9)

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

button.addEventListener('click', () => span.innerHTML = ++numberOfPresses); 

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)); 

Or maybe one could spend a new line:

button.addEventListener('click', () => (span.innerHTML = ++numberOfPresses));

The difference between x++ and ++x (11)

Basti Ortiz

Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.

  • Location

    Philippines

  • Education

    B.S. Computer Science @ University of the Philippines Diliman

  • Pronouns

    he/him

  • Joined

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!

The difference between x++ and ++x (13)

Jonas Røssum

Self-taught web application developer

  • Email

    jonas.g.roessum@gmail.com

  • Joined

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/

The difference between x++ and ++x (15)

Basti Ortiz

Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.

  • Location

    Philippines

  • Education

    B.S. Computer Science @ University of the Philippines Diliman

  • Pronouns

    he/him

  • Joined

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.

The difference between x++ and ++x (17)

Jonas Røssum

Self-taught web application developer

  • Email

    jonas.g.roessum@gmail.com

  • Joined

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.

The difference between x++ and ++x (19)

Basti Ortiz

Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.

  • Location

    Philippines

  • Education

    B.S. Computer Science @ University of the Philippines Diliman

  • Pronouns

    he/him

  • Joined

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.

The difference between x++ and ++x (21)

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

The difference between x++ and ++x (23)

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.

The difference between x++ and ++x (25)

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

The difference between x++ and ++x (27)

Sergiu Mureşan

Thank you for stopping by! I am a full-stack developer that combines the power of entrepreneurship and programming to make the lives of programmers easier.

  • Location

    Cluj Napoca, Romania

  • Education

    Computer Science

  • Work

    Full Stack Developer

  • Joined

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++

The difference between x++ and ++x (29)

Thanks a lot!;)

The difference between x++ and ++x (31)

Rémy 🤖

I spent my adolescence in Dreamweaver, my student years in Vim and my adult life in PyCharm.

  • Location

    Madrid

  • Education

    Telecommunications Engineer

  • Work

    CTO at WITH Madrid

  • Joined

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.

The difference between x++ and ++x (33)

Frank Puffer

Software developer, among other things

  • Location

    Europe

  • Joined

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.

The difference between x++ and ++x (35)

Rémy 🤖

I spent my adolescence in Dreamweaver, my student years in Vim and my adult life in PyCharm.

  • Location

    Madrid

  • Education

    Telecommunications Engineer

  • Work

    CTO at WITH Madrid

  • Joined

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.

The difference between x++ and ++x (37)

Frank Puffer

Software developer, among other things

  • Location

    Europe

  • Joined

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.

The difference between x++ and ++x (39)

Andrew (he/him)

Got a Ph.D. looking for dark matter, but not finding any. Now I code full-time. Je parle un peu français.

  • Email

    aww@awwsmm.com

  • Location

    Ottawa, Canada

  • Education

    Ph.D. in [Astroparticle] Physics

  • Pronouns

    he / him

  • Work

    Senior Software Developer at Improving

  • Joined

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

The difference between x++ and ++x (41)

Basti Ortiz

Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.

  • Location

    Philippines

  • Education

    B.S. Computer Science @ University of the Philippines Diliman

  • Pronouns

    he/him

  • Joined

• Edited on • 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.

The difference between x++ and ++x (43)

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.

The difference between x++ and ++x (45)

Jason C. McDonald

Author of "Dead Simple Python" (No Starch Press). Speaker. Time Lord.

  • Email

    codemouse92@outlook.com

  • Location

    Time Vortex

  • Pronouns

    he/him

  • Work

    Director of Community at OWASP Foundation

  • Joined

• Edited on • 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 circ*mstances. As pythonic as the saying may be, "explicit is better than implicit" is true as a generally universal rule, especially wherever performance is concerned.

The difference between x++ and ++x (47)

Lisa Benmore

  • Location

    Los Angeles, CA, USA

  • Education

    Bachelor's of Science in Web Design and Interactive Media (2014)

  • Work

    Software Engineer (JS Team) at GumGum

  • Joined

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);

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 ;)

The difference between x++ and ++x (49)

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

The difference between x++ and ++x (51)

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

The difference between x++ and ++x (53)

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.

The difference between x++ and ++x (55)

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.

The difference between x++ and ++x (57)

emilyjuan58

I m web design and Developer

  • Location

    United State

  • Work

    React Knit Developer at Ourability

  • Joined

int main()
{
int x=5,y=15;
x= x++ + ++y;
y = ++x + ++y;
printf("%d %d",x,y);
return 0;
}
MardamsGreat blog very useful thanks

The difference between x++ and ++x (59)

Riyas Rawther

Learning the coding...

  • Location

    Ernakulam, Kerala, India

  • Work

    IT Infrastructure Consultant at Self-employed...

  • Joined

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} }}

The difference between x++ and ++x (61)

Riyas Rawther

Learning the coding...

  • Location

    Ernakulam, Kerala, India

  • Work

    IT Infrastructure Consultant at Self-employed...

  • Joined

//DARTvoid main() {int x;//Postfix (e.g a++)x =1; print (x++); // Prints the previous value. Output is 1print (x++); // Previous value is 1 and adds 1 to it. Output is 2print (x++); // Previous value is 2 and adds 1 to it. Output is 3//note: The first value will be the same. Then incements with 1 each time when it called.//PostFix// examplefor (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}}}

The difference between x++ and ++x (63)

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, Canlı TV İzle as it just makes having clean code that much easier.

The difference between x++ and ++x (65)

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

The difference between x++ and ++x (67)

I love programming but it is a very hard thing, I have tried learning php online every thing was going well till i meet functions and loop.
I wonder how people write a full code for a website like 9jaHob 9jaHob

The difference between x++ and ++x (69)

IsaacLeimgruber

I'm a very straightforward data science student in last year before master graduation. I like to learn bottom-up step by step and go through the logical discovery process myself as much as possible

  • Joined

What was the other post with the psychopath reviewing your code :)

The difference between x++ and ++x (71)

Basti Ortiz

Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.

  • Location

    Philippines

  • Education

    B.S. Computer Science @ University of the Philippines Diliman

  • Pronouns

    he/him

  • Joined

I'm sorry, but I don't quite get what you mean. Can you help me out here?

The difference between x++ and ++x (73)

IsaacLeimgruber

I'm a very straightforward data science student in last year before master graduation. I like to learn bottom-up step by step and go through the logical discovery process myself as much as possible

  • Joined

If you find yourself in a situation where it matters whether you write x++ or ++x then maybe you should first consider writing more readable code instead of compact one

The difference between x++ and ++x (75)

Basti Ortiz

Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.

  • Location

    Philippines

  • Education

    B.S. Computer Science @ University of the Philippines Diliman

  • Pronouns

    he/him

  • Joined

Ah, now I catch your drift. You're definitely not wrong in that regard. 🙂

Also, this post has anything to do with my previous one. Just wanted to share some information on an overlooked feature of the language. That's why I said, "If we want to go crazier," at some point in the article. Compacting the code in a single arrow function is just for those who are crazy and confident enough to do it (like me). I'm a pretty crazy person now that I think about it. I should chill myself out.

Meh, I'm still going to write more articles in the future that introduce crazy syntax and shortcuts when I feel like it. Who knows? Perhaps a maintainer of a minification algorithm would see my articles and improve his/her algorithm just a slight bit more. Every bit counts when you're minifying...

The difference between x++ and ++x (77)

IsaacLeimgruber

I'm a very straightforward data science student in last year before master graduation. I like to learn bottom-up step by step and go through the logical discovery process myself as much as possible

  • Joined

Yeah I mean some optimisation are good and some are detrimental to understanding. However I think arrow functions is the first kind :)

The difference between x++ and ++x (79)

Basti Ortiz

Web developer. Open-source contributor. Learner. Writer. Mentor. Leader.

  • Location

    Philippines

  • Education

    B.S. Computer Science @ University of the Philippines Diliman

  • Pronouns

    he/him

  • Joined

Right you are, my friend! 😉 One has to crawl before they could walk. In this case, one has to type function() {} before they could type () => {}.

The difference between x++ and ++x (81)

webdva

I'm a kind individual who's passionate about engineering and committed to building a future of prosperity. Let's work together and do our best!

  • Email

    webnodva@gmail.com

  • Joined

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

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

For further actions, you may consider blocking this person and/or reporting abuse

The difference between x++ and ++x (2024)
Top Articles
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 6423

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.