When to use var in Javascript

JavascriptVar

Javascript Problem Overview


Maybe pretty easy question.

Where should I use var keyword in JavaScript. It seems to me using it or not have the same effect ( but of course I'm still learning the language )

For instance these both seems the same to me:

(function(){
  var a = "mundo"
  alert("Hola, " + a )
})()

and

(function(){
  a = "mundo"
  alert("Hola, " + a )
})()

But of course there must be a more complex example where the difference shows up.

Javascript Solutions


Solution 1 - Javascript

When you use var , you are instantiating a variable in the current scope. This will also prevent access of variables named the same in higher scope, within the current scope.

In your first example, 'a' is being instantiated and set within the function scope. In your second example, 'a' is being set outside the function scope due to lack of var

With var:

var a = "A"
(function(){
  var a = "B"
  alert(a) //B
})()

alert(a); //A

Without var:

var a = "A";
(function(){
  a = "B"
  alert(a) //B
})()

alert(a) //B

Solution 2 - Javascript

Using var:

var a = 'world';   
myfunction = function(){
  var a = "mundo"
  alert("Hola, " + a )
}

myfunction();  //alerts 'hola, mundo'
alert(a);  //alerts 'world';

Not using var:

var a = 'world';   
myfunction = function(){
  a = "mundo"
  alert("Hola, " + a )
}

myfunction();  //alerts 'hola, mundo'
alert(a);  //alerts 'mundo'

Solution 3 - Javascript

I think that you need to refresh yourself on Javascript object scopes.

Using the "var" keyword will place your variable at the top-most (global) scope. This means that if a function uses the same variable, the "var" variable you declared will overwrite the (non-var) variable in your function... JavaScript Scopes

Solution 4 - Javascript

if var not used inside function, JS will look for it above, so in case you use save vars in different functions they might conflict. It always worth to use a var if you are defining new variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOscarRyzView Question on Stackoverflow
Solution 1 - JavascriptBodmanView Answer on Stackoverflow
Solution 2 - JavascriptSam DufelView Answer on Stackoverflow
Solution 3 - JavascriptIt GruntView Answer on Stackoverflow
Solution 4 - JavascriptAgonychView Answer on Stackoverflow