3 ms·
> In JavaScript, {} + [] evaluates to integer 0. This not really true. Put this js console and you'll see that a is the string "[object Object]": a = {}+[]
by esrauch 6y ago
> In JavaScript, {} + [] evaluates to integer 0.
This not really true. Put this js console and you'll see that a is the string "[object Object]":
a = {}+[]
When you put just {}+[] in your console its doing an empty block followed by unary-plus,like:
{/*do nothing block*/}; +[]
- jakear 6y agoHuh 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.
- esrauch 6y agoIt'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.
- Zarel 6y agoHow 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; }
- jakear 6y agoYes, I realized after the fact that I was indeed making a label. I’m now back to not having an issue with JS
- Non24Throw 6y agoYou’re right! I would never have guessed that. Learn something new every day.