Scope

Now that you have a pretty good understanding of functions, let’s go back and think about variables. A variable is a reference to some value, maybe a string, a Boolean, or an object. When a variable is encountered while a program is executed, the program’s runtime looks up the value related to the variable’s name. In this context, scope determines where the runtime is allowed to look for the value. If a variable is defined within a function, the runtime is allowed to look only inside the scope of the function to find the value related to that variable’s name. A variable defined in one function cannot be used in another function. That concept is confusing, but an example should make it a bit easier to understand. See Listing 8.18.

Listing ...

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.