5

Can anyone explain why these operations yield these results:

(I understand the first one is somehow related to strings being based on arrays but what does 'based on' mean here, how does it work internally)

[] + [] = ""

[] - []= 0

[] + {} = "[object Object]"

[] - {} = NaN

{} + {} = NaN

{} - {} = NaN

{} + 1 = 1
  • The accepted answer to [Why is ++\[\[\]\]\[+\[\]\]+\[+\[\]\] = "10"?](http://stackoverflow.com/questions/7202157/why-is-10) explains this really well. – Robbie Wxyz Feb 21 '15 at 00:03

1 Answers1

6

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
Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28
  • `- {}` results in `NaN` not `undefined`. – Ram Feb 20 '15 at 23:51
  • You are right, the `{}` is undefined so it is the same as writing `- undefined` which is `NaN` – Jonathan Crowe Feb 20 '15 at 23:55
  • But how can an object be `undefined`? `Number({})` also returns `NaN`. – Ram Feb 21 '15 at 00:01
  • javascript has some weirdness when you create objects without storing them into a value. For instance, try this in your console: `{}` and `{foo: "bar", baz: "qux"}`. The first one will output "undefined" the second will throw an error unless you store it to a variable. When the javascript engine encounters an object literal on the left side of an expression it ignores it as an empty code block – Jonathan Crowe Feb 21 '15 at 00:09