Categories
JavaScript Answers

What’s the Difference Between ++x and x++ in JavaScript?

Spread the love

In JavaScript, we can increment the value of a numeric variable in 2 ways.

We can put ++ before or after the variable.

They look similar but they’re different.

In this article, we’ll look at the differences between ++x and x++ in JavaScript.

The difference between ++x and x++ is the ++x increments the variable and returns the new value of x as the value.

For instance, if we write:

let x = 1  
console.log(++x)  
console.log(x)

Then we see that both console logs log 2.

On the other hand, x++ increments the variable but it doesn’t return the new value of x as the value.

For instance, if we have:

let x = 1  
console.log(x++)  
console.log(x)

Then we see that the first console log logs 1, and the 2nd console log logs 2.

Conclusion

Even though ++x and x++ looks similar, they’re different.

++x increments the variable and returns the new value of x as the value.

While x++ increments the variable but it doesn’t return the new value of x as the value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *