Skip to content Skip to sidebar Skip to footer

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 defi

Solution 1:

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


Solution 2:

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.


Solution 3:

If you define:

var y = 'I am defined outside foo definition';

It will be a global window variable (in case you are using js in a browser), which can be accessed 'globally' by calling:

window.y

If you use it inside a function, like:

function foo(x) {alert(y);}

It will still refer a global variable, because it is not shadowed by function parameters.

If you define a function as:

  function foo(y) {alert(y);}

Then y is being shadowed by function parameter (which is btw an alias for arguments[0]). Which means that all references to variable y inside this function will refer the parameter variable, not the global one. So for example:

var y = 'I am defined outside foo definition';
function foo(y) { y = 'something';}
alert(y);

will display I am defined outside foo definition.

Edit: If you have a function:

function bar(x) {
    alert(x);
}

and you try to call it using bar() then function parameter parameter x shadows global variable x. JS engine will look for local variable x and it will not be found - which means you will get undefined message in your alert.


Post a Comment for "JavaScript Function Parameter And Scope"