When we name variables in javascript, we’ve to follow certain rules. Each variable should have a name that appropriately identifies it. Your JavaScript code gets easier to comprehend and work with when you use suitable variable names. It’s critical to name variables correctly.
For example Constants and global variables are always written in uppercase.
The following are the rules for naming variables in JavaScript:
- Spaces are not allowed in variable names.
- Only letters, digits, underscores, and dollar signs are permitted in variable names.
- Case matters when it comes to variable names.
- A letter (alphabet), an underscore (_), or a dollar sign ($) must be the first character in a variable name, any other special characters must not be taken.
- certain terms such as reserved words in javascript shouldn’t be used to name variables.
Example 1: Check if variables can be named starting from other symbols. We start the variable name with a hyphen to check whether it’s a possible naming convention but it results in an error.
Javascript
<script> var #abc = "abc"; console.log( #abc); </script> |
Output:
We get an error because starting the variable name with an # symbol gives an error as it’s not the right naming convention.
Javascript
<script> var _abc = "abc" ; console.log(_abc); </script> |
Output:
Example 2: Check if spaces are allowed. The spaces aren’t allowed. an uncaught syntax error is raised.
Javascript
<script> var a bc = "abc" ; console.log(a bc); </script> |
Output:
Example 3: Variable names are case sensitive. The variable’s names are case sensitive that means uppercase letters like ‘A’ and lowercase letters like ‘a’ are treated differently.
Javascript
<script> // Enabling strict mode "use strict" ; // Defining variables of different cases var abc = "bcd" ; var ABC = "efg" ; console.log(abc); console.log(ABC); console.log(abc == ABC); </script> |
Output:
Example 4: Using reserved words. When we use reserved words to name variables, exceptions are raised. In the below example we use the reserved word “class” and an exception is raised. unexpected token “class”.
HTML
< script > var class = "class"; console.log(class); </ script > |
Output:
A few more conventions for good practices:
- It is good to decide on a case and continue it throughout the code. ex: camel case. code looks elegant and proper.
- Name your variable with more than one word. This will verify that the name of your variable is accurate.
- It is suggested not to use variable names that are too short. They do not make proper sense.