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.
{}
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With