10 Best Practices for Writing Clean, Readable JavaScript
A formatter fixes layout, but readable code depends on more than spacing. These are structural habits that a formatter can't apply for you.
1. Name things by what they hold, not how they're used
Prefer userCount over temp or data2. A good name saves the next reader from having to trace the variable back to its definition just to understand it.
2. Keep functions doing one thing
A function called saveUser that also sends an email and logs analytics is doing three things. Splitting it up makes each piece independently testable and easier to reason about.
3. Prefer early returns over deep nesting
// Instead of this
function process(user) {
if (user) {
if (user.active) {
// ...
}
}
}
// Do this
function process(user) {
if (!user) return;
if (!user.active) return;
// ...
}
4. Avoid magic numbers and strings
A bare if (status === 3) forces the reader to know what 3 means. A named constant like STATUS_SHIPPED tells them immediately.
5. Use const by default, let when reassignment is needed
Reserving let for variables that actually change signals intent — anyone reading a const declaration knows the value never changes after assignment.
6. Keep line and function length manageable
There's no strict rule, but if a function no longer fits on one screen, it's often doing too much and is a candidate for splitting up.
7. Handle errors explicitly
An empty catch block that swallows errors silently is one of the hardest bugs to track down later. At minimum, log what went wrong.
8. Comment the "why," not the "what"
Code already shows what it does. Comments are most useful explaining why a non-obvious decision was made — a workaround for a browser bug, a business rule that isn't visible from the code alone.
9. Remove dead code instead of commenting it out
Commented-out code rots — nobody's sure if it's safe to delete, so it lingers for years. Version control already has the history; delete it.
10. Automate the formatting layer entirely
None of the above is about spacing, which is exactly the point — once formatting is automatic, code reviews and reading time can focus on structure, naming and logic instead. Run your code through the JS formatter on this site to take spacing off the table, and see 8 common formatting mistakes for the layout issues this replaces.