Formatting JavaScript isn't just about making it look pretty; it's about making the logic obvious at a glance. Proper formatting reduces cognitive load and prevents scope-related bugs.

Core Formatting Rules

While teams may debate specific styles (like spaces vs. tabs), a few universal rules apply to JavaScript formatting:

  • Consistent Indentation: Every time you open a block {, increase the indentation. When you close it }, decrease it.
  • Operator Spacing: Always put spaces around operators (+, =, ===) to separate logic from variables. For example, a = b + c is far more readable than a=b+c.
  • Block Braces: Even for single-line if statements, wrapping the execution block in braces prevents future errors if another line is added later.

Formatting Complex Structures

When dealing with Promises or Array methods (like map, filter, reduce), chaining can quickly become unreadable. Break long chains onto multiple lines.

Poor Formatting
data.filter(x => x.active).map(x => x.id).sort();
Good Formatting
data
  .filter(x => x.active)
  .map(x => x.id)
  .sort();

If you have existing messy code, run it through our JavaScript code formatter to instantly establish a clean baseline.