23

When you notice that the sum of two empty arrays is an empty string in JavaScript

js> [ ]+[ ]
""

Comments
  • 8
    It's not a sum. It makes more sense if you think about what + actually does here. There's no implicit + operator for arrays, so it does a string concat.

    [1,2].toString() is "1,2"

    [].toString() is ""

    [1,2] + [3,4] is "1,23,4"

    what you want is [].concat()

    [1,2].concat([3,4]) is [1,2,3,4]

    There are a lot of gotchas in javascript, I'll definitely agree on that.
  • 3
    @Buggz I understand that toString() is called here.

    but how can you explain this

    js> [ ]+{}

    "[object Object]"

    js> {}+[ ]

    0
  • 3
    The first case is another string concat. For the second one I have no idea, for some reason you actually get a sum there.
  • 6
    This isn't really a problem. When would you ever write {} + [] anyway?
  • 0
    @olback Why I'm allowed to do it anyway ?
  • 2
    @undefinedUser because you'd be an idiot for doing so
  • 2
    @undefinedUser the {} is interpreted as an empty code block followed by +[] being interpreted. The + isn't seen as addition anymore but as prefix operator, converting the second object to a number. Number([].toString()) equals Number(""). Therefore, it's 0.

    As seen @ http://2ality.com/2012/01/...
  • 1
    @daintycode thanks! Always feels good to learn something!
  • 0
    Yet another js rant.

    JS is dynamically typed. We all know that that decision comes as the cost of having weird side effects like this.

    This is perfectly normal. None of these abnormalities affect day to day programming in any way whatsoever.

    If you don't want them, use typescript or any other static typed language. But don't blame js for being what it's supposed to be.

    Also he behavioral you mentioned is due to a phenomenon called type coercion. It's a bit hard to wrap one's head around but still predictable.
Add Comment