Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
Buggz6157yIt'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. -
@Buggz I understand that toString() is called here.
but how can you explain this
js> [ ]+{}
"[object Object]"
js> {}+[ ]
0 -
Buggz6157yThe first case is another string concat. For the second one I have no idea, for some reason you actually get a sum there.
-
@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/... -
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.
Related Rants
When you notice that the sum of two empty arrays is an empty string in JavaScript
js> [ ]+[ ]
""
joke/meme
javascript
classic
absurdity
meme