Global

Global variables are variables that are available everywhere. In general, a global variable is a variable that is declared outside any scope. Global variables can be convenient because they are available everywhere. You don’t have to think about what scope you are in because a global variable is always in scope. That really is useful, but global variables have downsides as well. Extensive use of global variables leads to messy code that is difficult to understand and difficult to debug. For instance, the sayAName function in Listing 8.19 is almost identical to Listing 8.18, but the small difference causes a big problem.

Listing 8.19 Be Careful with Global Variables

var myName = 'Steven';function sayAName() ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.