Javascript Identifiers | What are identifiers, and how do name them?

Javascript Identifiers

From some of our previous experiences, we have seen that, whenever we are creating some variable, we give some name to it. But, it can be a thing to wonder, what names can I give, or what are the names allowed for the variables, or can I give any name? So, now we are going to see what names are allowed and what are not. Just understand that the name that you give to the variables, functions, objects, etc are called identifiers. Here are some rules for giving names to these variables, functions, etc –

  • The name can start with any alphabet(a – z or A – Z)
  • You cannot start your identifiers with a number.
  • You can start the variable name with a dollar sign $.
  • You can also use an underscore in the variable.
  • You cannot use keywords as an identifier.

So, below are some valid names of variables and there are some invalid names too. Remember that when we will learn about functions and objects etc, we will be using such names there as well. So knowing what names we can use and what names we cannot use is much more important.

One thing to note is that you cannot use keywords(reserved words) as an identifier. Keywords are words whose meaning is known to JavaScript and they are used for some special purpose and are not supposed to be used anywhere else.

Here are some keywords that we will be using frequently –

  • for
  • if
  • break
  • continue
  • function
  • var
  • let
  • const
  • while
  • do
  • else
  • switch
  • return
  • typeof
  • true
  • false
    and many more…

You can explore the documentation for the list of the keywords, but we have listed the above quite frequently used keywords. Here are some variable names that are valid, and some are invalid.

As you can see, the IDE is telling as well, that there is something wrong with the last variable that you are creating, by showing the red underline. Well, the thing is that using keywords as an identifier is not allowed. Here is some output related to this –

So, we should be careful, when using the names of the identifiers. Well, it is not compulsory, but we should practice naming the identifiers in a semantic way, which means that the name should convey their meaning for existence. For if we have a function to calculate the area of a circle, the name of the function can be areaOfCircle, instead of something else, and also if there is some variable that holds some company name, then we should name it as the company name. However, it is not compulsory but always recommended.