0

I was messing around the JavaScript console and noticed that

>> {}[1]
[1]

evaluates as an array. After some more messing around I found that

>> b = {}[1]
undefined

gives me the expected result of undefined. At first I thought the curly braces were being interpreted as a block, but attempting

>> {a:1}[1]
[1]

still gave me the the [1] array. I would expect that if it was interpreted as a block, it would result in a syntax error. Why is this the case?

More Info: I discovered from Don't understand why you should not use an object literal at the beginning of a statement, that it likely is a block, but this does not answer how this is not a syntax error unless it is doing a lookahead to determine if it's an object literal or a block, but it's not an object literal because it's still evaluating to [1].

EDIT: I tried this in Chrome and Firefox in their debugging consoles and Node.js's command line interface.

duckbrain
  • 1,219
  • 1
  • 13
  • 26
  • Javascript is weird... this is worth watching- [link] (https://www.destroyallsoftware.com/talks/wat) (javascript starts at 1:20) – mm8511 Aug 17 '17 at 18:00
  • I feel like you've answered your own question. It's interpreted as a block in this case. You could do `{}"hello"` and it would return `"hello"`. However, if you try to store this value in a variable, then you will get your errors thrown. – Christopher Messer Aug 17 '17 at 18:00

1 Answers1

3

I would expect that if it was interpreted as a block, it would result in a syntax error. Why is this the case?

Inside a block, an expression consisting of a label followed by a number literal is valid.

but this does not answer how this is not a syntax error unless it is doing a lookahead to determine if it's an object literal or a block

It doesn't need to look ahead. It is a block because of what is on the left hand side of the { (i.e. nothing).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335