Rules of Naming Variables in JavaScript
There are few rules we need to follow when naming variables in JavaScript...
There are few rules we need to follow when naming variables in JavaScript:
- A variable name cannot be preceded by a
number
.
let 2years = 2022;
The above declaration will return an error because of the the variable name starts with a number.
Variable names can only be preceded by a letter
, underscore_
, or a dollar sign$
.
let year = 2022;
let _month = "February";
let $status = true;
- After the first letter, the rest of the variable name can contain
letters
,numbers
,underscores_
anddollar sign$
.
let years = 2022;
let _day3 = "Tuesday";
let second_month = "February";
let _day$ = 20;
Note: You can't use other characters like punctuation marks, spaces, symbols.
- JavaScript variables are case sensitive. This means variables written in different cases(Upper and lower cases) are treated as different variables. Example
let second_month = "February";
let Second_Month = "February";
Due to the difference in cases, second_month and Second_Month will be considered as different variable in JavaScript.
You can't use
JavaScript reserved words
as variable names. JavaScript reserved words are words that have special uses in JavaScript and can't be used when declaring variable names.Note: There is no limit to the length of the variable names in JavaScript. So, your variable name can be as long as you want. Use long and descriptive variable names, but don't make them too long as they will take so long to type and can be dangerous because, the longer the name the higher the possibility of you making typographical error.
That's it. Hope you found this article instructional. Kindly hit the reaction and share it.
To stay updated when I post, follow me on Twitter.