Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Strange Array Definition Syntax

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.

like image 410
Jamie Counsell Avatar asked Oct 31 '16 19:10

Jamie Counsell


2 Answers

{} 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.

like image 98
joews Avatar answered Oct 07 '22 00:10

joews


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]

like image 32
epascarello Avatar answered Oct 06 '22 23:10

epascarello