Lesson 4. Variable scope

 

After reading lesson 4, you’ll be able to

  • Know the benefits of variable scope
  • Use a shorter way to declare variables
  • See how variable scoping interacts with for, if, and switch
  • Know when to use a wide or narrow scope

In the course of running a program, many variables are used briefly and then discarded. This is facilitated by the scoping rules of the language.

Consider this

How many things can you keep in your head at once?

It has been suggested that our short-term memory is limited to about seven items, with a seven-digit phone number being an excellent example.

Computers can store many values in their short-term or Random Access Memory (RAM), but remember that code is read not only by computers, but also by humans. As such, code should be kept as simple as possible.

If any variable in a program could change at any time, and be accessed from anywhere, keeping track of everything in a large program could become quite hectic. Variable scope helps by allowing you to focus on the relevant variables in a given function or portion of code without concerning yourself with the rest.

4.1. Looking into scope

When a variable is declared, it comes into scope, or to put it another way, the variable becomes visible. Your program can access the variable so long as it’s in scope, but once a variable is no longer in scope, attempts to access it will report an error.

4.2. Short declaration

4.3. Narrow scope, wide scope

Summary