In Javascript, you can have lonely code blocks, that is, code blocks without an if
, function
or something like that preceding them, placed arbitrarily in the code, like this:
var a = 3,
b = 4;
{
a = 50;
b = 50;
}
alert(a + b); //alerts 100
I know some other languages have this (I think C++ does), and they use it for scope control: variables declared inside the lonely code block cannot be accessed outside of it. But since Javascript has function scope rather than block scope, you have to use a self-executing function (function(){})()
to acheive the same effect.
Is there a purpose for this construct? Have you ever seen anybody use it? Does the spec mention it? Is this just a side effect of the grammar having some sort of general rule about code blocks?
As I found out after googling my answer for How are labels used with statements that are not a loop? , the lonely code blocks can be related to labels:
myLabel:
{
for(x in y) {
break myLabel;
}
}
Will break out not only of the loop, but of the outer code block as well.
Update (as this question shows up high on Google for "javascript code block"):
With the introduciton of the let
keyword in ECMAScript 6, code blocks can also be used to limit scope of variables.
{
let x = 20;
alert(x) // 20
}
alert(x) // undefined
Only code readability, nothing more.
They do not even give you the advantage of closures:
var c = 'fail';
{
var c = 123;
}
alert(c); //alerts 123
( see it live )
Only readability. Other than that, nothing. Do not do this as it's not future-proof. The following will happily break:
"use strict";
var a = 3,
b = 4;
{
a = 50;
b = 50;
}
alert(a + b); //alerts 100
I used to use it myself as it allowed logical separation of functionality, but no longer do due to the above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.