This seems quite obvious in its logic (a string can't subtract) but I would like to know how this decision is taken in the underlying execution of JavaScript. How exactly are coercion rules being applied here?
Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).
Because == (and === ) test to see if two objects are the same object and not if they are identical objects.
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
console. log( 0 == '0'); javascript uses coerceing and converts both to number and compares . Now 0==0 so true is returned .
-
is defined in terms of ToNumber
, whereas +
has an extra clause for strings (emphasis mine):
11.6.1 The Addition operator (
+
)The addition operator either performs string concatenation or numeric addition.
The production
AdditiveExpression : AdditiveExpression + MultiplicativeExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingAdditiveExpression
.- Let
lval
beGetValue(lref)
.- Let
rref
be the result of evaluatingMultiplicativeExpression
.- Let
rval
beGetValue(rref)
.- Let
lprim
beToPrimitive(lval)
.- Let
rprim
beToPrimitive(rval)
.- If
Type(lprim)
isString
orType(rprim)
isString
, then
- Return the String that is the result of concatenating
ToString(lprim)
followed byToString(rprim)
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With