1

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.

6
  • 3
    Your observations all have to do with the semantics of the + operator, as is easily confirmed by reading the language spec. Commented Nov 15, 2012 at 14:52
  • 1
    I'm guessing that because the addition of objects and arrays make no sense to the compiler/interpreter that it's doing a toString() on these objects before concatenating them. Is this right? Commented Nov 15, 2012 at 14:53
  • Yes - check out the link I just edited into my comment. Commented Nov 15, 2012 at 14:54
  • Interestingly, on the Chrome console, {} + {} gives NaN and typeof(NaN) give "number" Commented Nov 15, 2012 at 14:54
  • 1
    @Dancrumb {} + {} 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. Commented Nov 15, 2012 at 14:56

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can't concatenate or "add" arrays or objects using the + operator.

If you add two objects their string-representations are concatenated.

Comments

0

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.

Comments

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.