I'm testin some JavaScript concepts and I'm trying to understand why:
typeof({} + {})
typeof([] + [])
return a 'string' yet:
typeof {}
typeof []
return an 'object'
I've tried this in NodeJS, FireFox, Chrome and IE9 all with the same results.
The + operator is defined to either concatenate strings or add numbers. If you try something else, the operands have to be converted to strings or numbers first. It looks like string is preferred here.
You can control what string or number is returned by defining functions .toString and .valueOf on the objects respectively
The + operator attempts to coerce the operands to a common type. In this case, the type is string, since adding objects or arrays does not make any sense.
From the + operator documentation:
If Type(lprim) is String or Type(rprim) is String, then Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
Since the default value of an object is a string (an empty string, in the case of an empty object), the return value of the operation is '' + '' => ''.
See the ECMAScript documentation for the + operator, ToPrimitive, and an object's DefaultValue if you care about the internals.
+operator, as is easily confirmed by reading the language spec.{} + {}givesNaNandtypeof(NaN)give"number"{} + {}is not the same as({} + {}). The first{}is treated as an empty block, so it is equivalent to+{}. With unary+, the operand is always converted to a number.