Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to use "var' in javascript programs [duplicate]

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 ?

like image 240
Aakash Chakravarthy Avatar asked Jun 20 '10 13:06

Aakash Chakravarthy


2 Answers

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.

like image 190
Quentin Avatar answered Nov 09 '22 06:11

Quentin


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.

like image 22
Nick Craver Avatar answered Nov 09 '22 07:11

Nick Craver