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
1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

- {} results in NaN not undefined.
You are right, the {} is undefined so it is the same as writing - undefined which is NaN
But how can an object be undefined? Number({}) also returns NaN.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.