When using the +
operator javascript will attempt to convert the elements being added together first into a string, then into an int. When you cast an empty array to a string you get ""
therefore "" + "" = ""
[] + [] = "" // equates to "" + "" = ""
When using the -
operator javascript will attempt to convert the element into integers. Empty arrays cast into integers will product 0
so 0 - 0 = 0
[] - []= 0 // equates to 0 - 0 = 0
Same thing here, the empty array is being converted to ""
and the object is being converted to "[object Object]"
because of the concatenation with the empty string the result is "" + "[object Object]" = "[object Object]"
[] + {} = "[object Object]" // equates to "" + "[object Object]" = "[object Object]"
{}
cannot be cast to an int so is instead cast to undefined
and 0 - undefined = NaN
[] - {} = NaN // equates to 0 - undefined = NaN
When an expressions starts with an empty object literal javaScript interprets the first {} as an empty code block and ignores it so evaluates the following expressions as + {}
which is NaN
{} + {} = NaN // equates to + {} = NaN
{} - {} = NaN // equates to - {} = NaN
{} + 1 = 1 // equates to + 1 = 1