Naming Variables

Variable labels should be meaningful, but you can choose almost any label you like. There are just a few rules and guidelines to be aware of.

Naming Rules

There are a few rules when choosing labels:

  • Labels cannot include spaces. For example, width of rectangle would generate an error.
  • Labels cannot begin with a number. 4sides and 2morrow will generate errors.
  • Be very careful with spelling. If labels are not spelled exactly the same way, the computer will not realize that they refer to the same variable.
  • Labels are case-sensitive. size is not the same as Size or SIZE.

Using Meaningful Labels

When you see a variable in your program, you'll want to know exactly what's in it without having to search around. Make sure you label your variable something meaningful. score and lives are great labels that tell you exactly what that variable is used for. number and a are not as helpful.

camelCase

Labels with multiple words can be easier to read in camelCase. A camelCase label looks like sizeOfRectangle or aReallyLongLabelName. The first letter of the variable name is usually lower case, each new word starts with a capital letter. This helps you see the start of new words without using spaces, which are not allowed in variable names.

using_underscores

Another common way to put multiple words in a variable label is to use underscores between the words. When using underscores, programmers usually don't use capital letters at all. These types of variables look like size_of_rectangle or my_frog_sprite.

Consistency

The most important thing when you choose how to label your variables is to use a consistent style so it's easy for you to remember the exact spelling and capitalization of your variables.

Found a bug in the documentation? Let us know at documentation@code.org