JavaScript Beautifier
Re-indent minified JavaScript: one statement per line, braces by depth, operators spaced, with strings, templates and regexes untouched.
const panel = document.querySelector('.panel');
function toggle(open) {
const next = open === undefined ? !panel.hidden : open;
panel.hidden = !next;
panel.setAttribute('aria-expanded', String(next));
return next
}
document.addEventListener('click', (event) => {
if(event.target.closest('.panel-toggle')) {
toggle()
}
});
Output is valid and updates as you type.
Fix the highlighted fields to update the output.
Re-indent minified or badly formatted JavaScript: one statement per line, braces by depth, operators spaced, and everything inside a string left alone.
How to use
- Paste the script, minified or otherwise.
- Pick the indent. Tabs, two spaces or four.
- Read the result. Statements are split on semicolons and braces,
else,catch,finallyandwhilestay with their closing brace, and a trailing comment stays on its line. - Copy it out. This is for reading a file, not for enforcing a house style: Prettier is the tool for that.
Example
if(a){b()}else{c()}
becomes
if(a) {
b()
} else {
c()
}
The brace is where the structure is, so that is what the formatter uses. It does not add semicolons, add braces, or decide where a long line should wrap.
Pitfalls
- A formatter without a parser cannot know where an expression should wrap. Long lines stay long; that is a job for Prettier, which does have a parser.
- It does not add missing semicolons or braces. Code that relies on automatic semicolon insertion keeps relying on it, unchanged.
- Minified code that was mangled cannot be unmangled. Variable names are gone for good; only the shape comes back.
- A regex containing a brace or a semicolon is safe here because the tokeniser keeps it whole, which is exactly what a regular expression based formatter gets wrong.
- Object literals are broken across lines the same way blocks are, since both use braces. A one-line object becomes three lines, which is usually what you want when reading.
- Semicolons inside
for ( ; ; )are separators, not statement ends, and are left in place. - The output is not byte-identical to any particular style guide. If your project has one, run its formatter afterwards.
- Source maps are not produced. This changes line numbers, so debug the original.
Compatibility
The tokeniser covers strings, template literals including nested ones, regular expressions, comments, numeric separators, BigInt, private class fields and multi-character operators through 2022 syntax. Everything runs in your browser with no upload.