JavaScript Minifier

Minify JavaScript by removing whitespace, comments, and unnecessary characters to reduce file size.

Input JavaScript

Minified JavaScript

function  calculateTotal(items){let  total=0;for (let  i=0;i<items.length;i++){const  item=items[i];total+=item.price*item.quantity;}return  total;}function  formatCurrency(amount){return  '$'+amount.toFixed(2);}const  cart=[{name:'Apple',price:1.50,quantity:3},{name:'Banana',price:0.75,quantity:5}];const  total=calculateTotal(cart);console.log('Total:',formatCurrency(total));

Compression Results

Original Size

511 bytes

Minified Size

379 bytes

Bytes Saved

132 bytes

Reduction

25.8%

Note: This is a basic minifier. For production use, consider tools like Terser, UglifyJS, or esbuild which provide better minification and code safety.

What Is JavaScript Minification?

JavaScript minification is the process of removing all unnecessary characters from source code without changing its functionality. Those unnecessary characters include whitespace, newlines, comments, and block delimiters. The result is a smaller file that downloads faster and executes just as correctly as the original.

Every byte you send over the network costs time. On a slow mobile connection, a bloated script can delay the first interactive moment of a page by hundreds of milliseconds. Minification is one of the cheapest performance wins available because it requires zero changes to your logic — it simply strips the fat that humans need (comments, indentation) but browsers do not.

This JavaScript minifier calculator accepts raw JS source, applies a sequence of regular-expression transformations, and shows you the minified output alongside a compression summary. The summary reports the original byte count, the minified byte count, the total bytes saved, and the percentage reduction — so you know at a glance whether minification is worth it for a given file.

Minification is distinct from obfuscation (which renames variables to meaningless identifiers) and from bundling (which merges multiple files into one). All three techniques are often combined in modern build pipelines, but minification alone is what reduces whitespace and comments, and it is always the first step.

Compression Percentage Formula

reduction% = (1 - minifiedLength / originalLength) × 100

Where:

  • originalLength= Number of characters (bytes) in the original JS source
  • minifiedLength= Number of characters (bytes) after minification
  • reduction%= Percentage of the original size that was removed

How the JS Minifier Calculator Works

The minifier applies a deterministic chain of regular-expression replacements to the input text. Understanding the order matters because each step produces the input for the next one.

  1. Strip single-line comments — Any text from // to end of line is removed, using a negative lookbehind to avoid stripping the // inside URLs such as https://.
  2. Strip multi-line comments — Everything between /* and */ (including across line breaks) is removed.
  3. Trim lines — Leading and trailing whitespace on every line is stripped.
  4. Remove empty lines — Lines that contain only whitespace after trimming are deleted.
  5. Collapse newlines — All remaining newline characters are removed, merging the code onto a single line.
  6. Collapse internal spaces — Multiple consecutive spaces are reduced to a single space.
  7. Remove spaces around operators — Spaces adjacent to { } ( ) [ ] ; , = + - * / < > ! & | ? : are removed.
  8. Restore keyword spacing — Because step 7 may have removed the required space after keywords like var, let, const, function, return, if, else, for, while, new, and typeof, each keyword is rewritten with a trailing space.

After all replacements, the string is trimmed of any outer whitespace. The result is the minified output displayed in the output panel.

The compression summary then computes:

  • Original size: input.length (characters, which equal bytes for ASCII-range JS)
  • Minified size: minified.length
  • Bytes saved: original.length - minified.length
  • Reduction: ((1 - minified.length / original.length) * 100).toFixed(1)

Why Minify JavaScript? Performance and SEO Impact

Page speed is a confirmed ranking signal in Google Search. The Core Web Vitals metric Largest Contentful Paint (LCP) is directly affected by how long the browser waits for render-blocking scripts to download and parse. Minifying JavaScript is one of the fastest ways to improve LCP without touching server infrastructure.

Consider a script that starts at 80 KB. A 40% reduction through minification brings it to 48 KB. On a 3G connection at roughly 1 Mbps effective throughput, that difference is about 250 ms of download time — and that is before accounting for parse time, which also scales with file size.

Beyond raw speed, minification matters for:

  • Bandwidth costs — Hosting providers and CDNs often charge by data transferred. Smaller files mean lower bills at scale.
  • Cache efficiency — A smaller file fits more easily into browser caches and CDN edge caches.
  • Mobile users — Mobile CPUs parse JavaScript more slowly than desktop chips. Fewer bytes means faster parse time.
  • Lighthouse scores — Google Lighthouse flags unminified JavaScript as an opportunity and estimates the savings, directly affecting your performance score.

Even if you use HTTP/2 or HTTP/3 multiplexing and gzip/Brotli compression, minification still helps: gzip compression ratios improve when the input has already been stripped of redundant whitespace, because the compressor finds repeating patterns more easily in dense code.

Minification vs. Compression vs. Obfuscation

These three terms are often confused. They address different problems and operate at different layers of the delivery pipeline.

