Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to name variables in JavaScript?
Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
While naming your variables in JavaScript, keep the following rules in mind.
Variable Naming Rules
- You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
- JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
- JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
Valid Variable Names
// Valid variable names let userName = "John"; let _score = 100; let $price = 29.99; let age2 = 25; let firstName = "Alice"; console.log(userName); console.log(_score); console.log($price);
John 100 29.99
Invalid Variable Names
// These will cause syntax errors let 2age = 25; // Cannot start with number let for = "loop"; // Cannot use reserved keyword let my-name = "Bob"; // Hyphens not allowed let my name = "Bob"; // Spaces not allowed
Case Sensitivity Example
let name = "lowercase"; let Name = "Capitalized"; let NAME = "UPPERCASE"; console.log(name); // Different variable console.log(Name); // Different variable console.log(NAME); // Different variable
lowercase Capitalized UPPERCASE
Best Practices
- Use camelCase for multi-word variables:
firstName,totalScore - Choose descriptive names:
userAgeinstead ofa - Use const for values that won't change:
const PI = 3.14159 - Avoid abbreviations that aren't clear:
userNameinstead ofusrNm
Conclusion
Follow JavaScript's naming rules and use descriptive, camelCase names for better code readability. Avoid reserved keywords and numbers at the start of variable names.
Advertisements
