π Introduction
Variables are the backbone of any programming language, including JavaScript. A variable name not only represents data but also improves code readability. JavaScript does not enforce strict naming rules beyond certain syntactic restrictions, but developers follow conventions to maintain clarity and professionalism.
π General Rules for Naming Variables
Start with a letter, underscore (_), or dollar sign ($):
let name = "John"; β
let _count = 10; β
let $price = 99.99; β
let 1name = "Error"; β
Use letters, numbers, underscores, or dollar signs after the first character:
let user1 = "Alice"; β
let total_amount = 500; β
Case sensitivity:
let age = 25;
let Age = 30;
console.log(age); // 25
console.log(Age); // 30
Avoid reserved keywords:
let return = 10; // β Error
β¨ Naming Conventions in JavaScript
1οΈβ£ Camel Case (Recommended)
The most commonly used convention in JavaScript.
let firstName = "John";
let totalAmount = 100;
2οΈβ£ Pascal Case (Used for Classes & Constructors)
class Car {
constructor(brand) {
this.brand = brand;
}
}
let myCar = new Car("Toyota");
3οΈβ£ Snake Case (Less Common in JS, more in databases)
let user_name = "Alice";
let total_amount = 500;
π‘ Best Practices for Variable Naming
Use descriptive names:
let x = 50; // β Bad
let userAge = 50; // β
Good
Boolean variables should start with is
, has
, or can
:
let isLoggedIn = true;
let hasAccess = false;
let canEdit = true;
Constants should be in UPPERCASE (when values donβt change):
const MAX_USERS = 100;
const PI = 3.14159;
Avoid single-letter names (except loop counters):
for (let i = 0; i < 5; i++) {
console.log(i);
}
Keep names consistent and meaningful across the project:
let userName;
let userEmail;
let userPassword;
π Common Mistakes to Avoid
Mixing conventions (userName
vs user_name
).
Using vague names like data
, info
, or stuff
.
Using overly long names.
Using numbers at the beginning.
π Summary
Naming conventions in JavaScript help developers write clean and professional code. By following rules like starting with letters/underscore/dollar, avoiding reserved keywords, and adopting camelCase, you ensure your code is readable and maintainable. Always prefer descriptive, consistent, and meaningful names to make your code self-explanatory.