Hacker News new | past | comments | ask | show | jobs | submit login

Huh that’s quite interesting. It behaves this way even when you explicitly make it an object literal rather than a block.

I guess JS’s parser explicitly prohibits adding things to a curly-brace enclosed entity?

I’m normally quite defensive of JS, but I’ll have to admit I don’t like that.




How did you explicitly make it into an object literal?

    ({}) + []
    -> "[object Object]"
will correctly make it "[object Object]"

Did you try to do this?

    {a: 1} + []
    -> 0
That's interpreted as the statement 1 labeled a, not as an object. This makes it obvious it's not an object:

    {a: 1, b: 2} + []
    -> Uncaught SyntaxError: Unexpected token ':'
JavaScript supports labels so you can continue/break multiple levels at once:

    {
      a: while (true)
        while (true)
          break a;
    }


Yes, I realized after the fact that I was indeed making a label. I’m now back to not having an issue with JS


It's just ASI (automatic semicolon insertion) and at the top-level {} declares a block not an object.

You can also do like ({} + []) and it will actually be "adding" them; the confusion solely comes from people typing into the JS console something that wouldn't make any sense to put into an actual script.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: