4 ms·
How come {a:1}["a"] evaluates to ["a"] but ({a:1}["a"]) evaluates to 1?
by pvillano 2y ago
How come
{a:1}["a"] evaluates to ["a"]
but ({a:1}["a"]) evaluates to 1?
- langguage 2y agoThat’s not true. If it appears true it’s because you’re using a repl that treats the first part as a separate statement and returns the value of the second part as the most recent statement, but there’s literally nowhere you can encounter the behaviour you described in a JavaScript program
- johnfn 2y agoIt is true. If you paste it into TS on its own line, even inside a function, TS will flag 'a' as an unused label.
- langguage 2y agoThat’s not the claim that was made. That code can not be evaluated to produce that value by any rules of the language. It can only be evaluated to produce that result by a repl which is parsing it as statements and then evaluating the most recent statement, in a non-standard way, but in the language itself two consecutive statements do not have a defined evaluation, and in any context where it is being evaluated it would gramatically need to be parsed as a single expression instead. If that’s not correct you can provide a counter example
- DangitBobby 2y agoconsole.log(eval('{a:1}["a"]'))
- n2e 2y ago{ // start block statement a: // labeled statement [1] 1 // expression statement } // end block statement [ // start array literal “a” // string value ] // end array literal vs. ( // start expression statement { // start object literal a: // object literal key 1 // expression statement } // end object literal statement [ // begin subscript property access “a” // string (property key) ] // end subscript property access ) // end expression [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... versus Edit: fixed second example (it did not match the parent comment), changed some verbiage
- pvillano 2y agoVery helpful!
- deleted 2y ago[deleted]
- johnfn 2y agoI think this is because {a:1} is a cleverly disguised block statement with a label named 'a', followed by the expression 1. It looks bad, but it never comes up in practice because {a:1} is only parsed as a block if it's at the start of a line, which it never would be.
- pvillano 2y agoVery helpful!