Variable Naming Rules
The Rules of Naming
When you create a variable in JavaScript, you get to choose its name! However, JavaScript has strict rules about what you can and cannot name a variable.
1. Allowed Characters
Variable names can only contain:
- Letters (a-z, A-Z)
- Numbers (0-9)
- Underscores (
_) - Dollar signs (
$)
2. Must Not Start With a Number
A variable name can contain a number, but it cannot start with one.
let player1 = "Himanshu"; // Valid
// let 1player = "Himanshu"; // Invalid - throws an error!
3. Case Sensitivity
JavaScript is strictly case-sensitive. This means myAge, myage, and MYAGE are treated as three completely different variables.
4. No Reserved Keywords
You cannot use JavaScript's built-in keywords as variable names. For example, you cannot name a variable let, if, function, or return.
Best Practices (Conventions)
While the rules above are mandatory, developers also follow conventions (best practices) to make code readable:
- Camel Case: The most common naming convention in JavaScript. The first word is lowercase, and every subsequent word starts with an uppercase letter.
- Example:
firstName,totalPriceOfItems.
- Example:
- Descriptive Names: Always use names that describe the data. Use
let userAge = 25;instead oflet x = 25;. It makes your code self-documenting!
💡 Himanshu's Tip:
Get into the habit of using camelCase immediately! It is the undisputed industry standard for JavaScript. If you go to a technical interview and write let user_age, the interviewer will immediately know you might be primarily a Python developer.
Interview Questions
- Can a JavaScript variable name start with a number?
- Are
myVariableandmyvariableconsidered the same in JavaScript? Why or why not? - What is camelCase formatting?