When teaching students, the question of how to name things comes up.
There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.
— Jeff Atwood (@codinghorror) August 31, 2014
The rules naming things like variables and functions is simple:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letter
- Names can also begin with $ and _ (but we will not use it in this class)
- Names are case sensitive (rose and Rose are different variables, even if they both smell just as sweet)
- Names cannot contain spaces
Variables are declared with the keyword var. Once a variable has been declared, it can have its value reassigned.
// example: var rose; rose = "florabundas";
Then there are naming conventions, that while not required are expected, such as camel casing:
// good examples (camel casing) var hereIsOneExample; var hereIsAnotherExample; // bad examples var hereisoneexample; var here_is_another_example;
Why “camelCase”? Because there is a hump or two (or more) in the middle if the name is formed by more than one word. A camelCase name begins in lower case. If there’s more than one word in the name, each subsequent words gets an initial capitalization, thereby creating a “hump”. A one word variable name gets no hump, but a compound word would. The intention of using camelCase is to make your variable names stand out from the rest of the code. This way if another programmer comes along to read it, they will recognize it as a variable (or a function name).
You will also want to make your variable and function names representative of what they are. Nouns are good for variables as they represent specific values. Verbs or action words should make up your function names as functions do things.
// example variables: var score = 0; var lives = 3; var message = "hello world";
// example function names: doMath(); birdFlap(); animateNextSlide();