Difference between x++ and ++x | SrishCodes

Difference between x++ and ++x | SrishCodes

Hi everyone, welcome back to SrishCodes where I teach you interesting tech concepts that you should know about as a current or aspiring software developer. Today I will be sharing with you about the difference between prefix (++x) and postfix (x++).

This syntax is used across several languages like JavaScript and Java. In this article I will be focusing on the use of prefix and postfix in JavaScript.

Introduction

As we know, there are several ways to add 1 to any number in JS.

let someNum = 0;

// example 1
someNum = someNum + 1;

// example 2
someNum += 1;

// example 3
someNum++;

// example 4
++someNum;

Wait so what is the difference between example 3 and example 4 above? Both operators still do what it looks like: to increment the variable someNum by 1. The difference between the two lies in their return values.

Prefix vs Postfix

Prefix 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
let somePrefix = 1;
console.log(++somePrefix); // 2
console.log(somePrefix); // 2

// postfix
let somePostfix= 1;
console.log(somePostfix++); // 1
console.log(somePostfix); // 2

The reason I am writing this article is because I often get confused between the two despite using postfix very regularly over the last few years. The way I remember it now using the syntax.

In the case of prefix, ++somePrefix means to increment first then return the value of somePrefix. Whereas in the case of postfix, somePostfix++ means to return the value of somePostfix first then increment it after.

When do I use which one?

In my experience, postfix is the more commonly used syntax. But when do we use prefix?

// postfix
let displayValue = 0;

function getAddedValue() {
    addedValue++;
    displayValue = addedValue;
}

In such a case, prefix can help us reduce the function getAddedValue() to one line instead of two.

// prefix
let displayValue = 0;

function getAddedValue() {
    displayValue = ++addedValue;
}

And that was all for this now! I am attempting to post shorter articles more often so make sure to follow me and subscribe for the latest posts!