[javascript] Is using 'var' to declare variables optional?

Is "var" optional?

myObj = 1;

same as ?

var myObj = 1;

I found they both work from my test, I assume var is optional. Is that right?

This question is related to javascript

The answer is


Var doesn't let you, the programmer, declare a variable because Javascript doesn't have variables. Javascript has objects. Var declares a name to an undefined object, explicitly. Assignment assigns a name as a handle to an object that has been given a value.

Using var tells the Javacript interpreter two things:

  1. not to use delegation reverse traversal look up value for the name, instead use this one
  2. not to delete the name

Omission of var tells the Javacript interpreter to use the first-found previous instance of an object with the same name.

Var as a keyword arose from a poor decision by the language designer much in the same way that Javascript as a name arose from a poor decision.

ps. Study the code examples above.


I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf


Nope, they 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("second Try: " + external);
}

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

The second function alters the value of the global variable "external", but the first function doesn't.


Check out this Fiddle: http://jsfiddle.net/GWr6Z/2/

function doMe(){

a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+"  --  b:"+b);

b = "something else"; // still local (not global)
alert("a:"+a+"  --  b:"+b);

};


doMe()
alert("a:"+a+"  --  b:"+b); // `b` will not be defined, check console.log

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.


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

edit

I thought that the non-deletable part was true at some point in time with a certain environment. I must have dreamed it.


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.


Consider this question asked at StackOverflow today:

Simple Javascript question

A good test and a practical example is what happens in the above scenario...
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 keyword before the variable name.


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)

Update: ECMAScript 2015

let was introduced in ECMAScript 2015 to have block scope.


There's so much confusion around this subject, and none of the existing answers cover everything clearly and directly. Here are some examples with comments inline.

//this is a declaration
var foo;

//this is an assignment
bar = 3;

//this is a declaration and an assignment
var dual = 5;

A declaration sets a DontDelete flag. An assignment does not.

A declaration ties that variable to the current scope.

A variable assigned but not declared will look for a scope to attach itself to. That means it will traverse up the food-chain of scope until a variable with the same name is found. If none is found, it will be attached to the top-level scope (which is commonly referred to as global).

function example(){
  //is a member of the scope defined by the function example
  var foo;

  //this function is also part of the scope of the function example
  var bar = function(){
     foo = 12; // traverses scope and assigns example.foo to 12
  }
}

function something_different(){
     foo = 15; // traverses scope and assigns global.foo to 15
}

For a very clear description of what is happening, this analysis of the delete function covers variable instantiation and assignment extensively.


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.


Everything about scope aside, they can be used differently.

console.out(var myObj=1);
//SyntaxError: Unexpected token var
console.out(myObj=1);
//1

Something something statement vs expression


No, it is not "required", but it might as well be as it can cause major issues down the line if you don't. Not defining a variable with var put that variable inside the scope of the part of the code it's in. If you don't then it isn't contained in that scope and can overwrite previously defined variables with the same name that are outside the scope of the function you are in.