cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Coding style & naming

Learn JavaScript naming, formatting, comments, and clear-code habits that make programs easier to read, debug, and share.

By the end, you can
  • 01
    Name for intentPick variables and functions that explain the job they do.
  • 02
    Let a formatter handle layoutRecognize what Prettier changes and why teams use it.
  • 03
    Prefer 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.

The short version

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?

Real-life analogyNames are moving-box labels

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 data or arr2
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

INTERACTIVE

A 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:

Common JavaScript naming conventions
ThingConventionExamples
Variables and functionscamelCaseorderItems, calculateTotal, formatDate
Classes and component-like constructorsPascalCaseArticleSorter, ShoppingCart
True constantsUPPER_SNAKE_CASEMAX_RETRY_ATTEMPTS, API_TIMEOUT_MS
Booleansyes/no prefixesisMenuOpen, hasCoupon, canRetry, shouldShowWarning
Collectionsplural nounsusers, 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.

Rename to reveal intent
Renamed sourcePop out in the code editor (opens in a new tab)JavaScript
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;}
Behavior checkmatching
original doIt(...)42
renamed calculateEligibleTotal(...)42
readability checklist0 / 5
  • 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.
Try it yourself
Choose clearer labels:

You have improved 0 of 5 names. Keep asking: what role does this value play?

The code preview changes names only. The result pane calls the original and renamed real functions with the same inputs to prove the behavior stayed equal.

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.

Clear or unclear name?
  • ArticleSorter
  • arr2
  • isMenuOpen
  • doStuff
  • calculateTotal
  • data
  • MAX_RETRY_ATTEMPTS
  • tmp
Try it yourself
0 of 8 correct

Sort each name by whether it reveals its purpose. A wrong guess explains what clue was missing.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Formatting with Prettier

COMPARE

Formatting 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.

Real-life analogyFormatting is a newspaper layout

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.

Before formattingPop out in the code editor (opens in a new tab)JavaScript
const profile={name:"Mina",roles:["mentor","reviewer"]};function greet(name){return "Hello, "+name+"!"}console.log(greet(profile.name));
After formattingPop out in the code editor (opens in a new tab)JavaScript
const profile = {  name: "Mina",  roles: ["mentor", "reviewer"],}; function greet(name) {  return "Hello, " + name + "!";} console.log(greet(profile.name));
Prettier defaults used in this lesson

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.

Comments that help

SORT

Comments 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.

Real-life analogyComments are sticky notes about why

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.

In real life: Sticky note: Do not unplug; freezer is defrosting
In JavaScript: Comment: Keep retry delay long because the service rate-limits bursts
In real life: Sticky note: This is a plug
In JavaScript: Comment: Add one to count
In real life: Old sticky note left on the wrong drawer
In JavaScript: Stale comment that disagrees with the code

Where 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.

What-comment versus why-commentPop out in the code editor (opens in a new tab)JavaScript
// Adds 5 percentconst fee = subtotal * 0.05; // Keep a small fee so tiny orders still cover card processing.const minimumFee = Math.max(fee, 1);
Comment styles to keep or delete
Comment typeHelpful whenWatch out for
Why-commentExplains a product rule, trade-off, or surprising choiceDo not use it to excuse confusing code that could be renamed
WarningCalls out surprising units, browser behavior, or timingKeep it close to the risky line
TODO with contextNames what must change and why it is safe temporarilyA vague TODO can become permanent clutter
JSDocDocuments public functions other files will callTiny private helpers may not need it
Commented-out codeAlmost never in shared codeDelete it; version control remembers history
Helpful comment or noise?
  • // 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)
Try it yourself
0 of 6 correct

Sort each comment by whether it adds useful context. Obvious and stale comments belong in noise.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Avoiding clever code

STEP THROUGH

Clever 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.

Real-life analogyClever code is an inside joke

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.

Clever one-liner or clear branches?
Step 0 of 6Ready
Your turn: follow the blue line

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.

Running in
  1. script
Next: line 22
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
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));
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Switch the cart and predict both printed lines.

Changing the setting starts a fresh recorded run.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

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.

A small style checklist in codePop out in the code editor (opens in a new tab)JavaScript
const MAX_RETRY_ATTEMPTS = 3; function canRetryRequest(errorCount, isOffline) {  if (isOffline) {    return false;  }  return errorCount < MAX_RETRY_ATTEMPTS;}
  • MAX_RETRY_ATTEMPTS is a true constant: a fixed setting the team might discuss.
  • canRetryRequest is a verb phrase that tells you it returns a yes/no answer.
  • isOffline reads naturally inside an if.
  • 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 EXERCISES

Try 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.

Exercise 1 · Warm-upRename a vague count

The program works, but arr2 and x are vague. What clearer name could replace x?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const arr2 = ["draft", "sent", "archived"];
const x = arr2.length;
console.log(x);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeRewrite a clever one-liner clearly

    Rewrite the ternary as an if statement. What should the clear version print for the provided array?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const names = ["Ada", "Mina"];
    const label = names.length ? names.join(" & ") : "Nobody";
    console.log(label);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeTurn what into why

      The comment says what the code does. What kind of information should a better comment explain instead?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      // Adds 7 because a week has 7 days
      const reminderDay = signupDay + 7;

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeHand-format a messy snippet

        Format the code so its shape is clear. Then predict the output to prove you did not change behavior.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const user={name:"Ada",badges:["HTML","JS","CSS"]};
        console.log(user.name + " has " + user.badges.length + " badges");

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengePredict a nested ternary

          Trace one question at a time. What does the program log?

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const paid = true;
          const inStock = false;
          const message = paid ? (inStock ? "ship now" : "ship tomorrow") : "ask for payment";
          console.log(message);

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS

            Your first try counts for the score, and every answer explains itself. For code questions, trace the values before you choose.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7Which name best fits a boolean value that tracks whether a modal is open?

              Choose an answer to see the explanation.

            2. Question 2 of 7What does this program print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              function calculateTotal(price) {
                return price + 5;
              }
              console.log(calculateTotal(10));

              Choose an answer to see the explanation.

            3. Question 3 of 7What does Prettier mainly do?

              Choose an answer to see the explanation.

            4. Question 4 of 7Which comment is most helpful?

              Choose an answer to see the explanation.

            5. Question 5 of 7What does this nested ternary print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const isLoggedIn = true;
              const hasProfile = false;
              const page = isLoggedIn ? (hasProfile ? "profile" : "setup") : "sign in";
              console.log(page);

              Choose an answer to see the explanation.

            6. Question 6 of 7Why avoid clever code that works today?

              Choose an answer to see the explanation.

            7. Question 7 of 7What does this code print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const 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, and hasCoupon beat arr2, x, and flag.
            • 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.

            CompleteFrontend Clear concepts. Working examples.