When to use var in Javascript [duplicate]

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

Leave a Comment