-1

I noticed that in JavaScript, Inside a function some times a variable created without mentioning var before it.

For example :

function myfunction() {
     x = 10;
     var y = 10;
}

what is the difference between these both?

Saravana
  • 524
  • 1
  • 6
  • 28
  • 4
    I'd look at here: http://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-to-use-it-or-omit-it – tetutato Jul 29 '16 at 03:21

1 Answers1

3

function myact() {
  x = 20;
  var y = 10;
  console.log(x);
  console.log(y);
}
myact();
console.log(x);
//y not available here

var is used for declaration. So, assigning without declaration will simply give it global scope meaning: it will first search if it is available in any scope stack above, if not creates the variable implicitly in global scope and assigns.

JS Docs says:

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

Iceman
  • 6,035
  • 2
  • 23
  • 34