2

Is there a difference define variable in global scope between

var my_var;

and

my_var;
umut
  • 1,016
  • 1
  • 12
  • 25

3 Answers3

1

In global scope, there is no difference, unless you using it again: var my_var; will redeclare it, while my_var; will be simply useless expression.

nicael
  • 18,550
  • 13
  • 57
  • 90
1

There is a difference only when not in global context.

Ex1 (with var):

var x = 0; 
(function(){
  var x = 1; 
  alert('fx: '+ x);
})(); 
alert('gx: '+ x);

//fx: 1
//gx: 0

Ex2 (without var):

x = 0; 
(function(){
  x = 1; 
  alert('fx: '+ x);
})(); 
alert('gx: '+ x);

//fx: 1
//gx: 1
rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63
0

var is actually (re)declaring the variable in any current scope while second form is declaring it (globally?) unless it's been declared in a containing scope before. The second form is implicitly declaring, while first form is doing so explicitly.

Thus there is no difference in global scope, for it isn't contained in any other scope.

Thomas Urban
  • 4,649
  • 26
  • 32