JavaScript curly braces without function or json
Just opened a client javascript file and the first lines go line by line:
{
var s_account="blog";
}
Which I won't get. Usually, in my experience, curly braces wrap around a function ...
function welcome(){ ...
... or json JavaScript object
var attributes = { this : "that...
Can anyone tell me why there are curly braces with no text before or after them? What does it do / what's the point?
source to share
Can anyone tell me why there are curly braces with no text before or after them? What does it do / what's the point?
There is no essential point for them in Javascript. It will act exactly the same as if the code were just
var s_account="blog";
speculation
In other block-scoped languages, this can limit the scope of the variable, but since JS doesn't have this feature (better or worse), curly braces without a structure or control function are essentially meaningless and ignored.
Most likely, this code was left from a deleted function or if statement. This is definitely not a template to be copied.
source to share
The only logical reason to do something like this, in my opinion, is organizational technique.
function banana(){
// private members
{
var foo = "foo",
bar = "bar",
baz = "baz";
function bux(){
console.log("bux");
}
}
// public members
this.fin = "fin";
this.fang = "fang";
this.foom = "foom";
this.shamalamadingdong = function(){
bux();
};
}
Also, most IDEs will let you collapse and get rid of this "individuals" block.
source to share
He named the statement block statement . It allows you to group expressions. It is commonly used with control structures such as if
and while
, but it can also be used on its own.
Since JavaScript has no block scope, the code works in the same scope (as if {}
it wasn't there).
Example:
{
var s_account="blog";
}
console.log(s_account);
This works great.
source to share