Sapphire_Brick
Sapphire_Brick

Reputation: 1672

Why does a variable with the unary operator ++ in JavaScript not change the variable by 1 until the next appearance of the variable inside brackets?

I know that in C, C++, Java, etc, there is a difference between foo++ and ++foo. In JavaScript, there is no ++foo, and JavaScript's foo++ usually behaves like C's ++foo:

var x = 10;
x++;
console.log(x); //11

But here:

var x = 0;
var w = "012345";
console.log(w[x++]); //0
console.log(w[x++]); //1

...It behaves like C's foo++?

Upvotes: 0

Views: 158

Answers (2)

Sapphire_Brick
Sapphire_Brick

Reputation: 1672

With the help of Jack Bashford, I think I understand it:

The reason I asked this question is because I misunderstood what "increment after using" meant; I thought it meant at the next statement, it really means immediately after the expression. I also got confused because JavaScript has a few conventions about when to use ++. In conclusion, C's ++ and JavaScript's ++ work the same way.

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44087

In JavaScript, there is no ++foo

That's wrong. There is a pre-increment operator, and it works like this:

var x = 0;
var w = "012345";
console.log(w[++x]); //1
console.log(w[++x]); //2

Upvotes: 3

Related Questions