25

Possible Duplicate:
Difference between using var and not using var in JavaScript

Hi All

Declaringvar myVar; with var keyword or declaring myVar without it.

This might be a stupid question for some, but I'm in a learning process with javascript.

Sometime, when reading other people's code, I see that some variables are declared without the 'var' at the front. Just to emphasise, these variables are not even declared as parameters of a function.

So what's the difference between declaring a variable with or without the 'var' keyword?

Many Thanks

Community
  • 1
  • 1
Shaoz
  • 10,573
  • 26
  • 72
  • 100

2 Answers2

24

If you don't use it, it might be a global variable, or in IE's case, it'll just blow up.

There are cases you don't need it, for example if it's a parameter to the function you're in, it's already declared. Always use var in any other cases (other cases being: unless you're manipulating a variable that already exists). No matter what scope it needs to be defined at, explicitly define it there.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
15

It's all about scoping. Technically you can omit var but consider this:

myVar = "stuff";

function foo() {
    myVar = "junk"; //the original myVar outside the function has been changed
}

function bar() {
    var myVar = "things" //A new scoped myvar has been created internal to the function
}
Ollie Edwards
  • 14,042
  • 7
  • 28
  • 36
  • 4
    You can't "technically omit it", some browsers *allow it*, there's a difference. IE blows up when you do this, as it should. – Nick Craver Dec 08 '10 at 09:33
  • @Nick fair comment, I phrased that wrong – Ollie Edwards Dec 08 '10 at 09:35
  • Oh and by the way I wasn't suggesting that you EVER omit var, I was just saying you can get away with it. Using var makes your code easier to read and debug, get in the habit of using it. – Ollie Edwards Dec 08 '10 at 09:38