JavaScript Beautifier & Minifier — Free Online Tool

Pretty-print or minify JavaScript in your browser. Token-aware formatting for functions, classes, templates and regex with indent options.

Use this free online JavaScript Beautifier & Minifier directly in your browser. No signup required, no data leaves your device. Part of Utilier — a collection of 133+ developer utilities.

What is JavaScript Beautifier & Minifier?

Pretty-printing JavaScript means placing function declarations, statements, and expressions on separate lines with proper indentation based on scope depth and block nesting. This tool tokenizes the input into strings, template literals, regular expressions, and comments before formatting, so punctuation inside "use strict", `template ${expr}`, or /regex/g cannot be mistaken for code structure.

  • Beautify preserves comments, Minify removes them: Beautify moves each // line comment and /* block comment */ onto its own line and restores it verbatim, so license headers, JSDoc annotations, and section markers survive. Minify strips all comments and reports the resulting character count.
  • Scope-depth indentation: Indent is computed from brace and bracket depth, so statements inside functions, if blocks, try-catch, class bodies, and arrow function blocks are indented correctly. Object literals and array expressions nest properly too.
  • Semicolon handling: Beautify preserves semicolons exactly as authored — if the input uses ASI (Automatic Semicolon Insertion), the output does too. Minify keeps semicolons where required by the grammar but removes redundant ones.
  • Minify is conservative: It collapses whitespace, removes comments, strips spaces around operators where safe, and shortens function declarations. It does not rename variables, mangle property names, or apply dead-code elimination — so the output is byte-smaller but semantically identical.
  • Obfuscate for code protection: Adds variable name mangling (_a, _b, _c), hex-encodes string literals (\x48\x65\x6c\x6c\x6f), and injects anti-debugging traps (debugger statements in timed intervals) to make reverse engineering harder. Not encryption, but raises the bar significantly.
  • Eight indent presets: 1, 2, 3, 4, 6, and 8 spaces plus 1 tab and 2 tabs. Two spaces is the JavaScript/TypeScript standard (Airbnb, Google, Standard); tabs are for accessibility-focused projects.

Why use the JavaScript beautifier?

Minified JavaScript is unreadable, and browser DevTools cannot tell you why a function behaves unexpectedly. Formatting restores structure so you can see scopes, closures, and control flow at a glance.

  • Reveals what a bundler produced: Beautify the output from webpack, Rollup, esbuild, or Parcel and you can see the actual runtime code: polyfilled features, injected helpers, tree-shaken exports, and scope hoisting transformations your source did not explicitly show.
  • Finds shadowed variables and closure bugs: Once each statement is on its own line with proper indentation, a var declaration shadowing an outer parameter or a closure capturing the wrong loop variable becomes immediately visible.
  • Makes control flow legible: Deeply nested if-else, try-catch-finally, and callback pyramids are unreadable when minified. Indentation shows you the actual execution paths and error boundaries.
  • Reviewable diffs: A one-line minified file diffs as a single changed line. Beautify both revisions with the same indent width and reviewers can see which function or condition changed.
  • Byte measurement before compression: Minify prints the exact output length, so you can compare two implementation approaches, measure the cost of polyfills or feature flags, and see gzip/Brotli savings.
  • Code protection for client logic: Obfuscate proprietary algorithms, game logic, or business rules before shipping to the client. Makes casual inspection and automated scraping significantly harder.
  • Runs locally: Nothing is uploaded. Third-party scripts, internal tools, unreleased features, and client code stay in the browser.

When to use the JavaScript beautifier

Reach for it when code is unreadable, when you need to understand a production bundle, or when preparing code for deployment.

  • Reading a minified .js file from a CDN, browser Sources panel, or competitor's site to understand implementation details.
  • Debugging third-party libraries or vendor code where source maps are unavailable or out of sync.
  • Auditing a production bundle to check what polyfills, runtime helpers, or injected code a build tool added.
  • Normalizing formatting on a codebase edited by multiple people before committing, so diffs reflect logic changes rather than whitespace.
  • Minifying standalone scripts — bookmarklets, browser extensions, email templates, embedded widgets — without setting up a build pipeline.
  • Obfuscating proprietary client-side algorithms, game mechanics, or business logic to deter reverse engineering.
  • Checking whether license headers, source map comments, or feature flags survived the build process.
  • Preparing readable code snippets for documentation, bug reports, Stack Overflow posts, or teaching materials.

How to use the JavaScript beautifier

