Ask your Question

PEOPLE YOU MIGHT KNOW

Pooja
Pooja

Chiplun,  India
Everest Educational
Everest Educational

Visa Consultants in Punjab

Ludhiana,  India
Vikas
Vikas

Web developer

Gurgaon,  India
Space
Space

Courier Services

Birmingham,  United Kingdom
MobileComm
MobileComm

MobileComm Professionals Inc.

Richardson,  United States

Write to us

Ask Question

Javascript:Knowing the scope of your local and global variables

Shailesh Kumar

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.

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