Coding style & naming
Learn JavaScript naming, formatting, comments, and clear-code habits that make programs easier to read, debug, and share.
- 01Name for intentPick variables and functions that explain the job they do.
- 02Let a formatter handle layoutRecognize what Prettier changes and why teams use it.
- 03Prefer clear over cleverWrite comments and branches that help future readers.
Readable code is kind code
JavaScript does not care whether a variable is named x or minimumPrice. If the grammar is valid, the engine runs it. People are different. We read names, spacing, comments, and branches to understand what the program is trying to do.
Coding style is the habit of writing code that is easy for humans to scan, discuss, debug, and safely change. In this lesson you will use beginner JavaScript only: const, let, functions, arrays, strings, numbers, booleans, and a few if statements. The deeper rules for declaring variables come next in the Variables lesson, so this lesson focuses on what names and layout communicate.
Good style makes code answer four questions quickly: What is this value? What does this function do? How is this code grouped? Why is this surprising choice here?
Imagine moving apartments. A box labeled “Kitchen: plates” goes straight to the right room. A box labeled “stuff” must be opened before anyone knows what to do with it. Code names work the same way: a clear label saves every reader a little investigation.
- In real life: A box labeled Kitchen: plates
- In JavaScript: A variable named
orderItems - In real life: A box labeled stuff
- In JavaScript: A variable named
dataorarr2 - In real life: Helpers can unload without opening every box
- In JavaScript: Readers can understand code without tracing every line first
Where the analogy stops: A box label can be fixed with a marker after the move. A code name appears in many places, so rename carefully and run tests after changing it.
You already met comments and whitespace in Statements, comments & semicolons, strict mode in Strict mode, and editor setup in Setting up your tools. Now we combine those basics into everyday readability.
Naming variables & functions
INTERACTIVEA name should reveal intent: the role a value plays in the program. price is better than n. minimumPrice is better than price when the value is a threshold. Names do not need to be long; they need to be specific enough for the surrounding code.
JavaScript projects commonly use these conventions:
| Thing | Convention | Examples |
|---|---|---|
| Variables and functions | camelCase | orderItems, calculateTotal, formatDate |
| Classes and component-like constructors | PascalCase | ArticleSorter, ShoppingCart |
| True constants | UPPER_SNAKE_CASE | MAX_RETRY_ATTEMPTS, API_TIMEOUT_MS |
| Booleans | yes/no prefixes | isMenuOpen, hasCoupon, canRetry, shouldShowWarning |
| Collections | plural nouns | users, messages, searchResults |
Function names usually start with verbs because functions do work or produce answers: getUser, calculateTotal, renderMenu. Avoid abbreviations unless everyone on the team already uses them, and avoid meaningless numbers like arr2. A later reader should not need a secret decoder ring.
function doIt(arr2, x, flag) { let d = 0; for (const item of arr2) { if (item.price >= x) { d = d + item.price; } } if (flag) { d = d - 5; } return d;}doIt(...)42calculateEligibleTotal(...)42- Collection name is plural and specific.
- Boolean name starts with a yes/no helper.
- Function name is a verb phrase.
- Temporary-looking names are gone.
You have improved 0 of 5 names. Keep asking: what role does this value play?
Notice the key promise of a safe rename: the result did not change. The program still totals eligible items and applies the coupon. The difference is that the second version explains itself while you read it.
ArticleSorterarr2isMenuOpendoStuffcalculateTotaldataMAX_RETRY_ATTEMPTStmp
Sort each name by whether it reveals its purpose. A wrong guess explains what clue was missing.
Formatting with Prettier
COMPAREFormatting is the layout of code: indentation, line breaks, spaces, quotes, semicolons, and trailing commas. Bad formatting can make valid code feel broken because your eyes cannot see its shape.
Newspapers do not invent a new column width for every paragraph. The consistent layout lets readers move through the story. A formatter gives code that same steady rhythm, so spacing arguments disappear.
- In real life: Columns line up issue after issue
- In JavaScript: Indentation and wrapping stay consistent file after file
- In real life: Readers focus on the story
- In JavaScript: Developers focus on behavior instead of spacing choices
- In real life: Editors set the style guide once
- In JavaScript: A project sets formatter rules once
Where the analogy stops: A newspaper layout is designed by people for each article. A formatter is mechanical: it cannot choose better names or explain why code exists.
Prettier is a popular formatter. In a real project you install it and let your editor or scripts run it. This page does not run Prettier in the browser; it shows a predefined before-and-after example, formatted the way Prettier defaults would format this snippet.
const profile={name:"Mina",roles:["mentor","reviewer"]};function greet(name){return "Hello, "+name+"!"}console.log(greet(profile.name));const profile = { name: "Mina", roles: ["mentor", "reviewer"],}; function greet(name) { return "Hello, " + name + "!";} console.log(greet(profile.name));Prettier’s defaults include an 80-character print width, two-space indentation, double quotes for JavaScript strings, semicolons, and trailing commas set to all in Prettier 3. Projects can override choices in a .prettierrc file, but the best team rule is simple: agree once, then automate it.
In VS Code, teams often enable Format on Save so the file is cleaned up the moment it is saved. Formatting is different from linting: a formatter fixes layout; a linter such as ESLint points out likely bugs or rules. That is the next lesson.
Avoiding clever code
STEP THROUGHClever code is code that makes the writer feel smart and the reader feel slow. It often appears as nested ternaries, && used for side effects, double negation such as !!value, truncation tricks like ~~x, or long chains of one-letter names. Some of those patterns are useful in advanced code, but they are expensive when a plain if would say the same thing.
An inside joke is fun for the person who knows the story and awkward for everyone else. Clever code can feel the same. It may work, but a teammate has to learn the joke before they can fix the bug.
- In real life: The author laughs immediately
- In JavaScript: The writer remembers the trick
- In real life: New friends need the whole backstory
- In JavaScript: Reviewers must decode operators before seeing the logic
- In real life: A clear joke invites everyone in
- In JavaScript: Clear branches invite safe changes
Where the analogy stops: Brevity is not always bad. Small, familiar expressions are fine. The problem is compressing several decisions until only the author can read them quickly.
Step through this comparison. Both functions are real and the tests run them over several inputs. Your job is not to prove one is more powerful; your job is to notice which one you would rather change next month.
Pick a cart. Both functions run for real and print the same shipping message; the lesson is about which one future you can read faster.
script
function shippingMessageClever(itemCount, isMember) { return ( (itemCount && (isMember ? "Free shipping" : itemCount > 3 ? "Discount shipping" : "Standard shipping")) || "Cart is empty" );} function shippingMessageClear(itemCount, isMember) { if (itemCount === 0) { return "Cart is empty"; } if (isMember) { return "Free shipping"; } if (itemCount > 3) { return "Discount shipping"; } return "Standard shipping";} const isMember = false;console.log(shippingMessageClever(itemCount, isMember));console.log(shippingMessageClear(itemCount, isMember));Where you’ll use this
Style shows up anywhere code has to be read: your own debugging notes, a pull request, a tutorial, a team project, or a file you forgot for three weeks. Clear style turns a program into a conversation with its next reader.
const MAX_RETRY_ATTEMPTS = 3; function canRetryRequest(errorCount, isOffline) { if (isOffline) { return false; } return errorCount < MAX_RETRY_ATTEMPTS;}MAX_RETRY_ATTEMPTSis a true constant: a fixed setting the team might discuss.canRetryRequestis a verb phrase that tells you it returns a yes/no answer.isOfflinereads naturally inside anif.- The early return handles the special case first, so the final line stays simple.
Before sharing code, ask: Do names reveal intent? Did the formatter run? Do comments explain why? Is any expression clever enough to slow down a beginner version of me?
Common misconceptions
“Style is just personal taste.”
Some details are preferences, but consistency is practical. A team that agrees once can stop debating spacing and focus on behavior.
“Shorter code is always better.”
Short is good when it stays obvious. When short code hides three decisions in one expression, a few extra lines are cheaper.
“Prettier will make my code good.”
Prettier formats. It does not choose better names, delete stale comments, or decide whether a nested ternary should become an if statement.
“Comments can fix confusing code.”
First try better names and structure. Add comments for context the code cannot express, not as subtitles for avoidable confusion.
“Readable code does not need tests.”
Readability helps people reason, but tests prove behavior. This lesson’s rename and clever-code examples are tested for equality.
Practice: style decisions
5 EXERCISESTry each task before opening hints. The answer checker is only for the parts with exact outputs or short wording; the real skill is explaining your choice.
The program works, but arr2 and x are vague. What clearer name could replace x?
const arr2 = ["draft", "sent", "archived"];
const x = arr2.length;
console.log(x);const statuses = ["draft", "sent", "archived"];
const statusCount = statuses.length;
console.log(statusCount);statuses says what the collection contains, and statusCount says the number is a count. The output is still 3.
Rewrite the ternary as an if statement. What should the clear version print for the provided array?
const names = ["Ada", "Mina"];
const label = names.length ? names.join(" & ") : "Nobody";
console.log(label);const names = ["Ada", "Mina"];
let label;
if (names.length === 0) {
label = "Nobody";
} else {
label = names.join(" & ");
}
console.log(label);The clear version uses more lines, but each branch has one job. It still prints Ada & Mina.
The comment says what the code does. What kind of information should a better comment explain instead?
// Adds 7 because a week has 7 days
const reminderDay = signupDay + 7;// Wait a full week so new users get one weekend before the reminder.
const reminderDay = signupDay + 7;The new comment explains why seven days is the chosen delay. The code already shows that seven is added.
Format the code so its shape is clear. Then predict the output to prove you did not change behavior.
const user={name:"Ada",badges:["HTML","JS","CSS"]};
console.log(user.name + " has " + user.badges.length + " badges");const user = {
name: "Ada",
badges: ["HTML", "JS", "CSS"],
};
console.log(user.name + " has " + user.badges.length + " badges");The object shape is easier to read, and the behavior is unchanged: it prints Ada has 3 badges.
Trace one question at a time. What does the program log?
const paid = true;
const inStock = false;
const message = paid ? (inStock ? "ship now" : "ship tomorrow") : "ask for payment";
console.log(message);paid is true, so JavaScript checks the inner ternary. inStock is false, so the message is ship tomorrow.
Quiz: check your understanding
7 QUESTIONSYour first try counts for the score, and every answer explains itself. For code questions, trace the values before you choose.
Question 1 of 7Which name best fits a boolean value that tracks whether a modal is open?
Choose an answer to see the explanation.
Question 2 of 7What does this program print?
Read the code, then predictfunction calculateTotal(price) { return price + 5; } console.log(calculateTotal(10));Choose an answer to see the explanation.
Question 3 of 7What does Prettier mainly do?
Choose an answer to see the explanation.
Question 4 of 7Which comment is most helpful?
Choose an answer to see the explanation.
Question 5 of 7What does this nested ternary print?
Read the code, then predictconst isLoggedIn = true; const hasProfile = false; const page = isLoggedIn ? (hasProfile ? "profile" : "setup") : "sign in"; console.log(page);Choose an answer to see the explanation.
Question 6 of 7Why avoid clever code that works today?
Choose an answer to see the explanation.
Question 7 of 7What does this code print?
Read the code, then predictconst users = ["Ada", "Mina", "Bo"]; const hasUsers = users.length > 0; console.log(hasUsers);Choose an answer to see the explanation.
Key takeaways
- Name values for their role:
orderItems,minimumPrice, andhasCouponbeatarr2,x, andflag. - Use common conventions: camelCase, PascalCase, UPPER_SNAKE_CASE for true constants, boolean prefixes, verb functions, and plural collections.
- Prettier is a formatter. It fixes layout, not logic; ESLint in the next lesson looks for likely bugs and rules.
- Helpful comments explain why, warn about surprises, or document public functions. Delete stale and commented-out code.
- Prefer clear branches over clever puzzles when future readers need to change the code safely.
Remember the one-liner.
Coding style is kindness to the next person reading the program, especially when that person is future you.
Up next: Linting with ESLint.
Comments that help
SORTComments are not decorations. They are notes for readers. The best comments explain something the code cannot say by itself: a reason, a warning, a temporary decision, or how public code should be used.
A useful sticky note saves someone from a mistake: “Do not unplug; freezer is defrosting.” A useless one says “This is a plug.” Code is similar. If the next line already says what happens, use the comment to explain why it happens.
countWhere the analogy stops: A sticky note is easy to throw away. Code comments live beside the program, so update or delete them whenever the code changes.
// Round down so discount codes never overcharge the shopper.// Add one to count// TODO: Replace the test discount after launch week.// const oldTotal = price * 1.2;// Warning: the API sends cents, not dollars.// Sort newest first (above code actually sorts oldest first)Sort each comment by whether it adds useful context. Obvious and stale comments belong in noise.