Variable naming

  1. Short names
  2. Multiple words
  3. Under_score VS camelCase
  4. Summary

When you create a variable, it is very important to give it a proper name.

The script may have a lot of variables. Compare it with a number of labelled boxes in the attic. Without good labels, you will never be able to find the right box.

Same with variables. As your scripts will become more and more complex, right variable names will also become more and more important.

Short names

One of the things which tells an experienced programmer from a newbie is how they name variables.

Hopefully, there are rules of thumb.

The variable is allowed to have a short or senseless name like ‘a’, ‘b’ only when it is used only in the nearest code.

A variable named a is like a box which you label by a cross or circle. For five minutes you remember what is inside the crossed box. But after a week, you forget it.

The name of most variables should be both descriptive and concise. Sometimes it’s not easy to find a good name. One word may be not enough.

For example:

var userId; 
var slidingPanel; 
var wrappingElement;

Multiple words

There is another rule in all names from the above.

The variable name becomes increasingly accurate from right to left. Adjectives always go left.

For example, a userId is basically an id which, speaking more precisely, belongs to a user.

The slidingPanel is a panel which slides.

Under_score VS camelCase

Syntactically, there are two ways of joining words into a name.

The first is called a camel-case, it looks like this:

var mainTextElement;

The other one is underscore:

var main_text_element;

The common conception is to use camel-case in object-oriented style of programming and underscore in procedural/functional style.

JavaScript is a flexible language where you can use both approaches. But object-oriented approach is more widespread.

The advantage of camel-case is shorter names, because you don’t need extra underscores.

Also, most built-in JavaScript methods use camel-case, so it is recommended that you use it too.


In short, the naming rules are:

  1. Short names for variables which you use only in nearest code.
  2. Multiword names add precision from right to left, adjectives are always at the left side.
  3. Use camel-case.

The approach described in this section is not a dogma. Please share your ideas in comments.