Local and Global Variable Naming Conventions

Officially, it doesn't matter what you name local and global variables, as long as you follow the naming conventions that we have discussed in earlier modules. In practice, however, there are standardized local and global variable naming conventions that many programmers follow.

Here is the naming convention that I follow:

Local variable names always begin with the prefix "my".

Example:

myText
myCounter
myPosition
myNumber

Global variable names always begin with the prefix "the".

Example:

theText
theCounter
thePosition
theNumber

Following a local/global naming convention, like the one outlined above, can really help you keep your local and global variables straight when you start writing more complex code. Trust me, it makes a difference!

I also strongly recommend making your variable names reflect their purpose; this will make your code read much more like regular English than like techno-gibberish. For instance, if your variable is holding the result of a calculation, name it myResult or myAnswer rather than goobah or fred. Which of the following code examples is easier to read?

var goobah = 1 + 1;
var myAnswer = 1 + 1;

If I were dealing with temporary information, I might call my variable temp or myTemp. If I were dealing with some HTML text, I might call my variable myHTMLText or myText or theText (depending on whether it were local or global).

In the same way, if I were writing a function which switched images, I would name that function using verb syntax, reflecting its purpose: switchImage() or handleImageSwitch(), rather than grumble() or snuffBox().

I have one student who named all of her functions after days of the week, and all of her variables after friends. Needless to say, she couldn't remember which function did what, or what the variables were for. My partner works at a company where one of the programmers had the bright idea of naming a utility function "fillUpMyCokePlease()". Again, no one can ever remember exactly WHAT that function is supposed to do! You get the idea.

Do yourself a favor: name variables and functions after their purpose, not after your dog or to commemorate the purchase of your new lava lamp. You'll thank yourself later, trust me...


Main Menu