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?
use strict
and it won't work in future ES5 engines.