Beautify JavaScript — Format and Pretty-Print JS Code
Learn how to beautify minified JavaScript code by restoring indentation, line breaks, and readable formatting. Understand AST-based formatting vs regex approaches and tool options.
Detailed Explanation
How JavaScript Beautification Works
JavaScript beautification (also called pretty-printing) is the reverse of minification. It takes compact, hard-to-read code and restores human-friendly formatting with proper indentation, line breaks, and spacing.
Before and After
// Minified input
function greet(e){if(!e)return"Hello, stranger!";const t=e.charAt(0).toUpperCase()+e.slice(1);return"Hello, "+t+"!"}
After beautification:
function greet(e) {
if (!e) return "Hello, stranger!";
const t = e.charAt(0).toUpperCase() + e.slice(1);
return "Hello, " + t + "!";
}
What Beautification Cannot Restore
Beautification adds whitespace and structure, but it cannot undo:
- Variable name mangling —
eandtremain shortened because the original names are lost during minification. - Removed comments — Documentation and inline explanations are permanently gone.
- Simplified expressions — Constant-folded values or collapsed statements stay in their optimized form.
For full reverse-engineering of minified code, you need a source map (if available) or manual analysis.
AST-Based vs. Regex-Based Formatting
- AST-based formatters (Prettier, js-beautify) parse the code into an Abstract Syntax Tree, then re-print it according to formatting rules. This produces correct, consistent output even for complex syntax.
- Regex-based formatters apply pattern matching to insert line breaks and indentation. They are faster but can misformat edge cases like template literals, regex patterns, or nested ternaries.
Formatting Options
Most beautifiers let you configure:
- Indent style — Tabs vs. spaces (2 or 4 spaces being most common)
- Brace style — Same-line (
collapse) or next-line (expand) - Semicolons — Insert or omit trailing semicolons
- Quote style — Single vs. double quotes
- Max line width — Wrap long lines at a specified column
When to Beautify
- Debugging production issues when source maps are unavailable
- Reviewing third-party library code
- Reformatting inconsistent code before applying a linter
- Making copy-pasted code snippets readable
Use Case
Beautifying JavaScript is critical when debugging minified production code, reviewing obfuscated third-party scripts, or standardizing formatting across a team before adopting a code formatter like Prettier.