tags:

views:

430

answers:

8

Is "var" optional?

myObj = 1;

same as ?

var myObj = 1;

I found they both work from my test, I assume var is optional?

+2  A: 

They are not the same.

Undeclared variable (without var) are treated as properties of the global object. (Usually the window object, unless you're in a with block)

Variables declared with var are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)

SLaks
Why the -1? +1 for correct although short answer.
PatrikAkerstrand
+1 for the link
codemeit
+26  A: 

They mean different things. If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable is automatically global, and attached to the global object (window, if you are doing it in the browser).

This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget var and have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.

Stefano Borini
You can create a variable inside a method without using `var`. That doesn't make it global, IE does that often, how can that be dangerous?
The Elite Gentleman
@The Elite Gentleman: Wrong. It does.
SLaks
@The Elite Gentleman: Yes, it does make it a global variable.
PatrikAkerstrand
+1 for "one of the most dangerous issues with javascript, and should be deprecated"
codemeit
@codemeit : javascript is full of pitfalls like this, but all in all it's a beautiful and very pleasant language. Don't hate it. Just know the pitfalls and leave them out of your code.
Stefano Borini
Automatic global variables are removed from ECMAScript 5 strict mode, which is basically an implicit deprecation. Hopefully implementations will give a warning if you forget `var` in non-strict mode.
Matthew Crumley
Actually no, assigning to a variable without using `var` does not make it *global*. It causes JS to traverse up the scope chain, eventually ending up at the global object if the variable was not used anywhere before. If the variable *was* declared using `var` somewhere before global, that's the scope that will be used. It's also an integral part of how JS works and what makes it really powerful, so I wouldn't describe it as a "pitfall".
deceze
@deceze: traversing up the scope chain is a good thing, but adding it to the global scope if it doesn't find anything is a pitfall.
Matthew Crumley
+6  A: 

var is optional. var puts a variable in local scope. If a variable is defined without var, it is in global scope.

kzh
+1 for short and sweet answer.
codemeit
+12  A: 

Nope, there are not equivalent.

With

myObj = 1;

You are using a global variable.

The latter declaration create a variable local to the scope you are using.

try the following code to understand the differences:

external = 5;
function firsttry() {
  var external = 6;
  alert("first Try: " + external);
}

function secondtry() {
  external = 7;
  alert("first Try: " + external);
}

alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7

The second function alter the value of the global variable "external", the first function don't.

Eineki
+1 for the examples.
codemeit
+3  A: 

The var keyword in Javascript is there for a purpose.

If you declare a variable without the var keyword, like this:

myVar = 100;

It becomes a global variable that can be accessed from any part of your script. If you did not do it intentionally or are not aware of it, it can cause you pain if you re-use the variable name at another place in your javascript.

If you declare the variable with the var keyword, like this:

var myVar = 100;

It is local to the scope ({] - braces, function, file, depending on where you placed it).

This a safer way to treat variables. So unless you are doing it on purpose try to declare variable with the var keyword and not without.

Cyril Gupta
+1 for "t can cause you pain if you re-use the variable name"
codemeit
+1  A: 

Consider this question asked at StackOverflow today:

Simple Javascript question

A good test and a practical example is what happens in the above ceneario...
The developer used the name of the JavaScript function in one of his variables.

What's the problem with the code?
The code only works the first time the user clicks the button.

What's the solution?
Add the var keywork before the variable name.

Leniel Macaferi
+4  A: 

There's a bit more to it than just local vs global. Global variables created with var are different than those created without. Consider this:

var foo = 1; // declared properly
bar = 2; // implied global
window.baz = 3; // global via window object

Based on the answers so far, these global variables, foo, bar, and baz are all equivalent. This is not the case. Global variables made with var are (correctly) assigned the internal [[DontDelete]] property, such that they cannot be deleted.

delete foo; // false
delete bar; // true
delete baz; // true

foo; // 1
bar; // ReferenceError
baz; // ReferenceError

This is why you should always use var, even for global variables.

bcherry
+4  A: 

This is one of the tricky parts of Javascript, but also one of its core features. A variable declared with var "begins its life" right where you declare it. If you leave out the var, it's like you're talking about a variable that you have used before.

var foo = 'first time use';
foo = 'second time use';

With regards to scope, it is not true that variables automatically become global. Rather, Javascript will traverse up the scope chain to see if you have used the variable before. If it finds an instance of a variable of the same name used before, it'll use that and whatever scope it was declared in. If it doesn't encounter the variable anywhere it'll eventually hit the global object (window in a browser) and will attach the variable to it.

var foo = "I'm global";
var bar = "So am I";

function () {
    var foo = "I'm local, the previous 'foo' didn't notice a thing";
    var baz = "I'm local, too";

    function () {
        var foo = "I'm even more local, all three 'foos' have different values";
        baz = "I just changed 'baz' one scope higher, but it's still not global";
        bar = "I just changed the global 'bar' variable";
        xyz = "I just created a new global variable";
    }
}

This behavior is really powerful when used with nested functions and callbacks. Learning about what functions are and how scope works is the most important thing in Javascript.

deceze
A clean and well written answer :)
Mattis