What Is Prettier and How It Formats JavaScript

This article provides an overview of Prettier, an opinionated code formatter widely used in modern web development. It explains what Prettier is, how it processes and formats JavaScript by parsing code into an Abstract Syntax Tree (AST), and the mechanisms used to enforce uniform code style across teams and development workflows.

What Is Prettier?

Prettier is an open-source, opinionated code formatter that supports JavaScript, TypeScript, HTML, CSS, JSON, and several other languages. Unlike traditional linters that primarily identify logic bugs and code smells, Prettier focuses almost exclusively on code presentation. It takes your code, ignores all existing styling, and re-prints it from scratch according to a strict set of formatting rules.

Because Prettier is “opinionated,” it offers very few configuration options. This design choice removes the need for developer debates over style choices such as indentation size, quote types, trailing commas, and line wrapping.

How Prettier Enforces Formatting

Prettier does not simply apply search-and-replace rules or add spaces to existing text. Instead, it follows a deterministic formatting pipeline:

  1. Parsing to an Abstract Syntax Tree (AST): Prettier takes the raw JavaScript code and parses it into an AST. An AST is a tree representation of the code’s structural syntax, completely stripped of any original formatting, whitespace, or comments’ exact layout.
  2. Re-printing the Code: Prettier walks through the AST and re-prints the entire codebase from scratch. It applies formatting decisions based on structural context and a predefined maximum line length (the “print width”).
  3. Handling Line Wrapping Dynamically: If a line of code fits within the configured line length, Prettier keeps it on a single line. If it exceeds that length, Prettier calculates the cleanest way to break the line across multiple lines based on language grammar rules.

Because the output is generated purely from the AST and a fixed set of layout rules, running Prettier on the same code will always produce the exact same formatted output, regardless of how messy the input was.

Prettier vs. Linters (like ESLint)

It is common to confuse code formatters with linters, but they serve distinct purposes:

Prettier is often used alongside ESLint. By disabling ESLint’s stylistic rules and delegating all formatting tasks to Prettier, developers get the benefit of both deep static analysis and consistent code layout without rule conflicts.

Automating Prettier in Workflows

To ensure consistent formatting across an entire project or team, Prettier can be integrated into several stages of the development lifecycle:

By automating the formatting process entirely, Prettier saves developer time, reduces cognitive overhead, and eliminates stylistic arguments during code reviews.