Why is this crazy javascript not causing a syntax error?

Today I played with some Javascript snippets and noticed that this code actually runs:

{{for(var i = 0; i < 3; i++) {{{{ alert(i); }}}}}} 

You can try it yourself for jsFiddle .

Why is this done without any syntax errors? What do duplicate brackets mean? Javascript just ignoring duplicate curly braces?

+4
source share
3 answers

{ x++; } { x++; } is a Block Statement .

{{{ x++; }}} {{{ x++; }}} is a block inside a block inside a block.

Code is executed inside each block. Therefore, adding extra {} around someting does nothing.

+6
source

It creates a new block, which is actually useless 1 since JavaScript does not have a block 2 area .

1 This is a beautiful oxymoron.
2 nonetheless

+12
source

Brackets in brackets are just delimited blocks of code. Your sample can expand to:

 { { for(var i = 0; i < 3; i++) { { { { alert(i); } } } } } } 

which is stupid but subtle

+3
source

All Articles