Javascript:Knowing the scope of your local and global variables

If a variable is declared outside a function, it’s GLOBAL. If it’s declared inside a function, it’s LOCAL.

GLOBAL variables

Example of global variables:
var avatar;
var levelThreshold = 1000;

These are global variables; they’re accessible everywhere in your JavaScript code.

LOCAL variables

Example of local variables:
function getScore(points) {
    var score;
    var i = 0;
    while (i < levelThreshold) {
        //code here
        i = i + 1;
            alert(i);
    }

    return score;
}

The "points", "score" and "i" variables are all declared within a function.
We call them local variables because they are known locally only within the function itself.
Even if we use levelThreshold inside the function, it’s global because it’s declared outside the function.

If a variable is declared outside a function, it’s GLOBAL. If it’s declared inside a function, it’s LOCAL.

0   0
Shailesh Kumar

Please rotate your device

We don't support landscape mode on your device. Please rotate to portrait mode for the best view of our site