12

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

var foo = 1;

foo = 1;

What is the difference between above two lines ?

Community
  • 1
  • 1
ace
  • 11,526
  • 39
  • 113
  • 193
  • 2
    Which JavaScript tutorial/book are you using? (This is a rather fundamental ... topic.) –  Nov 09 '11 at 01:57

3 Answers3

21

Basically, var declares a variable and you can also assign to it at the same time.

Without var, it's assigning to the variable. Assigning will either assign to an existing variable or create a global variable of that name then assign to it.

Outside of functions, that means there's no real difference (in principal) if the variable does not already exist. Both create the global variable foo in that case.

Within a function, there's a huge difference. The first creates a variable local to the function regardless of whether or not it exists elsewhere.

The second will create a global variable if it doesn't exist, or simply change the value if it does exist.

In order to keep code as modular as possible, you should always use var unless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions with var and declaring all locals with var.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • There is a difference outside a function too. You can do this obj.prop, you can't do var obj.prop! – Chintan Shah Sep 23 '15 at 12:02
  • @Chintan, that's likely more to do with the fact that `obj.prop` cannot actually be a new variable, rather it's a property of an existing `obj` variable. – paxdiablo Sep 24 '15 at 04:48
5

foo = 1 will put foo in the last scope where foo was defined, or the global scope. var foo = 1 will put the variable in the current scope (i.e. the current function).

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Updated language is much better :) –  Nov 09 '11 at 02:00
  • @pst: Okay, I was originall going to tell you that: "I edited some 3 seconds after I posted, sorry :)" but then I though you meant http://jsfiddle.net/minitech/sEkYt/ – Ry- Nov 09 '11 at 02:03
1

In first case foo will be available in the same scope where it is defined, i.e. it will be local variable. In second case foo is a global variable, located in global scope.

Pavel Podlipensky
  • 8,201
  • 5
  • 42
  • 53