# The secret behind JavaScript increment operators

We often use the JavaScript pre and post increment operators in our code but seldom do we take time out to understand the basics of it. In this post I will cover the details about pre and post increment operators and why they work as they are supposed to be. Let’s get started.

### What are pre (++i) and post(i++) increment operators

These are mathematical operators that the JavaScript language provides. Using them you can do incremental operations. Both of them accept only one operand.

``````var t = i++;

for(var i=0; i < 3; i++) {
//some code here
}``````

### What is the best way to try them?

The simple way to understand is by trying it out in your browser console. Launch Google Chrome and open your dev tools. Then open the console tab and start writing some JavaScript. The inbuilt JavaScript runtime will execute your statements and give you results.

### Show me some code

Alright, let’s see some examples and understand them better

#### Post Increment (i++)

``````var i = 1;
var t = i++;

//What is the value of t and i?``````

So in the code snippet above, the expression i++, first returns the current value of i and then increments it. So t would receive the initial value of i which is 1. And i would become 2 thereafter.

``````console.log(t); //1
console.log(i); //2``````

This is what happens behind the scenes (interpreter level)

``````t = i;
i = i + 1;``````

#### Pre Increment (++i)

What happens here? You would have probably guessed it.

``````var i = 1;
var t = ++i;

//What is the value of t and i?``````

In this case, the expression ++i first increments the value of i and then returns the new value. So t would become 2 and i would also become 2

``````console.log(t); //2
console.log(i); //2``````

This is what happens behind the scenes (interpreter level)

``````i = i + 1;
t = i;``````

I hope now you have a clear understanding of how the increment operations work in JavaScript.

If you enjoyed this post and want similar articles to be delivered to your inbox directly, you can subscribe to my newsletters. I send out an email every two weeks with new articles, tips & tricks, news, free materials. No spamming, of course.