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.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in JavaScript. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://paulbatum.blogspot.com Paul Batum

    Jimmy you just cost me £114.66!!

    The problem with Amazon is you never manage to check out with just one book in your basket..

  • http://jimmybogard.lostechies.com Jimmy Bogard

    @Paul

    You’re welcome.

  • http://lazycoder.com Scott

    BLOCKED SCRIPT is even weirder than that. What do you think will be the value of myVar when you call the function?

    function t()
    {
    alert(myVar);
    var myVar = “scope”;
    alert(myVar);
    };

    The first alert shows “undefined”. The second alert shows “myVar”.

    Weird huh? No error when you try to access a variable that hasn’t been declared yet.

  • Sergio Pereira

    That book is nice indeed. It’s short and filled with valuable information. Great for anyone that does not remember why they hate “blocked script”

  • http://16randombytes.blogspot.com Bill Barry

    This is why you should always consider a good lint program:
    like http://www.jslint.com/