The +
operator is not only used for adding numerical values, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string.
The first one is 1
, which is a numerical value. 1 + 2
returns the number 3.
However, the second one is a string "Lydia"
. "Lydia"
is a string and 2
is a number: 2
gets coerced into a string. "Lydia"
and "2"
get concatenated, which results in the string "Lydia2"
.
{ name: "Lydia" }
is an object. Neither a number nor an object is a string, so it stringifies both. Whenever we stringify a regular object, it becomes "[object Object]"
. "[object Object]"
concatenated with "2"
becomes "[object Object]2"
.