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
What are Variable Naming Conventions in JavaScript
While naming your variables in JavaScript, keep some rules in mind. The following are the variable naming conventions in JavaScript:
- 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.
Basic Naming Rules
Here are examples of valid and invalid variable names:
// Valid variable names var name; var _2name; var userName; var $element; var firstName123; // Invalid variable names - these will cause syntax errors // var 2name; // Cannot start with number // var break; // Reserved keyword // var first-name; // Hyphens not allowed
Case Sensitivity Example
var name = "John"; var Name = "Jane"; var NAME = "Bob"; console.log(name); // Different variables console.log(Name); console.log(NAME);
John Jane Bob
Common Naming Conventions
JavaScript developers follow these best practices:
-
camelCase: Start with lowercase, capitalize subsequent words (e.g.,
firstName,userEmail) -
Constants: Use UPPER_SNAKE_CASE for constants (e.g.,
MAX_SIZE,API_URL) -
Private variables: Start with underscore (e.g.,
_privateVar)
// Recommended naming conventions var firstName = "Alice"; // camelCase for variables var userAccountBalance = 1500; // camelCase for variables const MAX_USERS = 100; // UPPER_SNAKE_CASE for constants var _internalCounter = 0; // underscore for private/internal use console.log(firstName); console.log(MAX_USERS);
Alice 100
Reserved Keywords to Avoid
These keywords cannot be used as variable names:
// Reserved keywords - avoid these break, case, catch, class, const, continue, debugger, default, delete, do, else, export, extends, finally, for, function, if, import, in, instanceof, let, new, return, super, switch, this, throw, try, typeof, var, void, while, with, yield
Conclusion
Follow JavaScript naming rules: start with letter/underscore, avoid numbers at start, and don't use reserved keywords. Use camelCase for readability and consistency in your code.
Advertisements
