Arijit Shome Arijit Shome - 1 day ago 4
Javascript Question

Clarification required in Javascript coercion example

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.

Answer

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.

Comments