here i didn't understand what happen when i use var
before variable in function it give me different out put and with out using var
also i got a different output
here is a code that you can easily figure out whats going on
function value() {
var m = 8; //here i am using var as a datatype
console.log(m)
}
m = 7
console.log(m);
value();
console.log(m);
and also when i removing var or not using any data type from value function then i got different out put here is a code
function value() {
m = 8; //here i am not using var as a datatype
console.log(m)
}
m = 7
console.log(m);
value();
console.log(m);
can any one can tell me whats going on thanks for your time
Take a look at w3school's JavaScript Scope.
Below is example code of the difference of global variable and local variable.
function value() {
// local variable in value()
var m = 8;
console.log("in value() : " + m)
}
function value2() {
// set global variable as 9
m = 9;
console.log("in value2() : " + m)
}
// global variable
m = 7
console.log("before value() : " + m);
value();
console.log("after value() : " + m);
value2();
console.log("after value2() : " + m);
Below is another case to show the difference of scope:
m = 7;
function v(){
var m = 6;
v2();
function v2(){
console.log("in v2 : " + m);
v3();
}
}
function v3(){
console.log("in v3 : " + m);
}
v();
Function looks for the m
in the functional scope, if it does not find it there, it searches in the higher scope which over here is global scope.
In the first example, function creates a variable m
in the function scope and any update will be limited to the variable in the function. So, basically in this example there are 2 variables, with one m
belongs to the global scope and one m
belongs to the function scope. See the interpretation of code below.
var m;
function value() {
var m; // creates a variable m in the function scope
m = 8;
console.log(m)
}
m = 7
console.log(m);
value();
console.log(m);
In the second example, function tries to access a variable m
in the function however, does not find there, hence, searches in the higher scope (global scope) and find one. So, basically in this example there is only 1 variable of m
belongs to the global scope. See the interpretation of code below.
var m;
function value() {
m = 8; // no function scope, variable, updates global scope
console.log(m)
}
m = 7
console.log(m);
value();
console.log(m);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With