Working code is only half the job. After this lesson you will know how to leave notes that help, how to name and lay out your code so that other people (including you in six months) can read it, and which automatic behaviours of the language to watch for.
Comments
The engine ignores comments completely. They are only for humans.
// A single-line comment runs to the end of the line.
const price = 20; // it can also sit after code
/*
A block comment can
span many lines.
*/Block comments also make a quick way to switch off code while testing: wrap lines in /* */, and remove the markers later. Most editors toggle line comments with Ctrl+/ (Cmd+/ on a Mac), which comments out a whole selection at once.
What deserves a comment
The best comment tells the reader something the code cannot: why.
// Weak: says what the code already says
count = count + 1; // add one to count
// Better: says why
// The API numbers pages from 0, but visitors expect page 1 first.
const pageNumber = apiPage + 1;Good reasons to write a comment:
- A decision that looks odd but is deliberate, with the reason.
- A workaround for a bug, with a link or description.
- A short summary above a complicated block.
- A reminder of a limit, such as "assumes the list is already sorted".
Avoid comments that repeat the code, that are out of date, or that apologise for messy code. A wrong comment is worse than none, so update comments when you change the code. Often a better name removes the need: const isAdult = age >= 18; needs no comment at all. Remove old commented-out code instead of keeping it, since version control remembers it.
Naming
Names are the main documentation in a program. Follow these habits.
- camelCase for variables and functions:
totalPrice,getUserName. - PascalCase for classes, which you will meet later:
ShoppingCart. - CAPITALS_WITH_UNDERSCORES for fixed, never-changing constants, by habit:
MAX_ITEMS. - Names that say what a value means:
remainingSeconds, notrsortemp2. - Booleans that read like a question:
isVisible,hasError,canSubmit. - Verbs for functions that do something:
calculateTotal,showMessage. - Avoid single letters outside tiny loops and short callbacks.
Formatting
JavaScript does not care about spaces or line breaks in most places. People do. Choose a style and use it everywhere.
// Hard to read
const total=price*qty>5?"big":"small";
// Easier to read
const total = price * qty > 5 ? "big" : "small";Common conventions:
- Indent each nested block by the same amount, usually 2 or 4 spaces.
- Put spaces around operators and after commas.
- One statement per line.
- Keep lines reasonably short.
- Pick one quote style for plain strings and stick to it.
You do not have to format by hand. Tools such as Prettier reformat a file every time you save, and ESLint flags likely mistakes. Many editors support them. They end arguments about style and catch typos early. A beginner can happily start without them, but add them once you write bigger projects.
Semicolons and automatic insertion
You have seen semicolons at the end of statements. JavaScript can insert missing ones for you, which is called automatic semicolon insertion (ASI). Many people write semicolons everywhere and avoid the issue. Whichever style you choose, know the two classic traps.
Trap 1: a line break after return.
function broken() {
return
42;
}
console.log(broken()); // undefinedThe engine sees return; on the first line and stops there, so the 42 is never used. Keep the returned value on the same line as return. If it is long, open a bracket on that line:
function fixed() {
return (
42
);
}
console.log(fixed()); // 42Trap 2: a line starting with ( or [. A new line that begins with one of these can be read as a continuation of the line above. If you write without semicolons, put one before such a line. Writing semicolons consistently avoids this too.
Reading error messages and keeping tidy
Code that is laid out consistently makes errors easier to find, because a missing bracket looks wrong against the pattern. When you hit a problem, shrink the code until the bug is clear, and then fix it. Keep experiments in a separate file so that your main code stays tidy.
Try it
This snippet works, but is hard to read. Click Try it, check that it runs, then rewrite it with clearer names, spacing and one useful comment. Make sure the output stays the same.
<p id="out"></p>
<script>
const a=19.99,b=3,c=0.18;
const d=a*b;
const e=d*c;
document.getElementById("out").textContent="Subtotal "+d.toFixed(2)+", tax "+e.toFixed(2)+", total "+(d+e).toFixed(2);
</script>One possible result uses unitPrice, quantity and taxRate, a single comment explaining that the tax rate is an example, and a template literal for the message. Your names may differ. Clear names matter more than matching mine.
Common mistakes
- Comments that repeat the code. Explain the reason instead.
- Leaving outdated comments. Update or delete them when the code changes.
- Inconsistent style. Mixing tabs and spaces, or switching quotes, makes code look careless.
- Cryptic names.
x1,tmp,data2. Use the meaning. - A line break after
return. The function silently returnsundefined. - Piles of commented-out code. Delete it, since your version history keeps it.
Exercise
- Take any code you wrote in earlier lessons and rename every unclear variable.
- Add comments only where the why is not obvious. Remove any that just repeat the code.
- Write a function with
returnon one line and the value on the next. Run it, and watch it returnundefined. Fix it. - Write down, in a comment at the top of the file, the style you chose (indentation, quotes, semicolons) and follow it.
You have finished the Getting started section. Next you can move on to if, else and else if and start making decisions in code.
Key points
- Use // for single-line comments and /* */ for blocks, and explain why the code does something rather than repeating what it does.
- Name variables for their meaning, using camelCase for values and functions and CAPITALS for fixed constants by habit.
- Pick one formatting style (indentation, quotes, semicolons) and apply it everywhere, ideally with a formatter.
- A return followed by a line break returns undefined, because JavaScript inserts a semicolon automatically.
- Small, well-named pieces of code need fewer comments than long, clever ones.