One input pane, one output pane, three actions. The indent setting affects Beautify only.

  1. Paste or upload your JavaScript: Paste into the "JS in" pane, or press Upload .js to load a file. The picker accepts .js, .mjs, and .cjs extensions, and the tool validates the content for balanced braces before loading.
  2. Choose an indent width: 1, 2, 3, 4, 6, or 8 spaces, or 1 or 2 tabs. Two spaces matches the Airbnb, Google, and Standard.js style guides; pick whatever the repository already uses to avoid whitespace-only diffs.
  3. Press Beautify: Each statement goes on its own line, blocks are indented by scope depth, operators get spacing (a+b becomes a + b), and comments are placed on their own lines with text unchanged. Semicolons are preserved exactly as authored.
  4. Or press Minify: All comments are stripped, whitespace collapses, unnecessary semicolons are removed, and spaces around operators and punctuation shrink to the minimum. The status line reports output length, e.g., "Minified (2847 chars)".
  5. Or press Obfuscate: Applies minification plus variable name mangling (_a, _b), hex-encodes string literals, and injects debugger traps. The result is much harder to reverse-engineer but runs identically. Adds ~15–30% size vs plain minify.
  6. Scan the result: Look for shadowed variables, unexpected closures, deeper nesting than intended, or missing semicolons in statement positions (if using ASI). Mismatched braces show as incorrect indentation.
  7. Copy or download: Use the controls on the output pane. If you edited the input, re-run the action; the output does not auto-update.

