A Simple Guide to Naming Variables in JavaScript

Naming variables can be sometimes confusing for absolute beginners in JavaScript, but with this simple guideline, you should be able to have a grasp of the do's and don'ts.

Identifiers in JavaScript

An identifier is a name that is given to entities like variables, functions, class, etc.

Guidelines for naming JavaScript identifiers

Below are some rules for naming identifiers:

  • Identifiers should start with either a letter, an underscore or a dollar sign. For example:

Screenshot (72).png

  • Identifiers should be void of space.

Screenshot (74).png

  • A digit can be used when naming a variable but not at the beginning of the identifier.

Screenshot (75).png

  • JavaScript is case-sensitive. nextyear and nextYear are different identifiers. It is best practice to use Camel case when naming variables.

Screenshot (76).png

  • Identifiers should be explanatory. userNumber = 2 is better than n = 2.

Screenshot (77).png

  • When using the Boolean operator, using is or has makes it understandable.

Screenshot (78).png

  • Avoid one letter variables.

  • Do not use reserved words like class, function, false, while, etc.

Here's a link for a more detailed explanation on Identifiers.