Reputation: 23
var a = 1+1+'2';
console.log(a);
> 22
var a = 1+1+'2'+7;
console.log(a);
> 227
var a = 1+1+'2'+7+10;
console.log(a);
> 22710
var a = 1+1+'2'+7+10-2;
console.log(a);
> 22708
where is the 0 coming from in 22708? coercion example.
Upvotes: 2
Views: 38
Reputation: 66
Javascript handles the subtract and minus signs differently. You get the zero because it is taking 22710
and subtracting 2 to get 22708
.
So it goes from 2
To 22
To 227
To 22710
To 22710 - 2
Which gives 22708
The actual reason as to why is way over my head though.
Upvotes: 0
Reputation: 198388
The hint is in the previous evaluation. 1+1+'2'+7+10-2
is equivalent to ((1+1)+'2'+7+10)-2
, or "22710"-2
. While +
is defined for both strings and numbers (it's addition when both arguments are numbers, concatenation in any other case), -
is only defined for numbers; and so "22710"
is coerced to number: 22710-2
is indeed 22708
.
Upvotes: 3