CalabiYau
CalabiYau

Reputation: 481

Why won't this increment and store the value?

If I want to increment a value and then store it in another variable, why is it not possible to do it on one line of code?

This works

var count = 0;
count++;
var printer = count;
alert(printer); //Prints 1

But this doesn't

var count = 0;
var printer = count++;
alert(printer); //Prints 0

Upvotes: 3

Views: 996

Answers (4)

Alfabravo
Alfabravo

Reputation: 7569

It can be done in one line.

//Example 1
var count = 0;
count++;
var printer = count;
alert(printer); //Prints 1

//Example 2
var count2 = 0;
var printer2 = count2++;
alert(printer2);   //Prints 0
printer2 = count2++;
alert(printer2);   //Prints 1

// Example 3, in one line
var count2 = 0;
var printer2 = count2 + 1;
alert(printer2);   //Prints 1

// Example 4, in one line
var count2 = 0;
var printer2 = ++count2;
alert(printer2);   //Prints 1

Upvotes: 1

Marc B
Marc B

Reputation: 360562

++ changes the results depending on where you use it:

 y = 0;
 x = y++; // post-increment

is equivalent to

 y = 0;
 x = y;
 y = y + 1;

and

 x = ++y; // pre-increment

is equivalent to

 y = 0;
 y = y + 1;
 x = y;

Upvotes: 0

user1106925
user1106925

Reputation:

You're using the post-incrementing operator. The increment happens after the assignment expression is complete.

Use the pre-incrementing version instead...

++count;

Or use the += operator...

count += 1;

Upvotes: 10

Jaime Torres
Jaime Torres

Reputation: 10515

You need to do

var count = 0;
var printer = ++count;
alert(printer); 

The JavaScript Arithmetic Operators section of the w3schools page has a decent breakdown with a Try Me lab. In short, if you do the increment/decrement operation before the variable, it will occur before it is used in the current operation. If you include it afterwards, it will occur after the current operation.

Upvotes: 5

Related Questions