Roman Shumskiy
Roman Shumskiy

Reputation: 33

Why js ignores '{}' in statements like '{}[0]'?

Can anybody explain why and describe how JavaScript converts statements like

{}[0]   => [0]
{}.2    => 0.2
{}'foo' => 'foo'

Upvotes: 0

Views: 41

Answers (2)

James Donnelly
James Donnelly

Reputation: 128836

The {} in your code is simply creating an empty Object, but doing nothing with it. The part directly after it is treated as a separate statement.

For instance:

{}var foo = 1;

This will create a foo variable with the value 1 assigned to it. The {} is parsed and an empty Object is created, but nothing happens with it as we aren't doing anything with it. The {} may as well be on a different line altogether:

{}
var foo = 1;

So in the three examples you've provided:

{}    => Object {}      // Creates empty object but does nothing with it.
[0]   => [0]            // As expected.
{}    => Object {}      // Creates empty object but does nothing with it.
.2    => 0.2            // As expected.
{}    => Object {}      // Creates empty object but does nothing with it.
'foo' => 'foo'          // As expected.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59292

Well, in your case {} isn't an object literal, but just empty blocks. You can use code blocks anywhere to improve readability. Also, such blocks can be useful when working with labels.

label: {
  // some code
}

Remember the curly braces after if condition? They're code blocks too.

Upvotes: 3

Related Questions