Scope

The scope determines the accessibility to variables and functions. If something is "outside of scope" it means we can not access it.

Global

The global scope is the scope that is accessible from anywhere. Anything that is defined outside of a function is a part of the global scope.

Consider this very simple program. It only contains a single variable called planet. The variable is a part of the global scope because it is defined outside any function.

var planet = 'earth';

Local

However, if the variable had been defined inside a function instead it would no longer belong to the global scope.

function universe() {
    var planet = 'earth';
}

planet is no longer in the global scope, but instead constrained to the scope of the universe function.

function universe() {
    var planet = 'earth';
}

console.log(planet);

In other words, it is inaccessible from the global scope. Which in turn means that the code above would throw a ReferenceError stating that planet is not defined.

Lexical

Another useful (but perhaps counterintuitive) scope is the lexical one. It provides a function within another function access to the scope of the outer function.

function universe() {
    var planet = 'earth';

    function milkyWay() {
        console.log\(planet\);
    }
}

Calling the milkyWay function would log out earth in the case above.

Last updated