Friday, September 18, 2015

Block Scoping - New in Node 4.0.0

Today wraps up "games week" on I had the frogs playing the lottery on Monday, Let's Make a Deal on Wednesday, and poker today. Since there's not much to discuss concerning poker being a game of skill or a game of chance, I'm back to discussing new JavaScript language features available in the recently released Node 4.0.0. (they've actually released 4.1.0 already but it's mostly just bug fixes).

So let's talk about Block Scoping!

This new ES6 feature gives you a new option for limiting the scope of declared variables to a block, statement, or expression. Just declare a variable with let instead of var and it won't be accessible to the entire function!

Here's an example that illustrates the point.

var x = 37;
if (x > 30) {
    let x = -1;
    let y = 900;
    console.log(x); // prints -1
    console.log(y); // prints 900
console.log(x); // prints 37
console.log(y); // prints undefined

if (x > 10) {
    var x = 5;
    var y = 777;
    console.log(x); // prints 5
    console.log(y); // prints 777
console.log(x); // prints 5
console.log(y); // prints 777

Inside the first if block, let x = -1 declares a block scoped variable x which is distinct from the global x variable declared on the first line. Changing it inside the block has no effect outside the block. By contrast, the second if block declares var x = 5, which isn't really much of a declaration at all. The x variable already in scope simply has its value reassigned. Once outside the block, it still has the value give it inside the block.

Also note the behavior of the y variable. Declared using let inside the first if block, it is undefined when used outside. But declaring it using var inside the second if block makes it global.

Declaring variables with let also works in for loops.

var i = 50;
for (let i = 0; i < 5; i++) {
    console.log(i); // prints 0 through 4
console.log(i); // prints 50

for (var j = 0; j < 5; j++) {
    console.log(j); // prints 0 through 4
console.log(j); // prints 5

The first loop, using let, prints the value of the variable i which is scoped to just the for loop. Outside of the loop, i still refers to the global variable. The second loop declares j with var and so j becomes available outside of the loop.

Making good use of let for variable declaration can make your code cleaner and lead to fewer bugs.

One final thing to note, however. While block scoping is available in Node 4.0.0+ it only works in strict mode. That means either launch node with the --use_strict flag or put
"use strict";
at the top of your source file. But you're probably using strict mode already, right?

Good. Now enjoy today's comic. comic for 18 September 2015