JavaScript block scoping


I’m going through JavaScript: The Good Parts (which I highly, highly recommend), and I’m finding I knew next to nothing about JavaScript.  For example, this does not compile in C#:

public void TestScope()
{
    if (true) 
    {
        int i = 5;
    }

    i.ShouldEqual(5); // does not compile
}

This is because C# has block scope.  Any variable declared inside a block is scoped to that block, but not to any parent blocks.  JavaScript, however, does not have block scope:

var foo = function()
{
    if (true)
    {
        var a = 5;
    }
    
    alert(a);
}

foo();

That will display “5”.  Since there is no block scope, the book recommends declaring all variables at the top of the function.  JavaScript does have function scope (as well as closures), so this is the safer bet:

var foo = function()
{
    var a;
    
    if (true)
    {
        a = 5;
    }
    
    alert(a);
}

foo();

This includes any variables declared inside for loops and any other kind of block.  Declaring them at the top of the function will eliminate pesky scoping bugs, when you might accidentally revert back to C-style block scope rules.

Did I also mention you should pick up JavaScript: The Good Parts?  It turns out learning about the language may dispel ill feelings towards it.

A TDD investment addendum