What you’ll learn in this guide:
- What makes code “clean” and why it matters
- Naming conventions that make code self-documenting
- How to write small, focused functions that do one thing
- The DRY principle and when to apply it
- How to avoid side effects and write predictable code
- Using early returns to reduce nesting
- When to write comments (and when not to)
- SOLID principles applied to JavaScript
The Newspaper Analogy
Think of your code like a newspaper article. A reader should understand the gist from the headline, get more details from the first paragraph, and find supporting information as they read further. Your code should work the same way: high-level functions at the top, implementation details below.Meaningful Naming
Names are everywhere in code: variables, functions, classes, files. Good names make comments unnecessary. Bad names make simple code confusing.Use Pronounceable, Searchable Names
Use the Same Word for the Same Concept
Pick one word per concept and stick with it. If you fetch users withgetUser(), don’t also have fetchClient() and retrieveCustomer().
Avoid Mental Mapping
Single-letter variables force readers to remember whata, x, or l mean. Be explicit.
Don’t Add Unnecessary Context
If your class is calledCar, you don’t need carMake, carModel, carColor. The context is already there.
Functions Should Do One Thing
This is the single most important rule in clean code. When functions do one thing, they’re easier to name, easier to test, and easier to reuse.Keep Functions Small and Focused
Limit Function Parameters
Two or fewer parameters is ideal. If you need more, use an object with destructuring. This also makes the call site self-documenting.Don’t Use Boolean Flags
A boolean parameter is a sign that the function does more than one thing. Split it into two functions instead.Avoid Magic Numbers and Strings
Magic values are unexplained numbers or strings scattered through your code. They make code hard to understand and hard to change.DRY: Don’t Repeat Yourself
Duplicate code means multiple places to update when logic changes. But be careful: a bad abstraction is worse than duplication. Only abstract when you see a clear pattern.Avoid Side Effects
A function has a side effect when it does something other than take inputs and return outputs: modifying a global variable, writing to a file, or mutating an input parameter. Side effects make code unpredictable and hard to test. For a deeper dive, see our Pure Functions guide.Early Returns and Guard Clauses
Deeply nested code is hard to follow. Use early returns to handle edge cases first, then write the main logic without extra indentation.continue to skip iterations instead of nesting:
Comments: Less is More
Good code mostly documents itself. Comments should explain why, not what. If you need a comment to explain what code does, consider rewriting the code to be clearer.Don’t State the Obvious
Don’t Leave Commented-Out Code
That’s what version control is for. Delete it. If you need it later, check the git history.Don’t Write Journal Comments
Git log exists for a reason.SOLID Principles in JavaScript
SOLID is a set of five principles that help you write maintainable, flexible code. Here’s how they apply to JavaScript:Single Responsibility Principle (SRP)
Single Responsibility Principle (SRP)
A class or module should have only one reason to change.
Open/Closed Principle (OCP)
Open/Closed Principle (OCP)
Code should be open for extension but closed for modification. Add new features by adding new code, not changing existing code.
Liskov Substitution Principle (LSP)
Liskov Substitution Principle (LSP)
Child classes should be usable wherever parent classes are expected without breaking the code.
Interface Segregation Principle (ISP)
Interface Segregation Principle (ISP)
Don’t force clients to depend on methods they don’t use. In JavaScript, use optional configuration objects instead of requiring many parameters.
Dependency Inversion Principle (DIP)
Dependency Inversion Principle (DIP)
Depend on abstractions, not concrete implementations. Inject dependencies rather than instantiating them inside your classes.
Write Testable Code
Functions that do one thing with no side effects are easy to test. If a function is hard to test, it’s often a sign that it’s doing too much or has hidden dependencies. Clean code and testable code go hand in hand.Key Takeaways
The key things to remember:
- Names matter — Use meaningful, pronounceable, searchable names. Good names eliminate the need for comments.
- Functions should do one thing — This is the most important rule. Small, focused functions are easier to name, test, and reuse.
- Limit function parameters — Two or fewer is ideal. Use object destructuring for more.
- Eliminate magic numbers — Use named constants that explain what values mean.
- DRY, but don’t over-abstract — Remove duplication, but a bad abstraction is worse than duplication.
- Avoid side effects — Prefer pure functions that don’t mutate inputs or global state.
- Use early returns — Guard clauses reduce nesting and make code easier to follow.
- Comments explain why, not what — If you need to explain what code does, rewrite the code.
- Delete dead code — Commented-out code and unused functions clutter your codebase. Git remembers.
- Use tools — ESLint catches issues, Prettier handles formatting. Don’t argue about style.
Test Your Knowledge
Question 1: What's wrong with this function name?
Question 1: What's wrong with this function name?
process is too vague. It doesn’t tell you what kind of processing happens or what kind of data is expected. Better names would be validateUserInput, parseJsonResponse, or calculateOrderTotal, depending on what the function actually does.Question 2: Why is this function problematic?
Question 2: Why is this function problematic?
isAdmin, sendWelcomeEmail) suggest the function might be doing multiple things. Refactor to use an options object:Question 3: When should you write a comment?
Question 3: When should you write a comment?
Answer:Write comments when you need to explain why something is done a certain way, especially for:
- Business logic that isn’t obvious from the code
- Workarounds for bugs or edge cases
- Legal or licensing requirements
- Complex algorithms where the approach isn’t self-evident
Question 4: What's a 'magic number' and why is it bad?
Question 4: What's a 'magic number' and why is it bad?
Answer:A magic number is an unexplained numeric literal in code, like
86400000 or 18. They’re bad because:- You can’t search for what they mean
- They don’t explain their purpose
- If the value needs to change, you have to find every occurrence
MILLISECONDS_PER_DAY or MINIMUM_LEGAL_AGE.Question 5: How would you refactor this nested code?
Question 5: How would you refactor this nested code?
Related Concepts
Pure Functions
Deep dive into functions without side effects and why they make code predictable
Modern JS Syntax
ES6+ features like destructuring and arrow functions that enable cleaner code
Error Handling
How to handle errors cleanly without swallowing exceptions or cluttering code
Design Patterns
Reusable solutions that embody clean code principles at a higher level
Books
Clean Code: A Handbook of Agile Software Craftsmanship
The foundational text by Robert C. Martin that started the clean code movement. While examples are in Java, the principles apply to any language. A must-read for every developer.
Articles
Clean Code JavaScript
The definitive JavaScript adaptation of Clean Code principles with 94k+ GitHub stars. Every example is practical and immediately applicable to your code.
Clean Coding for Beginners
freeCodeCamp’s beginner-friendly introduction covering the “why” behind each clean code principle. Great starting point if you’re new to these concepts.
Coding Style
javascript.info’s practical guide to syntax, formatting, and style. Includes a visual cheat sheet you can reference while coding.
Ninja Code
A satirical guide showing what NOT to do. The humor makes the anti-patterns memorable, and you’ll recognize some of these mistakes in real codebases.
Videos
JavaScript Pro Tips - Code This, NOT That
Fireship’s fast-paced video showing modern patterns that replace outdated approaches. Great examples of before/after refactoring.
Clean Code Playlist
freeCodeCamp’s multi-part series covering each clean code principle in depth with live coding. Perfect for visual learners.
Clean Code - Uncle Bob
Robert C. Martin himself explaining clean code fundamentals. Hearing it from the source gives you the philosophy behind the principles.