To var or not to var my javascript

This is probably trivial to a lot of people. I’ve done a bit of javascript work recently and in looking at reference material and code snippets around the internet, I noticed that the ‘var’ keyword to declare a variable seems to be optional in all cases. Even popular libraries, like Script.aculo.us, have revisions where ‘var’ appears where it wasn’t in the previous release.

In your own coding there’s two things to keep in mind about it.

  1. For global variables, it doesn’t matter, but you may want to use it for consistency.
  2. Always try to use ‘var’ to declare variables in local functions. It makes sure you’re using a local copy of the variable instead of another variable of the same name in a different scope.

For example, the two similar functions here have very different effects:

var myvar = 0;
function affectsGlobalVar(i){
   myvar = i;
}
function doesNotAffectGlobalVar(i){
   var myvar = i;
}

Commenting has expired for this post.