Write Clean Javascript Code

A awesome resouce on writing clean javascript code
https://github.com/ryanmcdermott/clean-code-javascript

based on Robert C. Martin‘s book
Clean Code: A Handbook of Agile Software Craftsmanship

“The only valid measurement of code quality is WTFs/minute”

Variables

  • Use meaningful and pronounceable variable names
  • Use the same vocabulary for the same type of variable
  • Use searchable names
  • Use explanatory variables
  • Avoid Mental Mapping
  • Don’t add unneeded context
  • Use default arguments instead of short circuiting or conditionals

Functions

  • Function arguments (2 or fewer ideally)
  • Functions should do one thing
  • Function names should say what they do
  • Functions should only be one level of abstraction
  • Remove duplicate code
  • Set default objects with Object.assign
  • Don’t use flags as function parameters
  • Avoid Side Effects
  • Don’t write to global functions
  • Favor functional programming over imperative programming
  • Encapsulate conditionals
  • Avoid negative conditionals
  • Avoid conditionals
  • Avoid type-checking
  • Don’t over-optimize
  • Remove dead code

Objects and Data Structures

  • Use getters and setters
  • Make objects have private members

Classes

  • Prefer ES2015/ES6 classes over ES5 plain functions
  • Use method chaining
  • Prefer composition over inheritance

SOLID

  • Single Responsibility Principle (SRP)
  • Open/Closed Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

Testing

  • Single concept per test

Concurrency

  • Use Promises, not callbacks
  • Async/Await are even cleaner than Promises

Error Handling

  • Don’t ignore caught errors
  • Don’t ignore rejected promises

Formatting

  • Use consistent capitalization
  • Function callers and callees should be close

Comments

  • Only comment things that have business logic complexity.
  • Don’t leave commented out code in your codebase
  • Don’t have journal comments
  • Avoid positional markers

Leave a Comment