Lanston
Lanston

Reputation: 11844

why {key:value}["key"] doesn't work?

1:{key:value}["key"]
2:({key:value})["key"]
I'm wondering how the JS interpreter works on the above codes, and why 1 doesn't work and why 2 works?

Upvotes: 4

Views: 362

Answers (1)

Ray Toal
Ray Toal

Reputation: 88378

I assume you are asking the question because you saw this effect in a JavaScript REPL (shell). You are using a JavaScript shell which assumes the leading "{" begins a block statement instead of an object literal.

For example, if you use the JavaScript interpreter that comes with the Chrome browser, you see the following:

> {key:"value"}["key"]
["key"]

Here, Chrome saw what you entered as a block statement, followed by the expression that was an array of one element, the string "key". So it responded with the result of that expression, namely the array ["key"]

But not all shells work this way. If you use the interpreter with node.js, then #1 will work for you!

$ node
> {key:"value"}["key"]
'value'
> 

In interpreters like Chrome, you have to use parentheses to tell it that you want the first part to be an object literal. (This technique, by the way, is guaranteed to work in all shells, including node's).

EDIT

As pointed out in one of the comments, if you use that construct in an expression context anywhere in an actual script, it will produce "value". It's the use in the shell that looks confusing.

This fact was actually exploited in the famous WAT video by Gary Bernhardt.

Upvotes: 4

Related Questions