I have done some tests with codes listed below:
function foo(x) {
alert(y);
}
var y = 'I am defined outside foo definition';
foo();
The above code gives me an alert 'I am defined outside foo definition'.
Then another test:
function bar(x) {
alert(x);
}
var x = 'I am defined outside foo definition';
bar();
function bar(x) {
alert(x);
}
x = 'I am defined outside bar definition';
bar();
Both the above codes give me an alert 'undefined'.
So Why?
Because in both those cases you have a local scoped variable(the first parameter) in the function bar
to which you are not passing any value. Since there is a local scoped variable it will not check the global scope to see whether such a variable exists.
In this case you need to pass the value to the parameter when bar
is invoked
function bar(x) {alert(x);}
x = 'I am defined outside foo definition';
bar(x);
In the first case when you are using y
inside bar
there is no local scoped variable called y
in bar
so it looks at a parent scope to see whether such a variable exists if so that variables value is accessed that is how it is working
This is because when you declare the parameter x
function bar(x) { /*...*/ }
You are "hiding" the global variable x. You only have access to the parameter x
try passing in the global x
function bar(x) { alert(x); }
var x = 'I am defined outside bar definition';
bar(x); // here the x is the global x that we pass in
// the function gets a reference to the global x
If we omit the parameter then the global x would become visible again
function baz() { alert(x); }
var x = 'global var';
baz(); // 'global var'
Note that global variables should be limited in good js applications.
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