DEV Community

Discussion on: The difference between x++ and ++x

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