最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Do standalone JavaScript blocks have any use? - Stack Overflow

programmeradmin1浏览0评论

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)

发布评论

评论列表(0)

  1. 暂无评论