Rongohua o te Korimako

Technical Blog—Scope

The road to pro­gram­ming hell is paved with glob­al vari­ables. Steve McConnell—American Author

Scope

  • Explain to a non-tech friend, what ‘scope’ is, and how it works in JavaScript.
    A key concept in programming is the idea of a variable. This word comes from vary and is a storage location for data or calculations. Variables are used while a program is running and their contents are often modified (varied) by the program.

    In essence, variables have two types of scope: global and local. Global variables are accessible throughout an entire JavaScript program, whereas local variables can only be used inside the function (or part) where they are declared (set up).

    Some people think that all variables should be global. However, as programs grow bigger or are worked on by teams of programmers, there can be unfortunate side effects where different parts of a program change the variables in unexpected ways. A better, safer approach is to use local variables whenever possible. Please refer to Steve McConnell’s quote at the top of this page.