admin管理员组

文章数量:1355731

I was playing around with some Javascript snippets today and noticed that this code would actually run:

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

You can try it out for yourself on jsFiddle.

Why does this run without any syntax errors? What do the repeated brackets mean? Does Javascript just ignore repeated curly braces?

I was playing around with some Javascript snippets today and noticed that this code would actually run:

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

You can try it out for yourself on jsFiddle.

Why does this run without any syntax errors? What do the repeated brackets mean? Does Javascript just ignore repeated curly braces?

Share Improve this question asked Jun 28, 2012 at 20:18 Peter OlsonPeter Olson 143k49 gold badges208 silver badges249 bronze badges 8
  • 13 I get the error "too brackety." Do you think something's wrong with my interpreter? – Daniel Commented Jun 28, 2012 at 20:20
  • @Daniel You should disable some of the strictness options on jsLint. – Peter Olson Commented Jun 28, 2012 at 20:21
  • Also, you might be interested in stackoverflow./q/8618270/707111. – Ry- Commented Jun 28, 2012 at 20:22
  • 2 I guess the point is "why plicate the spec?" - If someone wants to throw in tons of useless curly-braces, so be it. Otherwise, you're requiring the implementers of JavaScript interpreters to check for unnecessary levels of block scopes. Then IE would of course do it all weird and then nothing works right.. – Mike Christensen Commented Jun 28, 2012 at 20:28
  • 2 In what way is this "too localized"? Argh, people always want to close the best questions. – Ry- Commented Jun 30, 2012 at 3:15
 |  Show 3 more ments

3 Answers 3

Reset to default 12

It creates a new block, which is effectively useless1 because JavaScript doesn't have block scope2.

1 This is a beautiful oxymoron.
2 Yet.

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

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

The code inside each block is executed. So adding extra {} around someting doesn't do anythng.

Brackets-within-brackets is just delineated blocks of code. Your sample could expand out to:

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

which is silly, but fine

本文标签: Why doesn39t this crazy brackety Javascript cause a syntax errorStack Overflow