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!
Latest comments (50)
Thank you nice exaplanation
This is definitely useful information if you want to keep your contacts update and organized. Thank you! Mens Collection
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
nice
OMG this saved me a big time headache. No one ever explained this properly to me. Thanks mate
I tried this method on canlitvapk.com/ my platform and I was very successful. Thank you.
include
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
one more Example:
Please visit dartpad.dev/. The default sample code when you open the dart-pad is
Run the sample code.
Note the line # 3 - print('hello ${i + 1}'); The i + 1 is used because initial value is 0. Now think how to avoid that with our prefix increment ++x.
The output will be same.
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.
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!
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
;)OMG this saved me a big time headache. No one ever explained this properly to me. Thanks mate!
Thank you for sharing your knowledge with this informative post about one of the intricacies of JavaScript. Well-written explanation. zarif
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
Some comments may only be visible to logged-in visitors. Sign in to view all comments.