Programming: Variable Scope

    Programming: Variable Scope

      Nothing lasts forever. Shmoop learned that the hard way with an expired can of caviar.

      It's especially true of variables, though. No variable—unlike a Twinkie—is likely to outlive the human apocalypse. Most variables don't even survive after a function ends. And they certainly don't last after the program ends.

      It's all part of a little thing called variable scope. A variable can only last as long as the piece of code it's nested in. Depending on where you initialize—or assign—a variable, the variable's shelf life changes drastically. Initialize the wrong variable in the wrong place, and you'll end up with a major error of the variable not…being there.

      But unlike 90% of the characters in a horror movie, variables can sometimes cheat death. It all depends on how you declare it.

      Watch where you declare your variables, Shmooper; declaring it in one level of nesting (in a code block) means that it can only stay in that level of nesting. (Except JavaScript. But just about everything goes down the drain when you use JavaScript.) This is mainly to keep things clean in our programs.

      The thing is, as much as it might make life easier to declare a variable in one place and use it somewhere completely different, that's the opposite of what you want. Let's talk about two different objects:

      • soft poached eggs
      • tennis shoes

      Fairly different objects, we'll admit, but they also have some shared…words, at least. For instance, both have the variable "run," and a boolean telling us whether each one is…running.
      If we try to find out "run" for tennis shoes and end up with the "run" associated with eggs, our results could get really…

      Scrambled.

      So we really need scope to make sure we can be sure we're calling the right variables.

      We can set variables that have a global scope, but we need to be sure that they affect everything in the program. Otherwise, we can get really…

      Wait for it…

      Scrambled.

      Seriously, though. Make sure your globals act the same way everywhere. Think constants like

      • pi.
      • the freezing point of pure water.
      • the freshness of a Twinkie.

      If it's something like whether or not the egg's runny, your code will get…

      Egg-ceptions.

      Runtime exceptions, to be exact.