Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript var or not var, what's the difference? [duplicate]

Tags:

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

like image 318
Shaoz Avatar asked Dec 08 '10 09:12

Shaoz


People also ask

What is the difference between VAR and without VAR in JavaScript?

Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it. Global variables are destroyed when you close the page. If you declare a variable, without using "var", the variable always becomes GLOBAL.

Should I never use var JavaScript?

This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.

What is the difference of using VAR and not using var in REPL?

What is the difference of using var and not using var in REPL while dealing with variables? Use variables to store values and print later. if var keyword is not used then value is stored in the variable and printed. Whereas if var keyword is used then value is stored but not printed.


2 Answers

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.

like image 200
Nick Craver Avatar answered Oct 17 '22 09:10

Nick Craver


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 } 
like image 43
Ollie Edwards Avatar answered Oct 17 '22 10:10

Ollie Edwards