Global Scope: The Hallway

Grade 9, page 2 of 11. A one-minute read.

A variable created outside of any function or block lives in the global scope. It can be seen from everywhere in your program:

JavaScript
const appName = "Scriptology Notes";

function showHeader() {
  console.log(`=== ${appName} ===`);
}

function showFooter() {
  console.log(`(c) ${appName}`);
}

showHeader();
showFooter();

It prints

=== Scriptology Notes ===
(c) Scriptology Notes

Both functions can see appName, because it lives in the hallway, which every room can see out into.

Watch outToo many globals

Global variables are convenient, but be careful. Because any code can read and change them, they make bugs very hard to track down. ("Who changed score to -500?! It could have been anyone!") Also, in a web page, all your scripts share the same global scope, so a global called count in one file can clash with a global called count in another. Keep your global variables to a minimum. Put variables inside functions whenever you can.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning