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;
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
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);
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;
}
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)
);
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)
Nice explanation! However, I'm not happy with the last line of your last code example:
The occurrence of both
=>
and=
make the expression somehow difficult to read.One could use parentheses to emphasize the assignment:
Or maybe one could spend a new line:
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!
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/
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.
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.
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.
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.I tried this method on tv izle my platform and I was very successful. Thank you.
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:
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.
Undefined behaviour!?
In Java,
x = 1 + 3 + 3 = 7
What is undefined?
In Java they are also evaluated from left to right (unless you have a
x += 1
instead ofx++
) then it gets confusing.Thanks a lot!;)
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:
Here's an example on how to use in a for loop:
Pitfalls: none
When to use this method: well anytime you need to increment by one.
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.
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
At the moment you start digging into it and do some quick copy/pasta for debugging purposes:
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
++
:The produced ASM is the following
Now using the
+= 1
method: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.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++
infor
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):But it looks weird and will hopefully be noticed soon.
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. ReferenceSomeone should make a jsPerf for that. Although I doubt a significant performance difference, it is nonetheless interesting (and exciting) to see the results.
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.
One other critical difference in some languages, including C and C++:
++x
is one less compiled instruction thanx++
. 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.
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:
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
;)Le pays du Bosphore et plus particulièrement la ville d’Istanbul offrent les conditions parfaites pour une greffe de cheveux turquie
Thank you for sharing your knowledge with this informative post about one of the intricacies of JavaScript. Well-written explanation.luxury replica watches
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.
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.
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.