Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is '2'+'2'-'2'= 20 in JavaScript?

I was just randomly playing around JavaScript. The '2'+'2'-'2' input I given to it.

and the output is surprisingly 20.

console.log('2'+'2'-'2');

Now I am not getting it.

Does anyone explain is to me Why it is like this? How can be output of this equal to 20?

like image 275
Zayn Korai Avatar asked Feb 08 '18 01:02

Zayn Korai


1 Answers

+ is both concatenation and addition. If any of the arguments are not numeric, then it's concatenation. Thus, '2' + '2' is '22' - just like "foo" + "bar" are "foobar", and just like 3 + {} is "3[object Object]".

- is only subtraction. No matter what its arguments are, they are coerced to numbers. Thus, '22' - '2' is evaluated as 22 - 2, which is 20.

like image 76
Amadan Avatar answered Sep 16 '22 15:09

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!