bazzlebrush
bazzlebrush

Reputation: 428

original variable value changes after calculation it's involved in

I don't get why this happens;

var var1 = 200;
var var2 = var1 += 50;
console.log(var1);

When I query var1 I get 250. Shouldn't I get the value of that variable? or is my logic wrong.

https://jsfiddle.net/bazzball/pf3eLeoo/

Upvotes: 0

Views: 67

Answers (3)

pfmaggi
pfmaggi

Reputation: 6496

Your code add 50 to var1, storing the result in var1. then it assign to var2, var1 value.

If you want to add 50 to var1 and store the result in var2, you need to do it with something like:

var var1 = 200;
var var2 = var1 + 50;
console.log(var1);

Upvotes: 1

Syd Lambert
Syd Lambert

Reputation: 1495

You used the += operator, this will change the value of your var1.

To eliminate this problem, use a singe +.

Example:

var1=200;
var2=var1+50;
console.log(var1);

//returns 200

Upvotes: 0

tymeJV
tymeJV

Reputation: 104785

+= is an assignment operator, so what you're actually saying is:

var var1 = 200;
var1 += 50; //200 + 50 and assign back to var1
var var2 = var1; //var2 is the value of var1 = 250

If you want var1 to stay at 200 - simply add 50 to it:

var var2 = var1 + 50;

What var var2 = var1 += 50; comes out to:

var var2 = var1 = var1 + 50;

Upvotes: 0

Related Questions