Technique What It Does Reversible? Changes Logic?
Minification Removes whitespace, comments, optional semicolons Yes (beautify) No
Gzip / Brotli Compresses bytes at the network transport layer Yes (lossless) No
Obfuscation Renames variables, scrambles strings to hinder reading Difficult No (functionally)
Tree-shaking Removes unused exports at bundle time No Removes dead code

For production workflows, the recommended stack is: tree-shake first (remove dead code), minify second (remove whitespace), then serve with Brotli compression. Each layer compounds the savings of the previous one. This calculator addresses the minification layer specifically.

Limitations and When to Use Production-Grade Tools

This calculator's minifier is a regex-based approach suited for quick estimates and educational use. It handles the most common patterns — stripping comments and collapsing whitespace — but it has known limitations compared to production tools like Terser, esbuild, or SWC.

Limitations of regex-based minification include:

  • String literals — A comment-like sequence inside a string (e.g., "// not a comment") may be incorrectly stripped by a naive regex if the lookahead logic is insufficient.
  • Automatic Semicolon Insertion (ASI) — Removing all newlines can break code that relies on ASI at the end of a statement.
  • Template literals — Backtick strings containing newlines or expressions may be mangled by whitespace-collapse rules.
  • No dead-code elimination — Unused variables and unreachable branches are kept as-is.
  • No scope-aware renaming — Local variable names remain long; only Terser/UglifyJS rename them to single letters.

Production tools parse the code into an Abstract Syntax Tree (AST) before transforming it. AST-based tools are safe by construction because they understand the language grammar. They also provide additional optimizations: constant folding, inline expansion of short functions, and dead-branch elimination. For any script that ships to real users, use an AST-based tool in your build pipeline (webpack with Terser, Vite/Rollup with esbuild, Next.js built-in SWC minifier, etc.). Use this calculator to estimate potential savings and understand what minification does before setting up a pipeline.

Reading the Compression Results Panel

Once you paste JavaScript into the input area, the compression results panel updates in real time. Here is how to interpret each metric:

  • Original Size (bytes) — The character count of your raw input. For standard ASCII-range JavaScript, one character equals one byte.
  • Minified Size (bytes) — The character count of the processed output.
  • Bytes Saved — The difference: originalLength - minifiedLength. This is the amount you shave off every download of this file.
  • Reduction (%) — Calculated as ((1 - minifiedLength / originalLength) × 100), rounded to one decimal place. Typical comment-heavy source files see 20–50% reduction; tightly-written utility scripts may see only 5–15%.

A high reduction percentage does not always mean better performance in isolation. A 1 KB file reduced by 50% saves 500 bytes — negligible compared to a 200 KB library reduced by 30% that saves 60 KB. Always consider absolute bytes saved, not just the percentage, when prioritizing minification efforts across a codebase.

Worked Examples

Minifying a Simple Utility Function

Problem:

A developer has a 210-character JavaScript snippet containing a comment and indentation. What are the savings after minification?

Solution Steps:

  1. 1Original code (210 characters) includes a comment line '// Add two numbers', function declaration with indented body, and a return statement on its own line.
  2. 2After stripping the comment, collapsing whitespace, removing newlines, and removing spaces around operators, the minified output is approximately 46 characters: 'function add(a,b){return a+b;}'.
  3. 3Bytes saved = 210 - 46 = 164 bytes.
  4. 4Reduction = (1 - 46 / 210) × 100 = (1 - 0.219) × 100 = 78.1%.

Result:

164 bytes saved, 78.1% reduction — a dramatic saving driven by the removal of the verbose comment and all indentation whitespace.

Compressing a Cart Calculation Script

Problem:

The default example in the calculator has an original size of 380 characters (your actual character count will vary with your browser). Estimate the minified size and percentage reduction.

Solution Steps:

  1. 1Original input contains two multi-line functions, two single-line comments ('// Calculator function' and '// Format currency' and '// Main execution'), several blank lines, and indented for-loop bodies.
  2. 2All three comments are stripped first, removing roughly 60 characters.
  3. 3All newlines, indentation spaces, and blank lines are collapsed, removing another ~100 characters.
  4. 4Spaces around operators ({, }, (, ), =, +, *, <, ;) are removed, saving additional characters.
  5. 5Keywords (function, let, const, return, for) get their required trailing space restored.
  6. 6Final minified length is approximately 215 characters. Bytes saved ≈ 165. Reduction ≈ (1 - 215/380) × 100 ≈ 43.4%.

Result:

Approximately 165 bytes saved, ~43% reduction for a typical cart-calculation script with moderate comments and indentation.

Heavily Commented Configuration Object

Problem:

A 600-character configuration object has block comments above every key explaining its purpose. How does minification perform?

