Skip to main content
JavaScript
Variable Scope (JavaScript)

JavaScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a global variable, and its value is accessible and modifiable throughout your program. If you declare a variable inside of a function definition, that variable is local. It is created and destroyed every time the function is executed; it cannot be accessed by anything outside the function.

Types of Scope

Languages such as C++ also have "block scope." Here, any set of braces "{}" defines a new scope. JavaScript does not support block scopes.

A local variable can have the same name as a global variable, but it is entirely distinct and separate. Consequently, changing the value of one variable has no effect on the other. Inside the function in which the local variable is declared, only the local version has meaning.

// Global definition of aCentaur.
var aCentaur = "a horse with rider,";

// A local aCentaur variable is declared in this function.
function antiquities() 
{
   var aCentaur = "A centaur is probably a mounted Scythian warrior";
}

antiquities();
aCentaur += " as seen from a distance by a naive innocent.";

document.write(aCentaur);

// Output: "a horse with rider, as seen from a distance by a naive innocent."

It is important to note that variables act as if they were declared at the beginning of whatever scope they exist in. Sometimes this results in unexpected behaviors.

var aNumber = 100;
tweak();

function tweak()
{
    // This prints "undefined", because aNumber is also defined locally below.
    document.write(aNumber);

    if (false)
    {
        var aNumber = 123;  
    }
}

When JavaScript executes a function, it first looks for all variable declarations,

var someVariable;

and creates the variables with an initial value of undefined. If a variable is declared with a value,

var someVariable = "something";

then it still initially has the value undefined, and will take on the declared value only when the line containing the declaration is executed, if ever.

JavaScript processes variable declarations before executing any code, so it does not matter whether the declaration is inside a conditional block or some other construct. Once JavaScript has found all the variables, it executes the code in the function. If a variable is implicitly declared inside a function - that is, if it appears on the left-hand-side of an assignment expression but has not been declared with var - then it is created as a global variable.