8

A few coworkers and I have come across some more strange JavaScript syntax. We are having trouble explaining the following behaviour (I am using the Chrome console):

> {}[1]

Yields

[1]

Essentially, it is valid syntax to include any object (not just empty) before the array, and the result is always just the array. Is there any explanation for this? Any case where this doesn't behave this way?

Also, this question is sort of hard to search for, since it consists of characters that don't play well with search engines. Please let me know if this is a duplicate question.

5
  • 3
    Because {} is a block with nothing in it.... Commented Oct 31, 2016 at 19:48
  • Can you give an example with a non-empty object before the array? Commented Oct 31, 2016 at 19:50
  • { a: 'b' }[1] yields [1] Commented Oct 31, 2016 at 19:54
  • @JamieCounsell that's a block that contains a labelled statement (a is the label, 'b' is a String literal expression statement). AST explorer. Commented Oct 31, 2016 at 20:07
  • Thanks! I've never seen that explorer before. Will definitely refer to that going forward. Commented Nov 1, 2016 at 3:18

2 Answers 2

7

{} is an empty code block statement. It's followed by an Array literal [1], which is the value that your program {}[1] evaluates to.

it's pretty much equivalent to:

if (true) {
  // empty block!
}
[1];

If you wanted to get the value with key 1 in an empty object literal, use parentheses:

({})[1] // undefined

You can use AST Explorer to see the JavaScript parser's view of your code.

Sign up to request clarification or add additional context in comments.

Comments

4

A block statement (or compound statement in other languages) is used to group zero or more statements. The block is delimited by a pair of curly brackets.

{} <-- block statement
[1] <-- array

so basically typed > [1]

3 Comments

Ahh, that makes sense! Thanks!
The chrome console not always evaluate it as it were a statement though, if you introduce { } alone it will evaluate it as an expression of an object literal.
@MinusFour the console implicitly wraps your input in parentheses. { }: block, ({ }): object literal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.