Minify JavaScript — Reduce JS File Size

Learn how JavaScript minification works to reduce file size by removing whitespace, shortening variable names, and eliminating dead code. Includes Terser examples and best practices.

JavaScript

Detailed Explanation

How JavaScript Minification Works

JavaScript minification is the process of transforming human-readable source code into a smaller equivalent that behaves identically at runtime. A well-configured minifier can reduce JavaScript file sizes by 40-70% before compression.

What a Minifier Removes

A JavaScript minifier applies several transformations:

// Before minification
function calculateTotalPrice(items, taxRate) {
  // Sum all item prices
  let subtotal = 0;
  for (let i = 0; i < items.length; i++) {
    subtotal += items[i].price * items[i].quantity;
  }
  // Apply tax
  const total = subtotal * (1 + taxRate);
  return total;
}

After minification:

function calculateTotalPrice(t,a){let e=0;for(let l=0;l<t.length;l++)e+=t[l].price*t[l].quantity;return e*(1+a)}

Key Transformations

  1. Whitespace removal — All spaces, tabs, and newlines that are not syntactically required are stripped.
  2. Comment removal — Single-line (//) and multi-line (/* */) comments are deleted.
  3. Variable name mangling — Local variable and parameter names are shortened to single characters (subtotal becomes e). Property names on objects are not mangled because they may be referenced externally.
  4. Dead code elimination — Unreachable code paths and unused variables are removed.
  5. Constant folding — Expressions like 1 + 2 are pre-computed to 3.
  6. Statement simplificationreturn total; preceded by const total = expr; collapses to return expr;.

Popular JavaScript Minifiers

  • Terser — The de facto standard for ES6+ code, used by webpack, Vite, and Rollup.
  • esbuild — Written in Go, extremely fast; handles both bundling and minification.
  • SWC — Written in Rust, used by Next.js for production builds.
  • UglifyJS — Legacy minifier for ES5; still used in older toolchains.

Unsafe Transformations to Watch

Minifiers offer aggressive optimizations that may break code:

  • Top-level mangling can rename exports.
  • eval() and new Function() rely on variable names at runtime.
  • Reliance on Function.prototype.toString() breaks when names change.

Always test your minified output before deploying.

Use Case

JavaScript minification is essential for every production web application. Smaller JS bundles mean faster download times, quicker parsing by the browser, and improved Core Web Vitals scores — all of which directly impact user experience and SEO rankings.

Try It — Code Minifier

Open full tool