Key features

  • Token-aware parsing: The input is tokenized into strings, template literals, regex, comments, and code first, so punctuation inside "string", `template`, or /regex/ is never treated as structure.
  • Comments preserved on beautify: Both // line comments and /* block comments */ are swapped for placeholders during formatting and restored byte-for-byte on their own lines, so JSDoc, license headers, and annotations stay intact.
  • Function and class formatting: Function declarations, arrow functions, async functions, class bodies, and method definitions all indent correctly. Supports modern syntax including optional chaining (?.), nullish coalescing (??), and private fields (#field).
  • Template literal support: Multi-line template strings with ${expression} interpolations are preserved as single tokens, so embedded newlines and punctuation do not break formatting.
  • Regex literal detection: Regular expressions like /[a-z]+/gi are recognized and left as single tokens, so slashes and brackets inside the pattern do not confuse the parser.
  • Conservative minification: Whitespace and comments only, no identifier renaming or dead code removal in Minify mode. Obfuscate mode adds mangling and encoding.
  • Character-count feedback: Minify and Obfuscate report exact output length, giving you quick before-and-after measurements without a build step.
  • ASI (Automatic Semicolon Insertion) aware: Beautify does not add or remove semicolons — it preserves the style of the input, whether semicolon-heavy or ASI-reliant.

Common use cases

  • Reverse-engineering bundled code: Beautify a production bundle to see how a framework, library, or competitor implemented a feature.
  • Debugging without source maps: Format third-party scripts or legacy code where source maps are missing, broken, or point to unavailable sources.
  • Audit build output: Inspect what a bundler actually emitted — polyfills, runtime helpers, injected code — to understand size bloat or unexpected behavior.
  • Pre-commit normalization: Apply consistent indentation to files edited by multiple people, so future diffs are meaningful.
  • Standalone minification: Shrink bookmarklets, user scripts, browser extension content scripts, or email template scripts where a build tool would be overkill.
  • Code obfuscation: Protect proprietary game logic, business algorithms, or licensing checks from casual inspection and automated scraping.
  • Educational examples: Produce clean, readable code snippets for tutorials, documentation, or bug reports.

Examples

Actual output from this tool. Indent is 2 spaces unless noted.

Beautify minified function with closure

function counter(){let n=0;return function(){return ++n}}
function counter() { let n = 0; return function() { return ++n }
}

The nested function is indented one level deeper, showing the closure relationship. Spacing around operators is normalized (n=0 becomes n = 0), and each statement lands on its own line.

Beautify arrow functions and template literals

const greet=name=>`Hello, ${name}!`;const users=["Alice","Bob"].map(greet);
const greet = name => `Hello, ${name}!`;
const users = ["Alice", "Bob"].map(greet);

Arrow function syntax is preserved, the template literal stays on one line (no embedded newlines), and the array method chain formats naturally.

Minify with comment and whitespace removal

// Utility function
function add(a, b) { // Return sum return a + b;
}
function add(a,b){return a+b;}

From 73 characters to 29. Both comments are removed, all indentation and newlines collapse, and spaces around operators are stripped where grammatically allowed.

Obfuscate for code protection

function secret(key) { return key === "admin" ? "granted" : "denied";
}
function secret(_a){return _a==="\x61\x64\x6d\x69\x6e"?"\x67\x72\x61\x6e\x74\x65\x64":"\x64\x65\x6e\x69\x65\x64";}setInterval(function(){debugger;},1000);

The parameter key is renamed to _a, string literals are hex-encoded, and an anti-debugging trap (debugger in a loop) is injected. The code runs identically but is much harder to read and modify.

Regex and string literals handled correctly

const email=/^[^@]+@[^@]+$/;const msg="Match: email@domain.com";
const email = /^[^@]+@[^@]+$/;
const msg = "Match: email@domain.com";

The @ inside the regex and the @ inside the string are both preserved as content, not treated as structure or operators, because the tokenizer lifts literals out before formatting.

Technical reference

The JavaScript language rules and conventions this tool relies on:

Specification
ECMAScript 2024 (ES15) syntax support, including modern features: optional chaining, nullish coalescing, private class fields, top-level await
Comment syntax
// line comments and /* block comments */. No preprocessor directives like #ifdef — those are non-standard
Whitespace tokens
Space, tab, line feed, carriage return, and form feed. Whitespace is significant only inside strings and template literals
Semicolon rules
Optional in many positions due to ASI. This tool preserves semicolons exactly as authored in Beautify mode; Minify removes redundant ones
Error handling
JavaScript throws SyntaxError for malformed code. This tool does basic validation (balanced braces, valid tokens) but does not run a full parser — broken code may format incorrectly
Indent convention
The Airbnb JavaScript Style Guide, Google JavaScript Style Guide, and Standard.js all specify 2 spaces per level. Node.js core uses 2 spaces
Regex literals
Delimited by / characters with optional flags (g, i, m, s, u, y). Ambiguous with division operator — context-dependent parsing required
Template literals
Delimited by backticks (`), support ${expression} interpolation and multi-line strings. Introduced in ES6, now universally supported
Arrow functions
Concise syntax: x => x * 2 or (a, b) => { return a + b }. No this binding, cannot be used as constructors
Obfuscation limits
Not encryption. Obfuscated code can be reverse-engineered with time and tools. Keeps API secrets and sensitive logic on the server

Common mistakes to avoid

Using obfuscation as a security measure for API keys or secrets

Why it happens: Obfuscation makes code harder to read but is not encryption. Any JavaScript delivered to the client can be inspected, debugged, and reverse-engineered with browser DevTools or deobfuscation tools. Hex-encoded strings can be decoded instantly, variable names can be inferred from context, and debugger traps can be disabled. If an API key, password, or authentication token is embedded in client code — obfuscated or not — it is exposed to anyone who looks.

How to avoid it: Keep all secrets on the server. Use server-side API endpoints that require authentication, and issue short-lived tokens (JWT, OAuth) from the backend. If you must protect client-side business logic, obfuscation raises the bar for casual inspection, but treat it as deterrence rather than security. For truly sensitive operations, move the logic server-side where the source never ships to the client.

Minifying code without testing or source maps

Why it happens: Minification is usually safe, but edge cases exist: ASI (Automatic Semicolon Insertion) can interact with whitespace removal in unexpected ways, and tools that do not properly tokenize regex or template literals can mangle them. If you minify without testing, a subtle syntax error may only appear in production. Without source maps, debugging a minified stack trace is nearly impossible — line numbers point to a single compressed line, and variable names are unrecognizable.

How to avoid it: Always test minified output in a staging or local environment before deploying. Generate source maps during the build so errors map back to original source. For this tool's Minify, it is conservative (no identifier renaming, no dead-code removal), so breakage is rare, but for any build-time minifier (Terser, esbuild, Closure Compiler), source maps are non-negotiable for production.

Expecting beautification to fix syntax errors

Why it happens: Beautify re-indents and spaces code based on brace depth and token boundaries, but it does not parse the full JavaScript grammar or check for syntax errors. If the input has unbalanced braces, a missing closing quote, or an invalid token, the formatter guesses at structure and produces malformed output. There is no error message because the tool is not a compiler — it is a whitespace transformer that assumes the input is valid.

How to avoid it: Run the code through a linter (ESLint) or the browser console first to catch syntax errors. If Beautify produces garbled output, check the input for missing braces, unterminated strings, or stray characters. The indentation itself is a clue: if a block is indented much deeper or shallower than expected, a brace is probably missing.

Removing all comments when they carry license notices

Why it happens: Many open-source JavaScript libraries include license headers in comments — MIT, BSD, Apache 2.0 — and those licenses require the notice to be preserved in distributed copies. This tool's Minify and Obfuscate both strip all comments, including license banners, so a naive minify-and-deploy workflow can quietly violate the terms of a dependency's license.

How to avoid it: Check the input for license headers before minifying. If present, either configure a build-time minifier to preserve /*! ... */ comments (Terser and esbuild support this), or re-add the header to the top of the output manually. For bundled code, collect all license text into a single LICENSES file or banner comment so it is not fragmented across modules.

Obfuscating code and expecting it to run faster

Why it happens: Obfuscation renames variables to shorter names, which saves bytes, but modern JavaScript engines optimize based on actual runtime behavior (inline caching, JIT compilation), not source code structure. Shorter variable names do not speed up execution, and the added anti-debugging traps (debugger statements in loops) can actually slow the code down when DevTools are open. Obfuscation is for code protection, not performance.

How to avoid it: Use minification (not obfuscation) to reduce file size, and enable gzip or Brotli compression on the server for the real bandwidth savings. For performance, focus on algorithmic improvements, reducing bundle size (tree shaking, code splitting), and leveraging browser caching. Obfuscate only when you need to deter reverse engineering, and measure the size cost before deploying.

Frequently asked questions

How do I beautify minified JavaScript from a production site?

Copy the script text — from the browser's Sources panel, a <script> tag in view-source, or the .js file itself — paste it into the input pane, pick an indent width, and press Beautify. Each statement lands on its own line, blocks are indented by scope depth, and operators get spacing. Comments are kept if present (most production code has them stripped). For very large files, use the Upload button instead of pasting to avoid clipboard limits. The result is for reading and debugging; keep the original minified version if you are serving the file.

What is the difference between Minify and Obfuscate?

Minify removes comments and whitespace and strips redundant semicolons, making the code smaller but still readable if you know JavaScript syntax. Obfuscate goes further: it minifies, renames variables to meaningless short names (_a, _b), hex-encodes string literals (\x48\x65\x6c\x6c\x6f for "Hello"), and injects anti-debugging traps (debugger statements in setInterval loops). Obfuscate makes reverse-engineering much harder but adds 15–30% size vs plain minify and is still not secure encryption. Use Minify for production builds, Obfuscate when you need to protect proprietary client-side logic.

Does minifying JavaScript actually improve page load speed?

Yes, but the savings depend on the original file size and whether text compression (gzip, Brotli) is enabled. Minifying can reduce raw JavaScript size by 20–40%, but after Brotli the actual transfer saving is often only 5–15% because compression already handles repeated indentation and long variable names well. The bigger wins for load speed are reducing the number of scripts (bundling), removing unused code (tree shaking), and serving scripts with proper caching headers. Minify is still worth doing — every byte counts — but it is one piece of a larger performance strategy.

Should I use 2 spaces or 4 spaces for JavaScript indentation?

Two spaces is the JavaScript and TypeScript community standard. The Airbnb JavaScript Style Guide, Google JavaScript Style Guide, Standard.js, and Prettier all default to 2 spaces. Node.js core code uses 2 spaces. The reasoning: JavaScript has deeply nested callbacks, promise chains, and object literals, and 2-space indents keep line length manageable without sacrificing readability. Four-space indents are common in Python and Java but are rare in the JavaScript ecosystem. Pick 2 spaces unless the repository you are working in has a different convention already established.

Will beautifying JavaScript change how my code runs?

No, outside of strings and template literals, JavaScript whitespace is insignificant. Adding or removing indentation, newlines, and spaces around operators cannot alter variable scope, hoisting, closure behavior, or computed values. The one thing to watch: if you are using ASI (Automatic Semicolon Insertion) and not writing explicit semicolons, be careful with return, break, and continue statements — a newline after return can insert an unwanted semicolon. This tool preserves semicolons exactly as authored, so ASI behavior does not change. Comments are kept in Beautify mode, so JSDoc annotations and source map references survive.

Can this tool format TypeScript or JSX?

It will mostly work, but not perfectly. TypeScript type annotations (: string, <T>, as const) and JSX tags (<Component />) use syntax that overlaps with JavaScript operators, so the formatter may mis-indent type expressions or JSX children. For serious TypeScript or React work, use a TypeScript-aware formatter like Prettier or the built-in formatting in VS Code. Use this tool for the compiled JavaScript output — the .js files that webpack, tsc, or esbuild produce — where TypeScript syntax is already gone.

Why does the obfuscated code include 'debugger' statements?

Obfuscate injects anti-debugging traps: debugger; statements inside setInterval loops that fire repeatedly. When a user opens browser DevTools, the debugger statement pauses execution, making it harder to inspect variables or step through the code. It is a deterrent, not a block — a determined reverse-engineer can disable breakpoints or patch the code — but it raises the effort required. If you do not want the traps, use Minify instead of Obfuscate.

References

Privacy and availability

  • Runs entirely in your browser — zero server processing
  • No signup or account required
  • Works offline once loaded
  • Fast, lightweight, no external dependencies
  • Available as a browser extension for Chrome and Firefox