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!

Latest comments (50)

Collapse
 
abhinowkatore profile image
Abhinav Katore

Thank you nice exaplanation

Collapse
 
jackleren profile image
Lerenjack

This is definitely useful information if you want to keep your contacts update and organized. Thank you! Mens Collection

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
 
khafidprayoga profile image
Khafid Prayoga

nice

Collapse
 
paul202183 profile image
paul202183

OMG this saved me a big time headache. No one ever explained this properly to me. Thanks matebuy replica YSL handbags

Collapse
 
taraftariumapk profile image
Canlı Maç İzle Apk

I tried this method on canlitvapk.com/ my platform and I was very successful. Thank you.

Collapse
 
emilyjuan58 profile image
emilyjuan58

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

Collapse
 
riyasrawther profile image
Riyas Rawther

one more Example:

Please visit dartpad.dev/. The default sample code when you open the dart-pad is

void main() {
  for (int i = 0; i < 5; i++) {
    print('hello ${i + 1}');
  }
}

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.

void main() {
  for (int i = 0; i < 5;) {
    print('hello ${++i}');
  }
}

The output will be same.

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
 
riyasrawther profile image
Riyas Rawther
//DART
void main() {
int x;

//Postfix (e.g a++)
x =1; 
print (x++); // Prints the previous value. Output is 1
print (x++); // Previous value is 1 and adds 1 to it. Output is 2
print (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
// 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
 
hcanltv profile image
hcanlıtv az • Edited

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.

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!

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
 
tiffany profile image
tiff

OMG this saved me a big time headache. No one ever explained this properly to me. Thanks mate!

Collapse
 
zarifnet profile image
zarifnet

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

Collapse
 
netvilox profile image
Netvilox

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.