Reputation: 503
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
?
Upvotes: 9
Views: 20331
Reputation: 68933
JavaScript performs string concatenation when find +
. So the first "2" and second "2" makes "22".
But when performing subtraction (-
) on strings, coercion happens. So the resulted "22" coerced to number 22
and final "2" coerced to number 2
. Finally subtracts 2
from 22
to result 20
.
For More: Coercion
Step by step evaluation:
'2' + '2' - '2'
To
'22' - '2'
To
22 - 2
To 20
Upvotes: 2
Reputation: 198324
+
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.
Upvotes: 36
Reputation: 12139
The mechanism at play in JavaScript is called coercion
.
The +
sign in JavaScript can either perform string concatenation, or arithmetic addition. So how does JavaScript choose which action to perform?
In case both arguments (on either side of the +) are strings, JavaScript performs a concatenation.
console.log(2 + 2); // 4
console.log('2' + '2'); // '22'
The minus sign however has only one meaning: the arithmetic subtraction.
So JavaScript has only one way to interpret '22' - 2
which is to subtract 2 from '22'. But of course '22' is not a number, so JavaScript first forces it ("coerces" it) into a number.
The real operation performed is 22 - 2
, which easily computes to 20
, the result you observe.
Upvotes: 2