Skip to content

Variable Scope

Global Variables

Global scope was discussed in the introduction to modularization. It's been around for a long time. A global variable is declared in a JavaScript file outside of any functions. The standard is to put them at the top of the file and not indented.

1
2
let date;
let city;
Global variables look like this:

Global Scope

  • If it's not Global it's local.

  • Local Variables are declared inside of functions and that's where they live:

1
2
3
4
function calculateSalesTax() {
    let salesTax; //<-- local variable ...

}

Local Variables

A local variable can't be accessed in any way from any other function. It can't even be seen by any other function--other functions do not know it exists. This is referred to as the variable having local scope.

Local variables look like this:

Local Scope

Read more

Related Reading

Pages 88 - 94 — This topic gets pretty technical. Luckily the book has an entire chapter dedicated to it.

Hands on Work

Labs

  1. Lab02: Local and Global Variables
    • unit05/labs/lab-02-global-vars.html