Rules for creating JavaScript Variables!
Naming Conventions for JavaScript Variables
There are some important rules to follow when naming variables in JavaScript:
Variable names can only consist of letters, numbers, underscores (
_
) and dollar signs ($
).Variable names must start with a letter, underscore or dollar sign. They cannot start with a number.
Variable names are case-sensitive.
myVariable
andMyVariable
are two different variables.It's good practice to use camelCase for variable names, where the first word is lowercase and proceeding words start with an uppercase letter.
Avoid using JavaScript reserved keywords as variable names.
Use meaningful names that describe the purpose of the variable.
Some examples of good variable names:
let firstName;
let userAge;
let $userName;
let _privateVariable;
Here are some bad variable names:
let 5years; // Cannot start with a number
let name; // Too generic
let var; // 'var' is a reserved keyword
It's also a good practice to declare variables at the top of your code using let
or const
:
let firstName;
let lastName;
firstName = 'John';
lastName = 'Doe';
As much as possible, use const
for variables that will never be reassigned:
const PI = 3.14;
Conclusion-
Hope this helps! If you like this information and want such information in future then follow and subscribe to my newsletter. Let me know if you have any other questions.