user578895
user578895

Reputation:

Why is this JS Syntax valid (extra braces)?

So I just mistakenly typed something in a JS console and was surprised that it didn't give me a syntax error. My question: Why is this valid?

function foo(){
    {
        console.log('Valid Function');
    }
}
foo();

I would assume that it would interpret the inner { ... } to be an object literal, but if that were the case the console.log wouldn't be valid... so...?

Upvotes: 2

Views: 198

Answers (3)

Tamzin Blake
Tamzin Blake

Reputation: 2594

Braces specify a block of code. A block is a valid statement, and can appear wherever a statement is allowed. See http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf page 220.

Upvotes: 1

Chris Mountford
Chris Mountford

Reputation: 595

According to this javascript 2.0 grammar:

http://www.mozilla.org/js/language/js20-2000-07/formal/parser-grammar.rtf

An object literal is defined here:

ObjectLiteral { } | { FieldList }

Which means it must be empty or contain a valid field list which must have a bare colon to separate the key and value.

Your block is therefore interpreted as a "Statement" which can have the braces around it.

Lots of c syntax languages have arbitrary braces to group statements, but unlike most of them, JavaScript does not limit variable scope of those variables declared in that block. This means that the extra braces do not really have much purpose, are almost never used and this is probably why you didn't expect it to work!

Upvotes: 3

ninjagecko
ninjagecko

Reputation: 91094

This is an anonymous code block. For example:

{var x=5; alert(x);}

Furthermore to clarify your question "to be an object literal, but if that were the case the console.log wouldn't be valid... so...?"

It is NOT an object. However, note that if you had a key: or something it could be interpreted as an object and still work, since statements which don't return anything will be interpreted as undefined.

({1:console.log('test')})

result (also prints out 'test'):

Object
1: undefined
__proto__: Object

Upvotes: 3

Related Questions