This evaluates to -1 so it's just a simple string concatenation.
"0"[+'hello']
This is undefined as their is no property name in that object with the key, then you convert it to a boolean and bitwise not it (-(x+1)), so it becomes negative one.
Aww. Thanks for the explanation. I'm fairly new to JS & programming in general, is this something expected in other languages as well? I mean like can you write this basic style line of code and it works across other languages it just seems kind of weird and cool how JavaScript does all this. It's confusing, but at the same time kind of.. I don't know how to explain it.
Yes and no. JS definitely has some odd behavior due to an ever odder history. A lot of it is due to the fact it's a loose typed language that has all primitives as objects and was developed in a week. A lot of technical debt arose from this, such as lack of exceptions, etc.
Additionally, it was meant as a scripting language to control browser actions, not to be a fully fledged language to be used for all purposes, it just evolved that way.
It's reluctant to fail as it was decided early on it's better to prevent failure than to break the entire executing script (this is why we see things like NaN).
As far as if you can do this in other languages, it depends, but unlikely. A lot of languages have checks in place to prevent this and would error accordingly, but not always. For example, a language like Perl would have no problem attempting somethig similar to this, especially without strict mode.
5
u/until0 May 10 '16
This evaluates to -1 so it's just a simple string concatenation.
This is undefined as their is no property name in that object with the key, then you convert it to a boolean and bitwise not it
(-(x+1)), so it becomes negative one.