Scope

Scope refers to the area in which code is accessible within a program. This module will explain the differences between global and local scope for variables.

File Location

    javascript-library
        └── 1-Fundamentals
            └── 1-Grammar-and-Types
                03-scope.js <-- You are here

Global vs. Local Scope

Global scope means that a piece of code is accessible throughout the entire program. This could be a variable, a code block, a function, or more. Local scope, on the other hand, means that a piece of code is only available within a limited part of the program. This could also be a variable, a function, and more. Here is an example of each:

//Global scope
var x = 12
{
    //local scope
    var y = 12;
}

So, notice that the scope of y is within the curly braces. Curly braces are one of the defining factors in the various levels of scope. Curly braces define a code block.

Practice

Let's look ahead at how let deals with scope:

  1. In 03-scope.js, declare a variable named "outside" using the var keyword; initialize it with the string: "outside".

  2. Add a code block beneath your first variable

  3. Inside the block declare a variable named "inside" using the let keyword; initialize it with the string: "inside". Inside the code block print the "inside" variable to the console.

  4. Outside of the block of code, print both variables to the console. What happens? The reasons for this will be covered more in-depth in the next module.

Last updated