JavaScript Tidbit: Block Scope With “let”

JavaScript has functional scope. Meaning that if you (properly) define variables within functions, those variables remain accessible only inside the function.

Block scope, on the other hand, defines scope within a block of code, usually defined by braces. JavaScript now has block scope as of version 1.7, which means it’s available in these browsers:

  • Firefox 2+

Block scope is enabled in JavaScript with the use of “let”:

let(x=100) {
    alert(x);
};

It also works perfectly well on one line, without the use of braces:

let(x=100) alert(x);

Note that we can define global variables with the same name outside the block scope and the variables won’t interfere with each other:

x = 200;
let(x=100) alert(x);
alert(x);
// result: 100, 200

Note that there’s a slight caveat – not only is this not available in any version of IE, but it also requires a special script type declaration in order to work (at least for Firefox): type=”text/javascript;version=1.7″

References:
JavaScript Versions
Video: Best Practices in Javascript Library Design (John Resig)
New in JavaScript 1.7