Skip to content

Instantly share code, notes, and snippets.

@jefflembeck
Created January 30, 2015 21:36
Show Gist options
  • Save jefflembeck/0829b09ff66357949598 to your computer and use it in GitHub Desktop.
Save jefflembeck/0829b09ff66357949598 to your computer and use it in GitHub Desktop.
i++ vs. ++i vs i += 1

JavaScript has a few different ways to increment a digit by one, and it's important to understand how each of them work.

Examples:

var i = 0;
var a = i++;

What does a equal here?

console.log( a );
0

What about i?

console.log( i );
1

Ok, weird, let's start over.

var i = 0;
var a = ++i;

What does a equal here?

console.log( a );
1

What about i?

console.log( i );
1

Now, last one:

var i = 0;
var a = i += 1;

What does a equal here?

console.log( a );
1

What about i?

console.log( i );
1

All that being said, i++ is the most common way to handle any kind of quick incrementing in JS or most other langs that have ++ in them. Watch out while debugging!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment