A wild coercion appears
Now that you understand which rules govern conversion, let’s look a bit at
where these rules are applied.
< and >
These two operators only make sense for numbers, and convert their arguments to
numbers:
3 < "4" //=> 3 < Number("4")
//=> 3 < 4
//=> true
null < 1 //=> Number(null) < 1
//=> 0 < 1
//=> true
-1 < null //=> -1 < Number(null)
//=> -1 < 0
//=> true
With that example, we have explained 2/3 of our first code example.
Note that this can get quite tricky with objects:
var clown = {
age: 32,
valueOf() {
return this.age
}
};
clown < 33 //=> ToPrimitive(clown) < 33
//=> 32 < 33
//=> true
Or with toString
:
var clown = {
toString() {
return "56";
}
};
clown < 57 //=> ToPrimitive(clown) < 57
//=> Number("56") < 57
//=> 56 < 57
//=> true
+
The +
operator in JavaScript is a bit more unpredictable than in other
languages. Like in other languages, it either performs string concatenation or
addition, but unlike other languages, it often mixes these two in the same
expression.
If you have a string or an object on either side, you get concatenation —
otherwise, you get addition. For concatenation, both arguments are converted to
strings; for addition, both are converted to numbers. If you have multiple plus
signs in the same expression, you apply this rule one plus at a time.
Some examples with numbers:
2 + 3 //=> 5
2 + true //=> 2 + Number(true)
//=> 2 + 1
//=> 3
true + 4 //=> Number(true) + 4
//=> 1 + 4
//=> 5
Because you only get concatenation when you have an object involved, you can get
an unexpected result if you try to add a number to an object that can perfectly
well be converted to a number:
var then = new Date(2019, 0, 1);
then + 1000 //=> "Tue Jan 01 2019 00:00:00 GMT+0100 (CET)1000"
What happened? Well, since one argument was an object, string concatenation
applies, and thus we get:
then.toString() + String(1000)
"Tue Jan 01 2019 00:00:00 GMT+0100 (CET)" + "1000"
If you have a longer expression, you only evaluate one plus at a time:
2 + 3 + true + []
//=> 5 + true + []
//=> 5 + Number(true) + []
//=> 6 + []
//=> String(6) + String([])
//=> "6" + ""
An array has a toString
that works like .join(",")
:
2 + [1, 2, 3] + true
//=> String(2) + String([1, 2, 3]) + true
//=> "2" + "1,2,3" + true
//=> "21,2,3" + String(true)
//=> "21,2,3true"