Naming Conventions in Programming: camelCase, snake_case, kebab-case and More
By Álvaro G.V. · Updated
Should it be myVariable, my_variable or my-variable? Short answer: use camelCase for variables and functions in JavaScript, TypeScript, Java and Go; snake_case in Python, Ruby, Rust and SQL; PascalCase for classes and types almost everywhere; kebab-case for URLs, CSS classes and file names on the web; and SCREAMING_SNAKE_CASE for constants and environment variables. The rest of this guide covers the details per language, the edge cases (acronyms, digits, database identifiers) and how to convert between layers without bugs.
To convert an identifier between styles, paste it into the text case converter, which handles camelCase, snake_case, kebab-case and more.
The Six Main Naming Conventions
All naming conventions are strategies for combining multiple words into a single identifier. Programming languages require identifiers without spaces, so conventions emerged to make multi-word names readable.
| Convention | Example | Also known as |
|---|---|---|
| camelCase | getUserById | Lower camel case, dromedary case |
| PascalCase | UserProfile | Upper camel case, StudlyCase |
| snake_case | user_profile | Underscore case, pothole case |
| kebab-case | user-profile | Hyphen case, lisp-case, spinal-case |
| SCREAMING_SNAKE | MAX_RETRY_COUNT | All caps, constant case, macro case |
| dot.case | app.server.port | Dot notation |
Convention by Language
JavaScript and TypeScript
// Variables and functions → camelCase
const userCount = 42;
function getUserById(id: string) {}
// Classes and interfaces → PascalCase
class UserService {}
interface UserProfile {}
type ApiResponse = {}
// Constants → SCREAMING_SNAKE_CASE
const MAX_RETRIES = 3;
const API_BASE_URL = "https://api.example.com";
// React components → PascalCase (required)
function UserCard({ user }: Props) {}
// CSS class names (via Tailwind/CSS Modules) → kebab-case
// .user-card, .nav-link, .primary-buttonPython
# Variables and functions → snake_case
user_count = 42
def get_user_by_id(user_id: str): ...
# Classes → PascalCase
class UserService:
pass
# Constants → SCREAMING_SNAKE_CASE
MAX_RETRIES = 3
DATABASE_URL = "postgresql://..."
# Private/internal → leading underscore
def _internal_helper(): ...
self._private_attr = True
# "Name mangling" (truly private) → double underscore
self.__really_private = TrueGo
// Exported (public) identifiers → PascalCase
type UserProfile struct {}
func GetUserByID(id string) {}
// Unexported (package-private) → camelCase
type userCache struct {}
func getUserFromCache(id string) {}
// Acronyms stay fully capitalized (Go convention)
// ID not Id, URL not Url, HTTP not Http
func ParseHTTPResponse(r *http.Response) {}
type UserID stringJava and Kotlin
// Variables and methods → camelCase
int userCount = 42;
public User getUserById(String id) {}
// Classes and interfaces → PascalCase
public class UserService {}
public interface UserRepository {}
// Constants → SCREAMING_SNAKE_CASE
public static final int MAX_RETRIES = 3;
public static final String API_URL = "...";
// Packages → lowercase (no separators)
package com.example.userservice;CSS and HTML
/* CSS class names → kebab-case (universal convention) */
.user-card {}
.nav-link:hover {}
.primary-button--disabled {}
/* CSS custom properties (variables) → kebab-case */
:root {
--color-primary: #6366f1;
--font-size-base: 1rem;
}
<!-- HTML attributes → kebab-case -->
<div data-user-id="123" aria-label="User profile"></div>
<my-custom-element></my-custom-element>SQL and Databases
Naming is only half of readable SQL; SQL formatting best practices covers keyword casing, indentation and aliases.
-- PostgreSQL → snake_case (idiomatic)
CREATE TABLE user_profiles (
user_id UUID PRIMARY KEY,
first_name TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Stored procedures → snake_case
CREATE FUNCTION get_user_by_email(p_email TEXT) ...Rust
// Variables, functions, modules, crates → snake_case
let user_count = 42;
fn get_user_by_id(id: &str) {}
// Types, traits, enum variants → PascalCase (UpperCamelCase)
struct UserProfile;
enum Status { Active, Suspended }
// Constants and statics → SCREAMING_SNAKE_CASE
const MAX_RETRIES: u32 = 3;Rust is unusual in that the compiler enforces this: let userCount = 1; compiles but emits a non_snake_case warning.
Convention by Context
Beyond language conventions, context determines naming style:
- Environment variables →
SCREAMING_SNAKE_CASEuniversally:DATABASE_URL,JWT_SECRET - URL slugs and routes →
kebab-case:/user-profile,/api/v1/user-tokens(see REST API URL design) - JSON API keys →
camelCase(JavaScript convention) orsnake_case(Python/Ruby APIs): pick one and be consistent - File names → depends on OS and language:
kebab-casefor web assets,PascalCasefor React components,snake_casefor Python modules - Config file keys →
snake_casein YAML,camelCasein JSON,kebab-casein TOML - Package/module names →
kebab-casein npm (my-package),snake_casein Python (my_module)
Acronyms and Initialisms
Acronyms are where style guides disagree most. Pick one rule and apply it everywhere:
| Style guide | Rule | Example |
|---|---|---|
| Go (Effective Go, code review comments) | Keep initialisms in one case | userID, ServeHTTP, parseURL |
| Google JavaScript and Java style | Treat acronyms as words | loadHttpUrl, XmlHttpRequest, userId |
| .NET design guidelines | Two letters stay upper, three or more are Pascal-cased | IOStream, HtmlButton, XmlReader |
Treating acronyms as words is the safer default outside Go, because automated converters can only split a run of capitals by guessing. That is the root of most case-conversion bugs.
Converting Between Cases: Worked Example and Edge Cases
Most converters, including ORMs and JSON serializers, first split an identifier into words and then join them in the target style. A typical splitter:
function words(id) {
return id
.replace(/([a-z0-9])([A-Z])/g, "$1 $2") // userId → user Id
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") // HTTPServer → HTTP Server
.split(/[\s_\-.]+/)
.filter(Boolean)
.map((w) => w.toLowerCase());
}
const snake = (id) => words(id).join("_");
const camel = (id) =>
words(id).map((w, i) => (i ? w[0].toUpperCase() + w.slice(1) : w)).join("");Run real identifiers through it and the edge cases show up immediately:
| Input | snake(input) | camel(snake(input)) | Problem |
|---|---|---|---|
userId | user_id | userId | None: round-trips cleanly |
parseHTTPResponse | parse_http_response | parseHttpResponse | Round trip changes the name |
userID | user_id | userId | Same: ID comes back as Id |
getUserIDs | get_user_i_ds | getUserIDs | Plural acronym splits in the wrong place |
iOSVersion | i_os_version | iOsVersion | Brand casing cannot be inferred |
base64Encode | base64_encode | base64Encode | Fine here; splitters that ignore digits produce base64encode |
The practical fix is to avoid relying on round trips: write acronyms as words (userIds, parseHttpResponse) and, where the mapping matters, declare it explicitly instead of letting a converter guess. You can check how an identifier splits with the text case converter.
Mapping Names Between Layers
Database columns in snake_case, JSON in camelCase and Go structs in PascalCase is normal. Declare the mapping once at each boundary:
// Prisma: camelCase in TypeScript, snake_case in PostgreSQL
model User {
id Int @id
createdAt DateTime @map("created_at")
@@map("users")
}
// Go: exported field, snake_case JSON key
type User struct {
CreatedAt time.Time `json:"created_at"`
}# Pydantic v2: snake_case in Python, camelCase in JSON
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
class User(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
created_at: str
User.model_validate({"createdAt": "2026-10-19"}).model_dump(by_alias=True)
# {'createdAt': '2026-10-19'}Why snake_case in PostgreSQL is not just taste
PostgreSQL folds unquoted identifiers to lower case. CREATE TABLE UserProfiles (createdAt timestamptz) creates a table userprofiles with a column createdat. If a tool quotes the names instead ("createdAt"), the column keeps its capital letter and every hand-written query must quote it too: SELECT createdAt FROM users fails with column "createdat" does not exist. snake_case names never need quoting. (MySQL is the opposite trap: whether table names are case-sensitive depends on the server's operating system and lower_case_table_names.)
Common Naming Mistakes
- Booleans without a question form.
opencould be a verb or a state;isOpen,hasAccess,canEditcannot. - Units missing from numbers.
timeout = 30invites a seconds-versus-milliseconds bug;timeoutMsortimeout_secondsdoes not. - Mixing conventions in one JSON API.
userIdnext tocreated_atforces every client to special-case fields. - Case-only differences in file names.
UserCard.tsxanduserCard.tsxare the same file on default macOS and Windows file systems but different files on Linux, so an import that works locally can fail in CI. Renaming only the case needsgit mv, because Git on a case-insensitive file system may not notice. - Abbreviations nobody shares.
usrCntsaves four characters and costs every reader a moment. Spell words out unless the abbreviation is universal (id,url,db).
Enforcing Conventions With Linters
Write the rules down where a machine checks them, so code review doesn't have to:
// eslint.config.js (typescript-eslint)
rules: {
"@typescript-eslint/naming-convention": [
"error",
{ selector: "variableLike", format: ["camelCase", "UPPER_CASE"] },
{ selector: "typeLike", format: ["PascalCase"] },
],
}In Python, Ruff's N rules (pep8-naming) flag non-snake_case functions and non-PascalCase classes; in Go, golangci-lint with revive reports initialisms such as Id that should be ID.
Why Consistency Beats Correctness
In a greenfield project, pick one convention per context and enforce it with a linter (ESLint, Pylint, golangci-lint). In an existing codebase, follow whatever is already there — a consistent snake_case codebase is better than a mixed camelCase/snake_case one, even if camelCase would technically be "more idiomatic."
Use the Text Case Converter to quickly transform identifiers between conventions — useful when translating database column names to API response keys, or when copying code between languages.
Frequently Asked Questions
Does naming convention affect performance?▾
No, naming conventions have zero effect on runtime performance. The compiler or interpreter treats myVariable and my_variable identically from an execution standpoint. Conventions exist entirely for human readability, team consistency, and tool interoperability (linters, code generators, ORMs that map column names to property names). Follow the convention of your language and codebase.
What happens when different layers of a stack use different conventions?▾
This is common and expected — a PostgreSQL database uses snake_case columns, a JavaScript frontend uses camelCase properties, and a REST API returns JSON. The mapping layer (ORM, JSON serializer) handles the conversion automatically. In JavaScript, libraries like humps or axios-case-converter can auto-transform snake_case API responses to camelCase objects. In Python, Pydantic's alias_generator handles this. Agreeing on a convention per layer and automating the transformation is better than forcing one convention everywhere.
What is Hungarian notation and should I use it?▾
Hungarian notation prefixes variable names with type information: strName, intCount, bIsValid. It was popular in 1980s-90s C programming when IDEs had no type inference. Modern languages have static types, type inference, and IDE tooltips that make the prefix redundant and verbose. Most modern style guides (Google, Microsoft, Airbnb) explicitly discourage it. Avoid it in new code — let the type system and meaningful names carry the type information.
Related guides
.env Files and Environment Variables Explained
Environment variables and .env files are how modern applications manage configuration across environments. Learn how they work, how to use dotenv, and how to keep secrets out of your codebase.
SQL Formatting Best Practices: Write SQL That's Easy to Read
Consistently formatted SQL is easier to read, review, and debug. Learn the conventions used by professional developers: keyword casing, indentation, JOIN formatting, subqueries, and more.
REST API Design Best Practices: A Practical Guide
The conventions that make REST APIs intuitive and consistent. Covers URL design, HTTP methods, status codes, versioning, pagination, and error responses.
Regex Cheat Sheet for JavaScript Developers
Anchors, quantifiers, character classes, flags, named groups, lookaheads, and copy-paste patterns for email, URL, date, and more — with JavaScript method examples.