OscarRyz OscarRyz - 2 months ago 6
Javascript Question

When to use var in Javascript

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.

Answer

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 (most likely window.a).

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
Comments