admin管理员组

文章数量:1312727

The MDN article on JavaScript blocks gives this example:

var x = 1;
{
  var x = 2;
}
alert(x); // outputs 2

As you can see JavaScript doesn't have block scope. So are there any good use cases for standalone blocks in JavaScript?

By "standalone" I mean not paired with a control flow statement (if, for, while, etc.) or a function.

The MDN article on JavaScript blocks gives this example:

var x = 1;
{
  var x = 2;
}
alert(x); // outputs 2

As you can see JavaScript doesn't have block scope. So are there any good use cases for standalone blocks in JavaScript?

By "standalone" I mean not paired with a control flow statement (if, for, while, etc.) or a function.

Share Improve this question asked Jul 30, 2013 at 5:54 Web_DesignerWeb_Designer 74.7k93 gold badges209 silver badges266 bronze badges 3
  • 2 Taken from the same article: "Although 'standalone' blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java." I would take their word for it on this one if I were you. – BoltClock Commented Jul 30, 2013 at 5:57
  • @BoltClock I'm still curious if they have a use, whether it's a good one or not. – Web_Designer Commented Jul 30, 2013 at 5:58
  • @BoltClock While that's true, the OP seems to be looking for specific scenarios where people think "Well, I've found block statements are great for ______". I'm not sure there are any, but still :) – Ian Commented Jul 30, 2013 at 5:59
Add a ment  | 

2 Answers 2

Reset to default 8

ES2015 introduces block scoping with let and const, so standalone blocks bee useful for limiting the scope of variables:

{
  let privateValue = 'foo';
}

console.log(privateValue); // -> ReferenceError

In contrast to var:

{
  var privateValue = 'foo';
}

console.log(privateValue); // -> "foo"

let and const are implemented in the latest versions of all major browsers (including IE11).

  • let patibility table
  • const patibility table

Short answer: ...not really.

The only use I know for them is labels:

myBlock: {
    // stuff
    if (something) break myBlock // jump to end of block
    // more stuff
    if (somethingElse) continue myBlock // jump to beginning of block
    // blah blah blah, more stuff
}

(almost like a goto, better watch out for the raptors)

Needless to say, this is a very bad idea. So basically, nothing; just don't use them.

(side note: a do { /* stuff */ if (something) break; /* stuff */ } while (false) could do the same thing)

本文标签: Do standalone JavaScript blocks have any useStack Overflow