0

If two Objects added together equal NaN(not a number), which is technically of type number, then why does getting the type of two Objects added together result in "string"?

I will express this via the REPL:
> {} + {}
> NaN
ok. two objects added together creates NaN

> typeof(NaN)
> "number"
ok. we know that NaN's type is "number"

> typeof({} + {})
> "string"
wait. shouldn't this have been "number" also?

I'm aware that javascript has a less then desireable type system, but I'm confused as to what's happening here. Is the type being converted from number to string for some reason? Is number even a part of the type converting that goes on here? Or am I just using typeof wrong?

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • `{}+{} !== ({}+{})` [Unary_plus](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) – epascarello Aug 21 '14 at 00:59
  • The first braces form a block. Because JavaScript. See also this awesome talk featuring this very example: https://www.destroyallsoftware.com/talks/wat – Andreas Rossberg Aug 21 '14 at 17:49

1 Answers1

3

{} + {} is an empty block ({}) followed by a type conversion from object to number (+{}). It basically reads as

{} // empty block (a statement)
;  // empty statement (just for clarity)
+{}; // expression statement (unary plus, object literal -> conversion to number)

However if you use typeof ({} + {}), then {} + {} will be evaluated as expression in which case both {} can only be object literals and the + is the concatenation operator.

You can also just use the grouping operator to force the construct to be evaluated as expression:

({} + {}) // expression statement (string concatenation with two objects)

See also Why {} + {} is NaN only on the client side? Why not in Node.js? and other questions related to [javascript] "{} + {}".

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143