When the statement console.log(1 + + " " + 3);
is executed in the Chrome console, the result is 4
and not "1 3"
as i would expect.
Can someone please explain why this is the case?
When the statement console.log(1 + + " " + 3);
is executed in the Chrome console, the result is 4
and not "1 3"
as i would expect.
Can someone please explain why this is the case?
The following operations are done when the statement is evaluated:
1 // one
+ // add
+ " " // implicitly convert " " to a number (0)
+ // add
3 // three
So basically 1 + 0 + 3
. There’s no string that enters this calculation. It’s converted to a number beforehand.
The +
operator in this case is the unary +
(see “coercion”).
This behaviour is called coercion.
In this case the unary plus operator
+
converts to number the expression at the right. If it cannot parse a particular value, it will evaluate to NaN.You can see some coercion examples in this Gist: JavaScript Coercion