Is this your first visit? You may want to subscribe to the feed.

The importance of var in JavaScript

I would consider myself proficient at JavaScript. Not a rockstar, but I can hold my own. But I didn’t learn it out of a book; I picked it up slowly over several years. So occasionally I come across something that I probably would have learned in the first couple chapters of a decent JavaScript book.

Today, I experienced the importance of declaring variables with var.

For the unenlightened like myself, JavaScript basically has two scopes for variables: global and local. Variables assigned outside of a function are global, and variables assigned inside of a function, using the var keyword, are local (not rocket surgery). However, if you leave the var keyword off, it assigns a global variable, regardless of where it’s declared.

Here’s a bit of code that demonstrates this:

function fail() {
  date = new Date();
  console.log('Before: ' + Number(date));
  setTimeout(function() {
    console.log('After: ' + Number(date));
  }, 1000);
}

fail();
fail();

The code defines a function that sets a variable, logs the variable, then defines a callback that logs the variable again on second later. If you call the function twice in a row, you can see the effect:

Before: 1220487263486
Before: 1220487263499
After: 1220487263499 <- This should be 1220487263486
After: 1220487263499

Declaring the date variable with var gives us this output:

Before: 1220487287985
Before: 1220487287994
After: 1220487287985 <- see, this is the same as the first line
After: 1220487287994

So remember kids, declare local variables with var!

Code: javascript Sep 03, 2008 ● updated Oct 14, 2008 4 comments

4 comments

  1. I knew I had to use var, but I’d long since forgotten why. Thx.

    Dr Nic Dr Nic September 04, 2008 at 12:19 AM
  2. Great minds think alike :)

    Paul Barry Paul Barry September 04, 2008 at 01:06 AM
  3. Heh, you kids and your crazy ignorance.

    var var September 04, 2008 at 02:13 PM
  4. I think that in IE6 you have to use var, despite there is js error.

    Infakta Infakta October 14, 2008 at 05:01 AM

Speak your mind:

*

*


* I hate spam and will never sell or publish your email address.

(You may use textile in your comments.)

Subscribe

Browse by Tag