JavaScript Naming Conventions
The complete guide to camelCase, PascalCase, and UPPER_CASE in JavaScript
JavaScript Naming at a Glance:
- Variables & Functions: camelCase →
getUserData - Classes & Components: PascalCase →
UserProfile - Constants: UPPER_SNAKE_CASE →
MAX_RETRY_COUNT - Private: Prefix with underscore →
_privateMethod
Why Naming Conventions Matter
Consistent naming conventions make your JavaScript code more readable, maintainable, and professional. They help developers understand the purpose and scope of identifiers at a glance, reduce bugs, and improve collaboration in teams.
1. camelCase for Variables and Functions
Use camelCase (first word lowercase, subsequent words capitalized) for variable names, function names, and object properties.
Variables
// ✅ Good
const userName = "John Doe";
const userAge = 25;
const isLoggedIn = true;
const shoppingCartItems = [];
// ❌ Bad
const user_name = "John"; // snake_case (Python style)
const UserName = "John"; // PascalCase (for classes)
const username = "John"; // lacks clarity for multi-wordFunctions
// ✅ Good
function getUserById(id) {
return users.find(user => user.id === id);
}
function calculateTotalPrice(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
const sendEmailNotification = (email, message) => {
// Send email
};
// ❌ Bad
function get_user_by_id(id) { } // snake_case
function GetUserById(id) { } // PascalCase
function getuserbyid(id) { } // no word separationBoolean Variables (Special Naming)
// Prefix with is, has, can, should
const isActive = true;
const hasPermission = false;
const canEdit = true;
const shouldValidate = false;
// Arrays: use plural nouns
const users = [];
const activeUsers = [];
const completedTasks = [];2. PascalCase for Classes and Constructors
Use PascalCase (every word starts with uppercase) for class names, constructor functions, and React components.
Classes
// ✅ Good
class UserAccount {
constructor(username, email) {
this.username = username;
this.email = email;
}
getUserInfo() {
return `${this.username} (${this.email})`;
}
}
class ShoppingCart {
// Class implementation
}
class PaymentProcessor {
// Class implementation
}
// ❌ Bad
class userAccount { } // camelCase
class user_account { } // snake_case
class USERACCOUNT { } // all capsReact Components
// ✅ Good
function UserProfile({ user }) {
return <div>{user.name}</div>;
}
const NavigationBar = () => {
return <nav>...</nav>;
};
class ShoppingCartItem extends React.Component {
render() {
return <div>...</div>;
}
}
// ❌ Bad
function userProfile() { } // camelCase
const navigation_bar = () => {} // snake_case3. UPPER_SNAKE_CASE for Constants
Use UPPER_SNAKE_CASE for true constants (values that never change) and configuration values.
// ✅ Good
const MAX_RETRY_COUNT = 3;
const API_BASE_URL = "https://api.example.com";
const DEFAULT_TIMEOUT = 5000;
const HTTP_STATUS_OK = 200;
const USER_ROLES = {
ADMIN: "admin",
USER: "user",
GUEST: "guest"
};
// ❌ Bad
const maxRetryCount = 3; // camelCase for constant
const Max_Retry_Count = 3; // mixed case
const MAXRETRYCOUNT = 3; // no separationWhen NOT to Use UPPER_CASE
// These are NOT constants (can be reassigned)
let currentUser = null; // ✅ camelCase
let itemCount = 0; // ✅ camelCase
// Configuration object (not a constant value)
const config = { // ✅ camelCase
apiUrl: "https://...",
timeout: 5000
};4. Private Variables and Methods
Prefix private properties with an underscore (_) or use the # private field syntax (ES2022+).
// Convention: underscore prefix
class BankAccount {
constructor(balance) {
this._balance = balance; // "private" by convention
}
_validateAmount(amount) { // "private" method
return amount > 0;
}
deposit(amount) {
if (this._validateAmount(amount)) {
this._balance += amount;
}
}
}
// ES2022+ true private fields
class ModernBankAccount {
#balance = 0; // Truly private
#validateAmount(amount) { // Truly private
return amount > 0;
}
deposit(amount) {
if (this.#validateAmount(amount)) {
this.#balance += amount;
}
}
}5. Special Cases
Abbreviations and Acronyms
// Treat acronyms as single words
const userId = 123; // ✅ Not userID
const apiUrl = "..."; // ✅ Not apiURL or APIURL
const httpRequest = {}; // ✅ Not HTTPRequest
// Exception: Well-known acronyms in classes
class HTMLParser { } // ✅ Acceptable
class XMLHttpRequest { } // ✅ Standard API
class URLSearchParams { } // ✅ Standard APINumbers in Names
// Numbers are treated as lowercase
const base64Encode = (str) => {}; // ✅
const mp3Player = {}; // ✅
const level2Cache = {}; // ✅
// ❌ Avoid
const base64ENCODE = () => {};
const MP3Player = {};Event Handlers
// Prefix with 'handle' or 'on'
function handleClick(event) { }
function handleSubmit(event) { }
const onUserLogin = () => { };
const onFormChange = () => { };
// React components
<button onClick={handleClick}>
<form onSubmit={handleSubmit}>6. File Naming Conventions
Module Files
- camelCase:
userService.js,apiClient.js - kebab-case:
user-service.js,api-client.js(also common)
React Components
- PascalCase:
UserProfile.jsx,NavigationBar.jsx
Configuration Files
- kebab-case or dot-notation:
webpack.config.js,.eslintrc.js
7. TypeScript Specific Conventions
// Interfaces and Types: PascalCase
interface UserData {
id: number;
name: string;
}
type UserRole = "admin" | "user" | "guest";
// Type parameters: Single uppercase letter or PascalCase
function identity<T>(arg: T): T {
return arg;
}
class Container<TItem> {
items: TItem[] = [];
}
// Enums: PascalCase for enum name, UPPER_CASE for values
enum UserStatus {
ACTIVE = "ACTIVE",
INACTIVE = "INACTIVE",
PENDING = "PENDING"
}8. ESLint Configuration
Enforce naming conventions automatically with ESLint:
// .eslintrc.js
module.exports = {
rules: {
"camelcase": ["error", {
"properties": "always"
}],
"@typescript-eslint/naming-convention": [
"error",
{
"selector": "variable",
"format": ["camelCase", "UPPER_CASE"]
},
{
"selector": "function",
"format": ["camelCase"]
},
{
"selector": "typeLike",
"format": ["PascalCase"]
}
]
}
};9. Common Mistakes to Avoid
- ❌ Mixing conventions:
get_UserData - ❌ Using single-letter variables (except in loops):
const d = new Date() - ❌ Abbreviating unnecessarily:
usrNminstead ofuserName - ❌ Using Hungarian notation:
strUserName,intAge - ❌ Using reserved words:
const class = "..."
10. Best Practices Summary
- Be descriptive:
calculateTotalPriceis better thancalc - Be consistent: Pick one style and stick with it across your codebase
- Follow the standard: camelCase for most things, PascalCase for classes
- Use meaningful names:
isUserActiveis clearer thanactive - Avoid magic numbers: Use named constants instead
Quick Reference Table
| Type | Convention | Example |
|---|---|---|
| Variables | camelCase | userName |
| Functions | camelCase | getUserData() |
| Classes | PascalCase | UserAccount |
| Constants | UPPER_SNAKE_CASE | MAX_RETRY_COUNT |
| Private | _camelCase or #private | _privateMethod |
| React Components | PascalCase | UserProfile |
Need to Convert Text?
Use our free converter to instantly transform text between different cases:
Conclusion
JavaScript naming conventions are straightforward: use camelCase for variables and functions, PascalCase for classes and components, and UPPER_SNAKE_CASE for constants. Following these conventions makes your code more professional, readable, and maintainable. Use ESLint to enforce consistency automatically and always prioritize clarity over brevity.