Variables and code instructions have specific contexts — or “scope” — when executing a Javascript program. The Javascript standard provides specific rules for managing scope.

The Javascript global scope is the default context for everything in a Javascript program, and programmers routinely create customized scopes for variables and other Javascript statements. Javascript variable scopes are purposely limited compared to the Javascript global scope.

This article describes the differences between the Javascript global scope and Javascript variable scopes. In addition, it explains why managing scopes is important to proper Javascript program function.

Javascript Global Scope

The Javascript global scope is the context where everything in a Javascript program executes by default. This scope includes all variables, objects, and references that are not contained within a customized scope defined by a programmer.

Global scope is the entire Javascript execution environment. Any variables assigned without an explicit scope (using the var, let, or const keywords) automatically become global variables. The same is true for functions.

myVar = 1; // An automatic global variable

// An automatic global function
function myFunc() {
    return true;
}

You can prevent variables assigned without an explicit scope from becoming global variables by using Javascript’s “strict” mode. Functions may still be declared as global, but variables may not. With strict mode enabled, the previous example’s variable declaration will no longer work, since all variables must be defined with an appropriate scope keyword; instead an error will be raised.

use strict;
let myVar1 = 1;  // Global variable, OK.
myVar2 = 2;      // Will throw an error!

In the global scope, any variable can overwrite any other variable at any time. This is why creating global variables and global functions in Javascript is potentially dangerous. The Javascript interpreter does not check to make sure that a variable or function name exists, so you might accidentally overwrite an important built-in Javascript function or property.

The Javascript global scope is critical to run programs properly, but developers should never create global variables or global functions in production code, especially in large projects. It is not dangerous to create global functions and variables in small, isolated test cases. Anytime someone else will use your code, using the global scope is a risky choice.

For example, most of Udacity’s Javascript examples are presented in the global scope for simplicity. If you base any of your code on Udacity’s examples modify the source code to use local scope.

Javascript Variable Scopes

Any customized scope specified by a programmer, and therefore not part of the global scope, is a local scope. Javascript local scopes contain variables, functions, and statements in a restricted context. The contents of local contexts are deleted as soon as the contexts are no longer needed.

Every Javascript structure has its own local scope, and most structures can also hold other scopes within them. For example, this Javascript function containing a Javascript switch statement has multiple scopes: the scope of the function, the scope of the switch statement, and the scope of each case inside the switch statement.

function scopeExample(param) {
    let myVar = 1 + param;
    switch (myVar) {
        case 1:
            let myVar2 = 2;
            myVar += myVar2;
            break;
        case 2:
            myVar += 5;
            break;
        default:
            myVar = 0;
            break;
    };
    return myVar;
}

Variables are available to children scopes. In this example, the variable inside a Javascript for loop is accessible inside its child Javascript if else statement, but variables created inside the if else statement are not accessible to its parent for loop.

for (let i = 1; i <= 10; i++) {
    let a = 0;  // Accessible to the if else statement

    if (i % 2 == 0) {
        a = 1;
        let b = a + 2;  // Only accessible to this if else branch
        console.log(b);
    } else {
        a += 2;
        let c = a + 3;  // Only accessible to this if else branch
        console.log(c);
    }
}

Managing Variables in Different Scopes

The safest way to manage scopes is to restrict the existence of variables to the smallest program region possible. If a variable is only needed inside a switch statement, for example, there’s no need to define that variable outside of the switch statement’s scope.

If you must create a global variable, make it a complex object, like a class, and give it an equally complex name to reduce the chance that it will conflict with other variables in the global namespace. Some programmers create a unique prefix that they attach to their global variable names, perhaps including their initials, the name of the company they work for, or the unique identifier for their overall project.

A common practice for managing scopes is to create a Javascript object or class with a unique name, as mentioned above, then to use that object as a base for all other variables and methods within a project.

Conclusion

The Javascript global scope might be the simplest context to place your code into, but you risk causing data type and reference errors if you overwrite values at the wrong time. Restricted Javascript variable scopes lessen this problem, but it is still possible to overwrite variables unintentionally in any scope.

Careful scope management is crucial to proper Javascript program function. The larger a program becomes, the higher the chance that data in the global scope will be problematic, so large programs should use variable scopes whenever possible.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript global scope, Javascript variable scopes, and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni