Saturday, January 3, 2015

Scope of a variable in javascript

Global scope of a variable:

When we declare a variable outside of a function then that variable has the global scope.
This type of variable can be accessed anywhere in the program or file.

Example:

var str = "test value";

It can be used anywhere in the program.

Local scope of a variable:

When we create a variable inside a function body then that variable has the local scope.
This type of variable cannot be accessed outside the function.

Example:

function getResult() {
    var result = 10;
    alert(result);
}

Note 1: When we do not declare a variable with “var” inside a function then
that variable can also be accessible outside of the function. Hence it has global scope.

Example:

<asp:Button ID="btn" runat="server" Text="submit" OnClientClick="getResult();" />

function getResult() {
    result = 10;   
    test();
    return false;
}

function test() {
    alert(result);//result will return 10 which is declared in getResult()
    return false;
} 


Note 2: When we define nested function then inner function has access to the variable defined in outer function but outer function cannot access to the variable defined in inner function.

Example:
function getResult() {
    var result = 10;

    function test() {
        var str = "Test";
        alert(result); //output will be 10
        return false;
    }

    alert("str" + str);// str will not be accessible
    return false;
}

No comments:

Post a Comment