What is the point of free standing blocks if there is no block scope? [closed]
-
04-07-2021 - |
Question
You are allowed to use free-standing blocks like this...
var something = 1;
{
var something = 2;
print("Inside: " + something);
}
print("Outside: " + something);
This is from: http://eloquentjavascript.net/chapter3.html#p3c7ae609
But what's the point of having blocks like that? What purpose does it serve?
Solution
In ES6 there'll be block scoped variables declared with let
, at which free-standing blocks won't be pointless any more.
OTHER TIPS
Free standing blocks don't usually add any value in a script, however they can be used for code organization, such as splitting out an equation:
One Line://long equations are hard to read
foo = bar * baz + fizz - buzz;
Block:
{
//this groups relevant information into a descrete section
foo = bar;
foo *= baz;
foo += fizz;
foo -= buzz;
}
Although, long equations that perform operations based on a standard set of inputs are usually broken out into their own function:
As Function:function qux(bar, baz, fizz, buzz) {
var ret;
ret = bar;
ret *= baz;
ret += fizz;
ret -= buzz;
return ret;
}
foo = qux(bar, baz, fizz, buzz);
Ooops, I kept reading, and here's my answer:
In fact, although blocks like this are allowed, they are utterly pointless.
You answered your own question. From the article linked in the OP:
In fact, although blocks like this are allowed, they are utterly pointless.