Thoughts on naming your variables

Naming variables has always been a source of debates around developers. The general idea is that you should pick a name as short as possible, but long enough to provide meaning, one which would be self-explanatory, for which you needn’t browse the code to understand what it’s used for.

Studying naming conventions can help. Also, having some specially set within your team is a good idea. Here are some that are quite general:

  • For variables, you should use nouns. Other ideas:
    • with a plural form for arrays;
    • if your variable is a boolean, you should prefix it with is, has, can;
  • For functions, you should use verbs, with a recommended format of actionResource (e.g. resetPassword);
  • Avoid using my in the names you pick (e.g. myClearFunctionName) and other keywords like if, else, for, switch, float, long etc.;
  • Do not combine case styles (e.g. use kebab-case with snake_case or camelCase);
  • Go from general to specific – e.g. nameFirst and nameSecond (name is the general part, First and Last are the specific parts);
  • Constants should be written in UPPERCASE.

Apart from these rather general rules, I found it easier and productive to keep my variables on the positive side (e.g. use isValid instead of isNotValid or isInvalid) throughout the code of a project.

It is hard to apply all of them right from the beginning, but with time and practice, everybody gets better and better.

A source for more best practices is Java. It is one of the mature programming languages which has solved in its features and rules many of the problems which a novice might encounter while “navigating the rivers” of the flexible javascript.

More information and sources: