JavaScript • Software Craft and Communication

Naming & Formatting Conventions — Follow consistent naming and formatting conventions (camelCase)

Well-chosen names and consistent formatting make your JavaScript code readable, maintainable, and professional.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 5 figures

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

Early languages like FORTRAN and COBOL had strict character limits, forcing cryptic names like ITMPRC. Readability suffered enormously, and programmers began seeking better approaches.

1972 • C Language and snake_case

The C programming language popularized snake_case — using underscores to separate words (e.g., max_value). This made multi-word names readable for the first time.

1991 • Java Standardizes camelCase

Sun Microsystems published the Java Code Conventions, formally recommending camelCase for variables and methods. This influenced many later languages, including JavaScript.

1995 • JavaScript Is Born

Brendan Eich created JavaScript in just ten days. The language inherited camelCase conventions from Java, and its built-in APIs (like getElementById and addEventListener) cemented the pattern.

2010s • Linters Enforce Conventions

Tools like ESLint and Prettier automate convention enforcement, flagging inconsistent naming and auto-formatting code. Consistent style became a non-negotiable expectation in professional development.

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.

1

Be Descriptive

Names should reveal purpose. Use totalPrice instead of tp. A reader should understand what a variable holds without hunting for context.
2

Use camelCase for Variables & Functions

Start with a lowercase letter and capitalize each subsequent word: firstName, calculateGrade. This is the standard JavaScript convention for most identifiers.
3

Use PascalCase for Classes

Class names capitalize every word, including the first: ShoppingCart, UserProfile. This visually distinguishes constructors from regular functions.
4

Use SCREAMING_SNAKE_CASE for Constants

True constants — values that never change — use all uppercase with underscores: MAX_ATTEMPTS, API_BASE_URL. This signals "do not change this value."
5

Be Consistent Throughout

Pick one style per category and stick with it. Mixing user_name and userName in the same project confuses readers and introduces bugs.
✦

KEY TAKEAWAY

Think of naming conventions like road signs. Imagine if every city used different shapes and colors for stop signs — driving would be chaos. Similarly, when every JavaScript developer uses camelCase for variables and functions, PascalCase for classes, and SCREAMING_SNAKE_CASE for constants, everyone can read and navigate the code quickly.

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.

Naming Convention ComparisonThe phrase "get user age" formatted four wayscamelCasegetUserAgeVariables, functions, methods, parametersJSPascalCaseGetUserAgeClasses, constructors, React componentsJSSCREAMING_SNAKE_CASEGET_USER_AGETrue constants, configuration valuessnake_case (not standard JS)get_user_ageCommon in Python, Ruby — avoid in JavaScript
The four major naming conventions compared side by side. In JavaScript, camelCase (top row, cyan border) is the default for most identifiers. PascalCase is reserved for classes and constructors. SCREAMING_SNAKE_CASE marks true constants. The dashed row (snake_case) is not typical in JavaScript projects.

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 TypeConventionExampleTip
VariablecamelCase (noun)studentNameUse nouns that describe the stored data
FunctioncamelCase (verb + noun)calculateAverageStart with a verb: get, set, calculate, is, has
BooleancamelCase (is/has prefix)isLoggedInPrefix with is, has, can, or should
ArraycamelCase (plural noun)userNamesUse plural form to signal a collection
ClassPascalCase (noun)GameCharacterCapitalize every word including the first
ConstantSCREAMING_SNAKE_CASEMAX_LIVESAll uppercase, underscores between words

JavaScript naming conventions by identifier type

💡

When to Use const vs. SCREAMING_SNAKE_CASE

In JavaScript, 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.

