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
.
ES2015 introduces block scoping with let
and const
, so standalone blocks become 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
compatibility tableconst
compatibility tableThe 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With