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?
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?
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.
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.