Solution Steps:

  1. 1Original: 600 characters. Roughly 280 characters are inside /* ... */ block comments describing each property.
  2. 2Step 1 — multi-line comment removal strips all block comments: output length ≈ 320 characters.
  3. 3Step 2 — whitespace and newline collapse brings it down further: output ≈ 200 characters.
  4. 4Step 3 — operator spacing removal trims a few more characters around colons and commas.
  5. 5Final minified length ≈ 195 characters. Bytes saved = 600 - 195 = 405.
  6. 6Reduction = (1 - 195/600) × 100 = (1 - 0.325) × 100 = 67.5%.

Result:

405 bytes saved, 67.5% reduction. Heavily commented code benefits most from minification because the comment text itself is voluminous and serves no runtime purpose.

Tightly Written One-Liner Utility

Problem:

A developer has a 90-character single-line arrow function with no comments and minimal whitespace. How much does minification help?

Solution Steps:

  1. 1Input: 'const clamp = (val, min, max) => Math.min(Math.max(val, min), max);' — 69 characters of code plus 21 characters of surrounding whitespace/newlines from copy-paste context.
  2. 2Comment removal: no comments present, no change.
  3. 3Whitespace collapse: removes the extra spaces around the arrow =>, spaces after commas in parameter list and inside Math calls.
  4. 4Final output: 'const clamp=(val,min,max)=>Math.min(Math.max(val,min),max);' — approximately 60 characters.
  5. 5Bytes saved = 90 - 60 = 30. Reduction = (1 - 60/90) × 100 = 33.3%.

Result:

30 bytes saved, 33.3% reduction. Compact code with no comments still benefits from operator-spacing removal, though the gains are smaller than for verbose, heavily-commented scripts.

Tips & Best Practices

  • Always keep original source files in version control — minified code is for deployment, not editing.
  • Combine minification with gzip or Brotli compression at the CDN layer for maximum byte savings.
  • Check your Lighthouse report under 'Opportunities' to see exactly which scripts benefit most from minification.
  • For React and Next.js projects, the built-in SWC minifier is enabled by default in production builds — no manual step needed.
  • Use source maps in development so browser DevTools can map minified code back to the original for debugging.
  • Minify third-party scripts you self-host, not just your own code — many npm packages ship unminified ESM builds.
  • Run minification as part of your CI/CD pipeline rather than manually, so every deployment is automatically optimized.
  • After minifying, verify the output in a staging environment to catch any edge cases before shipping to production.

Frequently Asked Questions

This calculator uses a regex-based approach that covers the most common whitespace and comment patterns but is not AST-aware. It can mishandle edge cases such as comment-like strings inside string literals, code relying on Automatic Semicolon Insertion, or template literals with embedded newlines. For production deployments, always use a proven tool like Terser, esbuild, or the built-in SWC minifier in Next.js. Use this calculator to estimate savings and understand the technique.
Minification should never change the runtime behavior of valid JavaScript. The transformations — removing whitespace and comments — do not affect the Abstract Syntax Tree of the program. However, code that is already syntactically fragile (for example, relying on ASI in non-standard ways) may behave differently after newlines are removed. Always test minified output in your target environment before deploying.
This calculator applies regex substitutions directly to the source text. Tools like Terser and UglifyJS first parse the source into an Abstract Syntax Tree, then perform transformations on the AST (renaming local variables, folding constants, eliminating dead branches), and finally serialize the AST back to code. AST-based tools are safer and achieve higher compression because they understand the program's structure, not just its text. This tool is suitable for quick estimates; AST-based tools are required for production.
Reduction depends heavily on how much comment and whitespace content exists in the source. Heavily documented source files — where block comments make up 30–50% of the text — commonly see 40–70% reduction. Tightly written utilities with few comments might see only 10–25% reduction from a regex minifier. AST-based tools that also rename variables typically achieve 5–15% additional savings on top of whitespace removal alone.
Minify first, then apply gzip or Brotli compression at the server or CDN level. Minification reduces byte count directly, and the resulting dense code compresses further because gzip finds longer repeated patterns in compact, comment-free source. The two techniques are complementary and are almost always used together in production.
Minification improves page load speed, which is a ranking signal in Google Search through the Core Web Vitals framework. Faster LCP and lower Total Blocking Time (TBT) — both partly driven by script size — lead to better Lighthouse scores and can positively influence search rankings. Minification alone will not transform a low-ranking page into a top result, but it is a standard practice that contributes to the overall performance budget.
You can re-format (beautify) minified JavaScript to make it human-readable again using tools like Prettier or online JS beautifiers, but you cannot recover the original comments or the original variable names if they were renamed during obfuscation. Whitespace and indentation can be reconstructed automatically, but comment text is gone permanently after minification. Always keep your source files (and their comments) in version control.

Sources & References

Last updated: 2026-06-05

💡

Help us improve!

How would you rate the JavaScript Minifier?

<>

Editorial Note

MyCalcBuddy Editorial Team

This page is maintained as an educational calculator reference.

Source

Formula Source: Standard Mathematical References

by Various

UpdatedLast reviewed: May 2026
CheckedFormula checks are based on standard references and internal QA review.