Achieving Block Scope With Immediate Functions In JavaScript

I was digging around on twitter and I found a great comment from @BenAtExocortex:

“Javascript has no block scope (!) but one can use self-executing functions instead (as Javascript has function scope.)”

What Ben is referring to is that JavaScript doesn’t scope your variables to if statements or other blocks the way C# and other languages would. Consider this example in C#:

On the “i++” line, the C# compiler (or Resharper / Telerik JustCode / etc) would throw a compiler error or warning, telling you that the variable isn’t defined at this point. This happens because the variable declaration is scoped to the if statement.

In JavaScript, though, the same code is perfectly fine:

This is because JavaScript scopes your variables to functions and not to if-blocks. But, we can achieve block-like scope through the use of immediate functions like this:

The “i” var in the “doSomething” function is assigned the value returned by the immediate function. The “x” var is scoped to the immediate function giving us block-like scope for our variables.

Of course, this does add a bit of noise to our JavaScript. Chances are if you need something like this you’ll really want to extract a proper function. There’s also some memory and performance implications due to re-defining and executing the immediate function every time you run “doSomething”. But, if you understand the implications and you need to achieve block-like scope in your JavaScript to isolate temporary variables, this is one way to do it.

Is JavaScript’s “Global” Scope Really Just A Closure?