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.