Back to the Basics: Javascript var keyword

Recently I’ve been pouring over some legacy code that also happens to have a ton of crappy, yet slightly masked, javascript errors. This has prompted me to consider that sometimes it’s a good idea to go back over some of the very basics. To start, let’s look at some javascript samples:

for(i = 0; i < 100; i++){
   // unimportant code
}
function createErrorMessage(){
    message += "an error occured."
    alert(message);
}

Notice any errors here? ;)

Yep, you probably noticed the absence of the var keyword where each of the instance variables were used. "B...b..but... javascript is sloppy like that! It's a dynamic language which means I don't need to declare anything, right!? And even if not, those variables only exist within their scope." The problem here is, thanks to the absence of the var keyword causes those variables not to be locally scoped... in otherwords, if I use i somewhere outside of that for loop or method and don't bother initializing it, I'll get it's last value it had in the for loop. Likewise, if I decide to use the same variable name "message" anywhere else, it's possible that I already have something in it.

This can cause bug holes big enough to fly a jumbo jet through! A lot of developers hate javascript anyway and hack it together as quick as possible so they can get away from it, and it's not uncommon that they might find a variable to be initialized to something, have no idea why, but go ahead and use it with that value outside of it's expected scope. This also leads to code that is very difficult to maintain and exposes the whole problem of global scope in the first place, as you can't really be sure where those values might be coming from.

Remember... always use the var keyword for locally scoped variables and never make exceptions. Write your loops as

for(var i = 0; i < 100; i++){
   // unimportant code
}

and write your local variables as

function createErrorMessage(){
    var message = "an error occured."
    alert(message);
}

and you'll thank yourself for it in the end. ;)

You can leave a response, or trackback from your own site.

Facebook comments:

One Response to “Back to the Basics: Javascript var keyword”

  1. Ray Myers says:

    Amen brother. As Dan Friedman said, Scope is everything.

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!