6

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

Hello,

I am a self learned developer. Always, i write javascripts without the var for variables. But some javascripts use var for variables.

Both worked well for me. I am bit confused by this.

Is Writing scripts with var a standard form or they used only within classes ?

Community
  • 1
  • 1
Aakash Chakravarthy
  • 10,523
  • 18
  • 61
  • 78
  • possible duplicate of [Difference between using var and not using var in JavaScript](http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript), [Javascript: is using ‘var’ to declare variables optional?](http://stackoverflow.com/questions/2485423/javascript-is-using-var-to-declare-variables-optional), [JavaScript variable scope question: to var, or not to var](http://stackoverflow.com/questions/1956296/javascript-variable-scope-question-to-var-or-not-to-var), found via SO search for `javascript var` ;) – Felix Kling Jun 20 '10 at 13:55
  • Thanks felix Kling ! moderators can close this post if needed ! – Aakash Chakravarthy Jun 20 '10 at 13:59

2 Answers2

11

var limits the scope of a variable to the function it is declared in, if you don't use var you create a global.

Globals tend to lead to code that is hard to maintain and suffers from race conditions.

Always use var unless you have a very good reason not to.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I wouldn't necessarily say that race conditions are the problem, since Javascript (Web Workers aside) execution is single-threaded. IMO, a better statement of the problem is namespace pollution and state stomping (accidentally overwriting data you need). – Matt Ball Jun 20 '10 at 16:51
1

If you don't use var, the variable will be global, not limited in the scope you're in (a problem for say another variable in the global space with the same name, you just over-wrote it, probably unintentionally).

Short version: always use var to be safe.

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