Skip to content
uencoder
TUTORIAL

How to Format JavaScript

Beautify JavaScript code with consistent indentation, spacing, and semicolons.

Problem

Your JavaScript is minified or inconsistently styled, making it hard to read and debug.

Prerequisites

  • Understanding of JavaScript syntax
  • Familiarity with code formatters

Steps

  1. 1. Parse the JavaScript

    The formatter parses the code into an AST to understand its structure. This ensures formatting is based on syntax, not text patterns. Invalid syntax will cause an error.

    Input
    const x=1;function f(){return x+2}
    Output
    parsed AST
  2. 2. Apply style rules

    Add indentation based on block nesting. Insert spaces around operators and after commas. Add or enforce semicolons based on your style. Break long lines and align chained calls for readability.

    Input
    const x=1;function f(){return x+2}
    Output
    const x = 1;\nfunction f() {\n  return x + 2;\n}
  3. 3. Handle modern syntax

    Ensure the formatter supports modern JavaScript features: arrow functions, destructuring, template literals, optional chaining, and async/await. ES modules and TypeScript syntax should also be supported.

    Input
    const f=async(a,b)=>a?.b??c
    Output
    formatted modern JS

Expected result

Readable JavaScript with consistent style that preserves the original semantics.

Common errors

Formatted code has different behavior
Automatic semicolon insertion can change behavior in rare cases (e.g., lines starting with () or []). Use a formatter that handles ASI correctly.
Formatter does not support TypeScript
Use a formatter with TypeScript support, such as Prettier, to handle type annotations.

Troubleshooting

  • If the formatter fails, the input has a syntax error. Fix it first.
  • Use Prettier or eslint --fix for industry-standard formatting.

Security limits

  • Formatting does not execute code. However, never eval() formatted code from untrusted sources.

Related tools

Related tasks

Ready to run it?

References