Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function parameter and scope

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?

like image 696
Gab是好人 Avatar asked Dec 11 '22 22:12

Gab是好人


2 Answers

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

like image 169
Arun P Johny Avatar answered Dec 20 '22 14:12

Arun P Johny


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.

like image 44
t3dodson Avatar answered Dec 20 '22 14:12

t3dodson