SECTION 1
Historical Context & Motivation
From the earliest days of computing, programmers realized that code is read far more often than it is written. When teams of developers work on the same project, inconsistent naming turns collaboration into a frustrating puzzle. Naming conventions — agreed-upon rules for how you name variables, functions, and other identifiers — emerged as a solution. In JavaScript specifically, the convention known as camelCase became the dominant standard, shaping how millions of developers write code every day.
1960s • Early Naming Struggles
ITMPRC. Readability suffered enormously, and programmers began seeking better approaches.1972 • C Language and snake_case
max_value). This made multi-word names readable for the first time.1991 • Java Standardizes camelCase
1995 • JavaScript Is Born
getElementById and addEventListener) cemented the pattern.2010s • Linters Enforce Conventions
The central question this lesson addresses is straightforward but critical: How should you name things in JavaScript so that your code is clear, consistent, and easy for others (and your future self) to understand? The answer lies in mastering a small set of conventions that the entire JavaScript community follows.
SECTION 2
Core Principles of Naming & Formatting
Good naming is not about following arbitrary rules — it is about communicating intent. When you read let x = 5; versus let studentAge = 5;, the second version tells you what the data means. The following principles guide every naming decision you will make in JavaScript.
Be Descriptive
totalPrice instead of tp. A reader should understand what a variable holds without hunting for context.Use camelCase for Variables & Functions
firstName, calculateGrade. This is the standard JavaScript convention for most identifiers.Use PascalCase for Classes
ShoppingCart, UserProfile. This visually distinguishes constructors from regular functions.Use SCREAMING_SNAKE_CASE for Constants
MAX_ATTEMPTS, API_BASE_URL. This signals "do not change this value."Be Consistent Throughout
user_name and userName in the same project confuses readers and introduces bugs.KEY TAKEAWAY
SECTION 3
Visual Guide to Naming Styles
The diagram below shows how the same multi-word phrase — "get user age" — gets formatted under each major naming convention used in programming. Notice how camelCase visually creates "humps" like a camel's back, which is where the name comes from.
Notice that each convention has a specific purpose. The style you choose immediately tells a reader what kind of identifier they are looking at. A variable called shoppingCart is clearly an instance or a plain value, while ShoppingCart signals a class that you would instantiate with new. This visual distinction makes code self-documenting.
SECTION 4
How camelCase Works — Rules & Patterns
The mechanics of camelCase are simple, but the details matter. Understanding the precise rules helps you apply them automatically in every line of code you write.
Rule 1: Start with a Lowercase Letter
The first word of a camelCase identifier is always entirely lowercase. This distinguishes it from PascalCase, where the first letter is capitalized. For example, totalScore starts with a lowercase t, not an uppercase T.
Rule 2: Capitalize the First Letter of Each Subsequent Word
Every word after the first begins with a capital letter, and the remaining letters are lowercase. The phrase "number of students" becomes numberOfStudents. No spaces, hyphens, or underscores separate the words — the capital letters serve as the visual word boundaries.
Rule 3: Choose Meaningful Words
Conventions dictate the format, but you still choose the words. A well-named variable answers the question "what does this hold?" without requiring extra comments. Compare let d = new Date(); with let currentDate = new Date(); — the second version needs no explanation.
Common Patterns for Different Identifier Types
| Identifier Type | Convention | Example | Tip |
|---|---|---|---|
| Variable | camelCase (noun) | studentName | Use nouns that describe the stored data |
| Function | camelCase (verb + noun) | calculateAverage | Start with a verb: get, set, calculate, is, has |
| Boolean | camelCase (is/has prefix) | isLoggedIn | Prefix with is, has, can, or should |
| Array | camelCase (plural noun) | userNames | Use plural form to signal a collection |
| Class | PascalCase (noun) | GameCharacter | Capitalize every word including the first |
| Constant | SCREAMING_SNAKE_CASE | MAX_LIVES | All uppercase, underscores between words |
JavaScript naming conventions by identifier type
When to Use const vs. SCREAMING_SNAKE_CASE
const prevents reassignment, but not all const values use SCREAMING_SNAKE_CASE. Reserve the screaming style for hard-coded configuration values that are truly constant across your entire program, like const API_KEY = "abc123". Regular const variables that just happen not to be reassigned (like const user = getUser()) should still use camelCase.SECTION 5
Formatting Conventions Beyond Names
Naming is only half the story. Formatting conventions govern how your code is visually structured: indentation, spacing, brace placement, and line length. Consistent formatting makes code scannable at a glance, just like how consistent paragraph formatting makes an essay easier to read.
Key Formatting Rules in JavaScript
- ✓ Indentation: Use 2 spaces (most common in JavaScript) or 4 spaces — but pick one and use it everywhere. Never mix tabs and spaces.
- ✓ Semicolons: Always include semicolons at the end of statements. While JavaScript has automatic semicolon insertion, relying on it can cause subtle bugs.
- ✓ Braces: Place the opening brace on the same line as the statement (not on a new line). Always use braces with
if,for, andwhile— even for single-line bodies. - ✓ Spacing: Add spaces around operators (
x + y, notx+y), after commas, and after keywords likeifandfor. - ✓ Line length: Keep lines under 80–100 characters. Break long expressions across multiple lines for readability.
SECTION 6
Worked Example: Refactoring Bad Names
Let's walk through refactoring a piece of poorly named and formatted code into clean, conventional JavaScript. Imagine a classmate hands you this code and asks you to figure out what it does.
Refactoring a Grade Calculator
- 1
Step 1 — Read the Original Code
The original code looks like this:function f(a,b,c){var d=(a+b+c)/3;if(d>=90){return 'A'}else if(d>=80){return 'B'}else{return 'C'}}. This is a working function, but it is nearly impossible to understand at a glance. The function nameftells you nothing, and parametersa,b,ccould be anything. - 2
Step 2 — Rename the Function
Functions should start with a verb and describe what they do. Since this function calculates a letter grade, renameftocalculateLetterGrade. This follows camelCase (starts lowercase, capitalizes subsequent words) and reveals the function's purpose.function calculateLetterGrade(...) - 3
Step 3 — Rename the Parameters
The three parameters represent test scores, so rename them totestOneScore,testTwoScore, andtestThreeScore. Each name clearly describes the data it holds.calculateLetterGrade(testOneScore, testTwoScore, testThreeScore) - 4
Step 4 — Rename the Local Variable
The variabledholds the average. Rename it toaverageScoreand changevartoconstsince the value is never reassigned.const averageScore = (testOneScore + testTwoScore + testThreeScore) / 3; - 5
Step 5 — Apply Formatting Conventions
Finally, add proper indentation (2 spaces), spaces around operators, braces on the same line as keywords, and consistent line breaks. The result is clean, readable code that any JavaScript developer would recognize and understand immediately.Final refactored code:function calculateLetterGrade(testOneScore, testTwoScore, testThreeScore) { const averageScore = (testOneScore + testTwoScore + testThreeScore) / 3; if (averageScore >= 90) { return "A"; } else if (averageScore >= 80) { return "B"; } else { return "C"; } }
SECTION 7
Naming Conventions Across Languages
Different programming languages prefer different naming conventions. Understanding these differences helps you switch between languages without carrying incorrect habits. The table below shows the preferred convention for variables and functions in several popular languages.
| Language | Variable/Function Style | Example |
|---|---|---|
| JavaScript | camelCase | getUserName |
| Python | snake_case | get_user_name |
| Java | camelCase | getUserName |
| C# | PascalCase (methods) | GetUserName |
| Ruby | snake_case | get_user_name |
| CSS | kebab-case | user-name-input |
Preferred naming conventions for variables and functions across popular languages
KEY TAKEAWAY
What About kebab-case?
my-variable) in CSS class names and HTML attributes. JavaScript does not allow hyphens in identifier names because the minus sign (-) is interpreted as subtraction. So my-variable would be read as "my minus variable" — a syntax error or unexpected math operation.SECTION 8
Linters & Formatters — Automating Conventions
As your projects grow, manually enforcing conventions becomes impractical. This is where linters and formatters come in. These automated tools check your code for convention violations (linting) and automatically fix formatting issues (formatting), just like a spell-checker and grammar-checker work together in a word processor.
| Feature | ESLint (Linter) | Prettier (Formatter) |
|---|---|---|
| Purpose | Catches naming issues, logic bugs, and style violations | Automatically reformats code (indentation, spacing, line breaks) |
| camelCase enforcement | Yes — the camelcase rule flags violations | No — Prettier does not check names |
| Fixes automatically? | Some rules auto-fix; naming requires manual changes | Yes — reformats on save |
| Best used | For code quality, naming rules, and catching bugs | For consistent visual formatting across a team |
ESLint vs. Prettier — complementary tools for code quality
In professional development teams, ESLint and Prettier are typically used together. ESLint handles naming and logic rules, while Prettier handles visual formatting. Many code editors, like VS Code, integrate both tools so that your code is automatically checked and formatted every time you save a file. As you move into more advanced courses or begin contributing to open-source projects, you will encounter style guides — comprehensive documents (like the Airbnb JavaScript Style Guide or Google's JavaScript Style Guide) that define every convention a team follows. These style guides are then enforced through linter configurations.
Try It Now
.eslintrc.json file in your project root with {"rules": {"camelcase": "error"}} and ESLint will underline any non-camelCase variable names in red — instant feedback as you code!SECTION 9
Practice Problems
Question 1: CONCEPTUAL
x is generally a poor choice in JavaScript. Under what specific circumstance might a single-letter variable name be acceptable?Show answer
x is poor because it communicates nothing about what the variable holds — a reader must trace through the code to understand its purpose. Good names are descriptive and reveal intent (e.g., userAge instead of x). However, single-letter names are acceptable in very small scopes where the meaning is obvious, such as a loop counter (for (let i = 0; i < 10; i++)) or a mathematical coordinate where x and y are standard notation.Question 2: BASIC
Show answer
totalNumberOfItems — each word after the first is capitalized, no spaces or underscores. (b) isUserLoggedIn — the "is" prefix signals this is a boolean. (c) getStudentGradePointAverage — the "get" prefix signals this is a function that retrieves a value. (d) maximumRetryCount — alternatively maxRetryCount is acceptable since "max" is a widely understood abbreviation.Question 3: INTERMEDIATE
const Max_Speed = 120; var user_name = "Ada"; function GetAge(birth_year){ let Current_Year = 2025; return Current_Year-birth_year }Show answer
Max_Speed mixes PascalCase with underscores — should be MAX_SPEED (true constant) or maxSpeed (regular variable). (2) user_name uses snake_case — should be userName. (3) var should be const. (4) GetAge uses PascalCase but is a function, not a class — should be getAge. (5) birth_year uses snake_case — should be birthYear. (6) Current_Year mixes styles — should be currentYear. (7) Missing space around the minus operator. Corrected: const MAX_SPEED = 120; const userName = "Ada"; function getAge(birthYear) { const currentYear = 2025; return currentYear - birthYear; }Question 4: APPLIED
Show answer
function addTask(taskTitle, dueDate) — camelCase, starts with a verb, parameters describe what they hold. (b) function isTaskComplete(taskId) — the "is" prefix indicates a boolean return value, which is the standard convention for functions that return true or false. (c) class TodoItem — PascalCase because it is a class. You could also use class Task if simplicity is preferred. (d) const MAX_TASKS = 100; — SCREAMING_SNAKE_CASE because this is a true constant that will never change during the application's lifetime.Question 5: CRITICAL THINKING
Show answer
isPaymentProcessed immediately understands the variable's type (boolean) and meaning, whereas flag2 forces them to trace through the code, wasting valuable time. Second, consistent conventions reduce cognitive load during code reviews; reviewers can focus on logic and correctness instead of deciphering inconsistent styles. Third, studies in software engineering have shown that poorly named code significantly increases the rate of bugs because developers misinterpret the purpose of variables and functions. The small upfront cost of choosing good names pays for itself many times over in reduced debugging time and smoother collaboration.SUMMARY
Lesson Summary
Summary
JavaScript naming and formatting conventions form the foundation of readable, professional code. The primary convention is camelCase — starting with a lowercase letter and capitalizing each subsequent word — used for variables, functions, methods, and parameters. Classes and constructors use PascalCase, while true constants use SCREAMING_SNAKE_CASE. Good names are descriptive — they reveal intent without requiring comments.
Beyond naming, formatting conventions include consistent indentation (2 spaces), spacing around operators, same-line braces, and semicolons at statement ends. Tools like ESLint and Prettier automate enforcement, catching violations as you write. Mastering these conventions is not about memorizing rules — it is about building the habit of writing code that communicates clearly to every developer who reads it.