Input Name

camelCase

Variables, functions, methods, object properties

PascalCase

Classes, interfaces, types, React components

CONSTANT_CASE

Global constants, enum values, config values

JavaScript Naming Conventions Explained

JavaScript follows specific naming conventions that make code more readable, maintainable, and consistent across projects. Understanding when to use each convention is crucial for writing professional JavaScript and TypeScript code.

camelCase - Variables and Functions

camelCase is the standard for most JavaScript identifiers. The first word is lowercase, and subsequent words are capitalized.

When to Use camelCase

  • Variables: let userName = 'Alice';
  • Functions: function getUserData() {}
  • Methods: user.getName()
  • Object Properties: { firstName: 'John', lastName: 'Doe' }
  • Parameters: function greet(userName, userAge) {}

Examples

// Variables
let currentUser = null;
let totalCount = 0;
let isAuthenticated = false;

// Functions
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

function fetchUserData(userId) {
  return api.get(`/users/${userId}`);
}

// Methods
class ShoppingCart {
  addItem(item) {
    this.items.push(item);
  }
  
  getTotal() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }
}

PascalCase - Classes and Types

PascalCase (also called UpperCamelCase) capitalizes the first letter of every word, including the first. This convention is used for constructors, classes, and types.

When to Use PascalCase

  • Classes: class UserAccount {}
  • Constructor Functions: function Person(name) {}
  • React Components: function UserProfile() {}
  • TypeScript Interfaces: interface UserData {}
  • TypeScript Types: type ResponseData = {}
  • Enums: enum UserRole {}

Examples

// Classes
class UserAccount {
  constructor(username, email) {
    this.username = username;
    this.email = email;
  }
}

class DatabaseConnection {
  connect() { /* ... */ }
  disconnect() { /* ... */ }
}

// React Components
function UserProfile({ user }) {
  return <div>{user.name}</div>;
}

function ShoppingCart({ items }) {
  return <ul>{items.map(item => <li>{item.name}</li>)}</ul>;
}

// TypeScript
interface UserData {
  id: number;
  name: string;
  email: string;
}

type ApiResponse<T> = {
  data: T;
  error: string | null;
};

SCREAMING_SNAKE_CASE - Constants

Constants that never change use all uppercase letters with underscores separating words. This makes them stand out in code.

When to Use SCREAMING_SNAKE_CASE

  • Global Constants: const MAX_USERS = 100;
  • Configuration Values: const API_BASE_URL = '...';
  • Mathematical Constants: const PI = 3.14159;
  • Enum Values: const STATUS = { PENDING: 'pending' }
  • Magic Numbers: const DEFAULT_TIMEOUT = 5000;

Examples

// Configuration
const API_BASE_URL = 'https://api.example.com';
const MAX_RETRY_ATTEMPTS = 3;
const DEFAULT_PAGE_SIZE = 20;
const CACHE_EXPIRATION_TIME = 3600;

// Status/State Constants
const STATUS = {
  PENDING: 'pending',
  APPROVED: 'approved',
  REJECTED: 'rejected'
};

const ERROR_CODES = {
  UNAUTHORIZED: 401,
  NOT_FOUND: 404,
  SERVER_ERROR: 500
};

// Feature Flags
const FEATURE_FLAGS = {
  ENABLE_NEW_UI: true,
  ENABLE_DARK_MODE: false
};

Special Naming Patterns

Boolean Variables

Boolean variables should be prefixed with words that indicate true/false states:

  • is...: isLoading, isValid, isAuthenticated
  • has...: hasError, hasPermission, hasChildren
  • can...: canEdit, canDelete, canAccess
  • should...: shouldRender, shouldUpdate, shouldCache

Private Properties (Convention)

Although JavaScript now has private class fields (#field), the convention of prefixing with underscore is still common:

class User {
  constructor(name) {
    this._name = name;  // Convention: underscore prefix for "private"
  }
  
  // Modern private field (truly private)
  #privateData = null;
}

Temporary Variables

For temporary or iterator variables, single letters are acceptable:

  • i, j, k - loop counters
  • e, err - error objects
  • cb - callback functions (though full name is better)

ESLint Rules for Naming

ESLint can enforce naming conventions automatically. Here are common rules:

// .eslintrc.js
module.exports = {
  rules: {
    // Enforce camelCase for variables and functions
    'camelcase': ['error', { properties: 'always' }],
    
    // Enforce PascalCase for classes
    'new-cap': ['error', { newIsCap: true, capIsNew: false }],
    
    // Require const for variables that are never reassigned
    'prefer-const': 'error',
    
    // Disallow dangling underscores (except specific cases)
    'no-underscore-dangle': ['error', { 
      allowAfterThis: true,
      allowAfterSuper: true 
    }]
  }
};

Common Mistakes to Avoid

Mistake #1: Mixing Conventions

let User_Name = 'Alice'; (mixing PascalCase and snake_case)

let userName = 'Alice';

Mistake #2: Starting Variables with Uppercase

let TotalCount = 0; (looks like a class)

let totalCount = 0;

Mistake #3: Using snake_case for Regular Variables

let user_name = 'Bob'; (Python style)

let userName = 'Bob';

Mistake #4: Not Using SCREAMING_SNAKE_CASE for True Constants

const maxUsers = 100; (looks mutable)

const MAX_USERS = 100;

TypeScript-Specific Conventions

TypeScript adds additional naming conventions:

Interfaces vs Types

// Both use PascalCase
interface User {
  id: number;
  name: string;
}

type UserId = number;
type ApiResponse = { data: any; error: string };

Generics

Generic type parameters typically use single uppercase letters or PascalCase names:

// Single letter (common for simple cases)
function identity<T>(arg: T): T {
  return arg;
}

// Descriptive names (better for complex cases)
function merge<TFirst, TSecond>(first: TFirst, second: TSecond) {
  return { ...first, ...second };
}

Enum Members

Enum members typically use PascalCase or SCREAMING_SNAKE_CASE:

// PascalCase (modern preference)
enum UserRole {
  Admin = 'admin',
  User = 'user',
  Guest = 'guest'
}

// SCREAMING_SNAKE_CASE (traditional)
enum HttpStatus {
  OK = 200,
  NOT_FOUND = 404,
  SERVER_ERROR = 500
}

React and JSX Conventions

React has specific conventions layered on top of JavaScript's:

Component Names

Always use PascalCase for React components:

// Function components
function UserProfile() { /* ... */ }
function ShoppingCart() { /* ... */ }

// Class components
class UserDashboard extends React.Component { /* ... */ }

Prop Names

Use camelCase for prop names:

function UserCard({ userName, userAge, isActive }) {
  return <div>{userName}</div>;
}

<UserCard userName="Alice" userAge={30} isActive={true} />

Event Handlers

Prefix event handlers with "handle" or "on":

function MyComponent() {
  const handleClick = () => { /* ... */ };
  const handleSubmit = (e) => { /* ... */ };
  
  return (
    <button onClick={handleClick}>Click</button>
  );
}

Best Practices Summary

  • ✓ Use camelCase for variables, functions, and methods
  • ✓ Use PascalCase for classes, interfaces, types, and React components
  • ✓ Use SCREAMING_SNAKE_CASE for true constants
  • ✓ Prefix booleans with is/has/can/should
  • ✓ Be consistent within your codebase
  • ✓ Use meaningful, descriptive names
  • ✓ Avoid abbreviations unless widely understood (URL, API, HTTP)
  • ✓ Configure ESLint to enforce naming conventions