Clean vs. Messy Formatting❌ Inconsistent Formattingfunction calcGrade(s,t){var avg=s/t; if(avg>=90){return "A"} else if( avg>=80 ){ return "B";}else{return "C";}}• Inconsistent indentation• Cryptic parameter names (s, t)• Inconsistent brace placement• Missing spaces around operators• Uses var instead of const/let✅ Clean Formattingfunction calculateGrade( totalScore, numberOfTests) { const average = totalScore / numberOfTests; if (average >= 90) { return "A"; } else if (average >= 80) { return "B"; } else { return "C"; }}• 2-space indentation throughout• Descriptive camelCase names
Side-by-side comparison of the same logic with poor formatting (left, red border) versus clean, consistent formatting (right, green border). The clean version uses descriptive camelCase names, consistent 2-space indentation, spaces around operators, and standard brace placement.

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, and while — even for single-line bodies.
  • ✓ Spacing: Add spaces around operators (x + y, not x+y), after commas, and after keywords like if and for.
  • ✓ 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. 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 name f tells you nothing, and parameters a, b, c could be anything.
  2. 2

    Step 2 — Rename the Function

    Functions should start with a verb and describe what they do. Since this function calculates a letter grade, rename f to calculateLetterGrade. This follows camelCase (starts lowercase, capitalizes subsequent words) and reveals the function's purpose.
    function calculateLetterGrade(...)
  3. 3

    Step 3 — Rename the Parameters

    The three parameters represent test scores, so rename them to testOneScore, testTwoScore, and testThreeScore. Each name clearly describes the data it holds.
    calculateLetterGrade(testOneScore, testTwoScore, testThreeScore)
  4. 4

    Step 4 — Rename the Local Variable

    The variable d holds the average. Rename it to averageScore and change var to const since the value is never reassigned.
    const averageScore = (testOneScore + testTwoScore + testThreeScore) / 3;
  5. 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.

LanguageVariable/Function StyleExample
JavaScriptcamelCasegetUserName
Pythonsnake_caseget_user_name
JavacamelCasegetUserName
C#PascalCase (methods)GetUserName
Rubysnake_caseget_user_name
CSSkebab-caseuser-name-input

Preferred naming conventions for variables and functions across popular languages

✦

KEY TAKEAWAY

Think of naming conventions like languages in different countries. When you visit France, you speak French; when you visit Japan, you speak Japanese. Similarly, when you write JavaScript, you "speak" camelCase. When you write Python, you "speak" snake_case. Following the local convention shows respect for the community and makes your code feel native.
⚠

What About kebab-case?

You may see kebab-case (words separated by hyphens, like 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.

FeatureESLint (Linter)Prettier (Formatter)
PurposeCatches naming issues, logic bugs, and style violationsAutomatically reformats code (indentation, spacing, line breaks)
camelCase enforcementYes — the camelcase rule flags violationsNo — Prettier does not check names
Fixes automatically?Some rules auto-fix; naming requires manual changesYes — reformats on save
Best usedFor code quality, naming rules, and catching bugsFor 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

If you use VS Code, install the ESLint and Prettier extensions. Create a .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

Explain why the variable name x is generally a poor choice in JavaScript. Under what specific circumstance might a single-letter variable name be acceptable?
Show answer
The name 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

Convert each of the following phrases into proper JavaScript camelCase identifiers: (a) "total number of items", (b) "is user logged in", (c) "get student grade point average", (d) "maximum retry count".
Show answer
(a) 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

Identify all naming and formatting convention violations in the following code snippet, then rewrite it correctly: const Max_Speed = 120; var user_name = "Ada"; function GetAge(birth_year){ let Current_Year = 2025; return Current_Year-birth_year }
Show answer
Violations found: (1) 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

You are building a to-do list app. Write the function signature (name and parameters only, no body) for each of the following operations, using proper JavaScript naming conventions: (a) A function that adds a new task to the list. (b) A function that checks whether a task is complete. (c) A class that represents a single to-do item. (d) A constant that stores the maximum number of tasks allowed.
Show answer
(a) 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

A teammate argues: "Naming conventions don't matter because the computer doesn't care what we call our variables — it compiles the same either way. Spending time on names is wasted effort." Write a thoughtful response (3–5 sentences) that addresses their argument, using at least two specific reasons why naming conventions provide real value to a development team.
Show answer
While it is true that the computer executes code identically regardless of variable names, code is read by humans far more often than it is written. First, descriptive and consistently formatted names act as built-in documentation — a developer encountering 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.

Varsity Tutors • JavaScript • Naming & Formatting Conventions — Follow consistent naming and formatting conventions (camelCase)