Get my new tutorials in your inbox every week

Secret behind JavaScript pre post increment

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.

javascript pre post increment try in browser console

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.

Want similar tutorials to be delivered to your inbox directly? Subscribe to my email newsletter. I also send out free ebooks and tutorial pdfs regularly to my readers. I do not spam by the way and respect your privacy. Unsubscribe any time.

Write a Comment

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