In short
A JavaScript style guide is a set of rules that keeps code clean and easy to read. Learn best practices for naming, const and let, small functions, comments and file organisation. Why follow a JavaScript style guide? Code is read many more times than it is written.
A JavaScript style guide is a set of rules that keeps code clean and easy to read. Learn best practices for naming, const and let, small functions, comments and file organisation.
Why follow a JavaScript style guide?
Code is read many more times than it is written. You read it when you fix a bug, when you add a feature six months later, and when a teammate reviews it. A style guide is a shared set of rules for how code should look and how it should be written. It is like the rules of the road: driving on the same side makes everyone safer, even if the other side would also work.
Big teams publish their own guides (Airbnb, Google and StandardJS are well known), and they mostly agree on the ideas below. In the tools lesson you met ESLint and Prettier. They check many of these rules for you automatically. This lesson explains why the rules exist, with a bad and a good version of each.
Naming: variables, functions and constants
Good names are the cheapest documentation you can write. A name should say what something is or what it does, so the reader does not have to guess.
| What | Style | Example |
|---|---|---|
| Variables and functions | camelCase | userName, getTotalPrice() |
| Classes and constructors | PascalCase | ShoppingCart, UserProfile |
| Fixed settings that never change | UPPER_SNAKE_CASE | MAX_LOGIN_ATTEMPTS, API_URL |
| True/false values | Start with is, has, can, should | isLoggedIn, hasItems, canEdit |
| Functions | Start with a verb | fetchOrders(), formatDate(), showError() |
| File names | kebab-case or camelCase, be consistent | cart-utils.js, api.js |
// Bad: short, vague names
const d = 7;
const x = users.filter((u) => u.a);
function calc(p, q) { return p * q; }
// Good: the names explain themselves
const DAYS_PER_WEEK = 7;
const activeUsers = users.filter((user) => user.isActive);
function calculateTotal(price, quantity) { return price * quantity; }
The good version needs no comments. Short names like i are fine for a tiny loop counter, but anything that lives longer than a few lines deserves a real name.
Write safer code: const, let and strict equality
Three small habits prevent a large number of bugs.
Use const by default, and let only when the value must change. Never use var in new code. const tells the reader "this will not be reassigned", which makes code easier to follow.
Always use === and !==. The loose == converts types before comparing and gives surprising results.
Avoid global variables. A global variable can be changed by any script on the page, including other libraries. Use modules (<script type="module">), which keep variables private to each file.
// Bad
var total = 0; // var, and global
if (input == 0) { } // "" == 0 is true!
for (var i = 0; i < 3; i++) {} // i leaks outside the loop
// Good
let total = 0; // let, because total changes
const TAX_RATE = 0.2; // const, because it never changes
if (input === 0) { } // only true for the number 0
for (let i = 0; i < 3; i++) {} // i exists only inside the loop
console.log("" == 0); // Output: true (surprise)
console.log("" === 0); // Output: false (what you expect)
Tip: Turn on ESLint's
no-var,prefer-constandeqeqeqrules. They catch these three problems every time you save the file.
Small functions and early returns
A function should do one job. If you need the word "and" to describe it ("it checks the form and sends it and shows a message"), split it. Small functions are easier to test, reuse and name. A good rough limit is that a function fits on your screen without scrolling.
Early return means checking for problems first and leaving the function straight away. This avoids deep nesting, where the real work is hidden inside many if blocks.
// Bad: deep nesting, the main logic is buried
function checkout(cart, user) {
if (user) {
if (cart.length > 0) {
if (user.hasAddress) {
return `Order placed for ${cart.length} items`;
} else {
return "Please add an address";
}
} else {
return "Your cart is empty";
}
} else {
return "Please log in";
}
}
// Good: early returns, flat and clear
function checkout(cart, user) {
if (!user) return "Please log in";
if (cart.length === 0) return "Your cart is empty";
if (!user.hasAddress) return "Please add an address";
return `Order placed for ${cart.length} items`;
}
console.log(checkout(["book"], { hasAddress: true }));
// Output: Order placed for 1 items
console.log(checkout([], { hasAddress: true }));
// Output: Your cart is empty
Both versions give the same results, but in the good version you can read each rule on one line, and the "happy path" is at the bottom with no indentation.
Comments and consistent formatting
Good code explains what it does through names. Comments should explain why: a business rule, a workaround, or a reason that is not obvious.
// Bad: the comment repeats the code
// add 1 to count
count = count + 1;
// Good: the comment explains a reason you cannot see in the code
// The payment API counts months from 0, so January is 0.
const apiMonth = date.getMonth();
/**
* Formats a price in cents as a currency string.
* @param {number} cents - The price in cents, e.g. 1999
* @returns {string} The formatted price, e.g. "$19.99"
*/
function formatPrice(cents) {
return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(cents / 100);
}
console.log(formatPrice(1999)); // Output: $19.99
The /** ... */ block is called JSDoc. Code editors like VS Code read it and show the description when you hover over the function.
For formatting (spaces, quotes, semicolons, line length), the most important rule is be consistent. Do not argue about it; let Prettier decide. Common choices are 2-space indentation, semicolons at the end of statements, one style of quotes, and a space after keywords like if (. Delete commented-out old code; version control (Git) remembers it for you.
JavaScript reserved words and file organisation
Reserved words are words the language already uses, so you cannot use them as variable or function names. const class = "A" is a syntax error.
| Group | Reserved words |
|---|---|
| Declaring things | var, let, const, function, class, import, export, extends |
| Control flow | if, else, switch, case, default, for, while, do, break, continue, return |
| Errors | try, catch, finally, throw |
| Operators and values | new, delete, typeof, instanceof, in, void, this, super, true, false, null |
| Other | debugger, with, yield, await |
| Reserved for the future / strict mode | enum, implements, interface, package, private, protected, public, static |
Also avoid names that are not reserved but already mean something, such as undefined, NaN, Infinity, eval, arguments and name (a property of window).
For file organisation, keep one topic per file and group files by what they do. A small project might look like this:
my-shop/
index.html
src/
main.js (starts the app, connects everything)
api.js (all fetch calls in one place)
cart.js (cart logic: add, remove, total)
ui/
render-cart.js (functions that update the page)
utils/
format.js (small helpers like formatPrice)
styles/
main.css
Inside each file, use the same order: imports at the top, then constants, then functions, then the code that runs. Export only what other files need.
Practice exercise
Clean up this code using the rules from this lesson: var a = [5, 12, 8]; function f(x) { if (x) { if (x.length > 0) { var t = 0; for (var i = 0; i < x.length; i++) { t = t + x[i]; } return t; } } return 0; } console.log(f(a));. Rename everything, replace var, use an early return, and add one helpful comment.
Hint: a good result starts with const prices = [5, 12, 8]; and a function called something like sumPrices. It should still log 25.
Key takeaways
- A style guide makes code predictable, so anyone on the team can read it quickly.
- Use camelCase for variables, PascalCase for classes, UPPER_SNAKE_CASE for fixed settings, and clear, descriptive names.
- Default to
const, useletwhen needed, nevervar, and always compare with===. - Keep functions small, use early returns instead of deep nesting, and write comments that explain why.
- Let Prettier and ESLint handle formatting and simple rules, and organise files by what they do.