JavaScript Minifier

Minify and compress JavaScript scripts directly in your browser. Eliminates redundant whitespace, strips debugging statements and comments, preserves required license notices, and optionally shortens local variable identifiers without altering execution semantics.

Options
Input
Lines24
Size470 B
Minified
/*! MyLib v1.2.3 | MIT License | (c) 2026 Example Corp */
function calculateTotal(items,taxRate){let total=0;for(const item of items){total+=item.price*item.quantity;}const withTax=total*(1+taxRate);console.log("total:",withTax);return withTax;}const cart=[{price:19.99,quantity:2},{price:5.5,quantity:4},];calculateTotal(cart,0.08);
Minified in <1ms
Output2 lines · 333 B

Removed 2 comments.

Preserved 1 license comment (/*! ... */).

All minification runs 100% locally in your browser — your code never leaves your device.

Operation Guide

Step 1

Load Source Script

Paste or type JavaScript code into the editor, or drag and drop a .js, .mjs, .cjs, or .txt file directly into the input area.

Step 2

Configure Minification Rules

Toggle comment removal, license banner preservation, whitespace compression, local variable mangling, or console.* stripping.

Step 3

Inspect & Export Compressed Code

Review the minified code in the output panel, then copy the result or download minified.min.js.

Transformation Examples

1. Multi-line Function & Loop → Compact Production Script

Input · Formatted Source (318 bytes)

function calculateTotal(items, taxRate) {
  // Sum up all item prices
  let total = 0;

  for (const item of items) {
    total += item.price * item.quantity;
  }

  /* Apply tax rate to the subtotal */
  const withTax = total * (1 + taxRate);

  return withTax;
}

Output · Minified (165 bytes · ↓ 48.1%)

function calculateTotal(items,taxRate){let total=0;for(const item of items){total+=item.price*item.quantity;}const withTax=total*(1+taxRate);return withTax;}

2. Open-Source License Preservation & Internal Comment Stripping

Input · License Header + Routine Comments

/*! MyLib v1.2.3 | MIT License | (c) 2026 Example Corp */
function greet(name) {
  // Say hello
  return "Hello, " + name + "!";
}

Output · License Retained, Inner Comments Removed

/*! MyLib v1.2.3 | MIT License | (c) 2026 Example Corp */
function greet(name){return"Hello, "+name+"!";}

3. Lexical Scope Variable Mangling (Safe Parameter & Local Shortening)

Input · Standard Local Identifiers

function calculateTotal(items, taxRate) {
  let total = 0;
  for (const item of items) {
    total += item.price * item.quantity;
  }
  return total * (1 + taxRate);
}

Output · Mangled Parameters & Locals (a, b, c, d)

function calculateTotal(a,b){let c=0;for(const d of a){c+=d.price*d.quantity;}return c*(1+b);}

4. Debug Statement Stripping (Clean Production Build)

Input · console.time, log, info, timeEnd

function fetchUserData(userId) {
  console.time('fetch');
  console.log('Fetching user:', userId);
  const result = db.query(userId);
  console.info('Query completed');
  console.timeEnd('fetch');
  return result;
}

Output · Purged Console Calls (Zero Runtime Overhead)

function fetchUserData(userId){const result=db.query(userId);return result;}

Processing Rules & Configuration Reference

OptionDefaultExecution Mechanism & Safety Boundary
Remove commentsEnabledStrips single-line (//) and block (/* ... */) comments. Literal string contents, template string literals, and regular expressions are shielded against accidental truncation.
Keep /*! license */EnabledIsolates comments prefixed with an exclamation mark (/*!) and re-attaches them at the top of the generated code to satisfy MIT, Apache, and BSD attribution requirements.
Compress whitespaceEnabledCollapses redundant spaces, tabs, and line breaks down to the minimal valid separator. Automatically inserts semicolons where Automatic Semicolon Insertion (ASI) would fail.
Mangle namesDisabledScans function declarations, arrow parameters, and block scopes (let, const, var), remapping local identifiers to short tokens (a, b, c…). Preserves global variables and object properties.
Strip console.*DisabledDetects console.log, warn, error, info, table, and time invocations. Statement positions are eliminated; expression positions resolve safely to void 0.

Lexical Analysis & Token Boundary Disambiguation

JavaScript cannot be safely compressed with global regular expressions. Naive replacement transforms like stripping // corrupt valid URLs ("https://api.domain.com") and string content, while removing whitespace inside template strings breaks layout interpolation. Minification requires a stateful lexical analyzer that segments code into distinct token categories:

State 1

Literal Shielding

Single-quoted, double-quoted, and backtick template literals are parsed with escape-sequence tracking (\\). String contents remain entirely isolated from whitespace stripping.

State 2

Slash Disambiguation

Determines whether a forward slash represents a division operator (a / b), comment prefix (//, /*), or regex literal (/pattern/flags) based on the preceding significant token.

State 3

Interpolation Nesting

Tracks curly-brace depth inside template string interpolations (`val: ${nested}`), preventing embedded objects or sub-expressions from prematurely terminating the template token.

State 4

Operator Preservation

Distinguishes multi-character punctuators (===, >>>, ?., ??=) and inserts required spaces between identical adjacent unary operators (+ +a vs ++a).

ECMA-262 Automatic Semicolon Insertion (ASI) Constraints

Under ECMA-262 specifications, semicolon insertion is triggered when a token violates JavaScript grammar rules across a line terminator. When whitespace and newlines are stripped during minification, the conditions that previously triggered ASI disappear unless explicit semicolons are injected:

Restricted Productions Hazard

JavaScript strictly prohibits a line terminator between keywords such as return, throw, yield, await, break, and continue and their subsequent expression. If a newline is removed without inserting a semicolon, a function returning an object literal can unexpectedly alter its return value.

// Unminified Source:
return\n{ success: true }; → returns undefined under ASI
// Minifier Output:
return;{success:true}; → Semicolon preserved; logic matches original

Leading Token Traps ((, [, /, +, -)

When a statement begins with an open parenthesis or bracket on a new line, omitting a semicolon before it causes the runtime engine to parse it as an argument list invocation or computed property lookup on the preceding statement, triggering severe runtime exceptions.

// Unminified Source:
const a = b\n(items).forEach(...)
// Naive Compression (Broken):
const a=b(items).forEach(...) → Calls b as function!
// Safe Minification:
const a=b;(items).forEach(...) → Semicolon inserted

Scope Analysis & Identifier Mangling Boundaries

Identifier mangling renames variables to single- and double-character symbols (a, b, c... aa, ab...) to yield an additional 15–25% reduction in token weight. However, lexical boundaries dictate strict rules regarding which symbols can be safely transformed:

Identifier CategoryMangle SafetyTechnical Rationale & Runtime Constraints
Function Parameters & Local VariablesSafe (Mangled)Variables declared with let, const, or var whose lexical reference remains strictly inside the local scope. Never exposed to external caller boundaries.
Object Properties (obj.prop, { prop: val })Unsafe (Preserved)Renaming property names breaks dynamic lookups (obj[key]), serialized JSON schemas, backend database API responses, and browser DOM access. Must remain untouched.
Global Variables & Web APIsUnsafe (Preserved)Identifiers such as window, document, fetch, localStorage, and built-in objects (Math, Promise) cannot be reassigned without corrupting the host execution environment.
Top-Level Exported DeclarationsUnsafe (Preserved)Named exports (export function calculate()) constitute the public API of an ES module. Mangling top-level names breaks external importing consumers.

Execution Budget: Network Transfer vs V8 Engine Parse Overhead

Optimizing JavaScript is not solely about network transfer speed. Modern browser engines (including Chromium V8, WebKit JavaScriptCore, and Gecko SpiderMonkey) incur heavy main thread compute costs during script ingestion:

Scanner & Tokenizer Phase

Before code can run, the browser scanner reads characters sequentially from network buffers. Stripping 50% of whitespace and comments eliminates millions of redundant scanner loops on the main thread during initial page load.

Ignition Bytecode Generation

V8's Ignition interpreter generates bytecode directly from AST nodes. Compact code reduces AST node depth and memory allocations, directly lowering Total Blocking Time (TBT) and improving Interaction to Next Paint (INP).

Brotli / Gzip Entropy Synergy

Compressing variable names to short tokens reduces the distinct symbol count in Huffman trees. Minified JavaScript yields an additional 20–30% size reduction after Brotli compression compared to compressed raw code.

Toolchain Matrix: Client-Side Minifier vs CLI Bundlers

Understanding when to use an interactive browser-based tool versus full build-system tooling ensures clean development workflows:

Feature DimensionOnline JavaScript MinifierCLI Tooling (Terser / esbuild / SWC)
Setup & EnvironmentZero setup; instant browser executionRequires Node.js/Rust runtime, package.json, and CI config
Optimal WorkloadsInline HTML scripts, bookmarklets, debugging snippets, vendor filesMonorepos, multi-file bundling, tree-shaking, production builds
Source Maps GenerationSingle-file standalone outputFull multi-file .map file generation for production debugging
Whole-Program Tree ShakingSingle-file lexical passCross-module dead-code elimination and symbol graph pruning

Frequently Asked Questions

What is the difference between JavaScript minification, uglification, and obfuscation?

Minification eliminates whitespace, indentation, line breaks, and comments to reduce raw byte size. Uglification (mangling) goes one step further by renaming local variables and parameters to short tokens (a, b, c) while keeping program logic and AST semantics identical. Neither technique is obfuscation: neither encrypts strings nor alters control flow. Obfuscation intentionally introduces dead code, string encoding, and control flow flattening to deter reverse engineering at the cost of runtime performance, whereas minification focuses strictly on execution and transfer efficiency.

Will minifying JavaScript break code execution or alter runtime behavior?

Valid JavaScript will not break when processed by a syntax- and token-aware minifier. Safe compression protects string literals, regex patterns, template string interpolations, and automatically inserts semicolons where Automatic Semicolon Insertion (ASI) rules require them. Breakage only occurs if the source code already contains syntax errors, or if you rely on reflective identifier names (such as Function.prototype.name or arguments.callee) while enabling Mangle mode.

Why is JavaScript minification still necessary if web servers enable Gzip or Brotli compression?

Minification and HTTP compression operate at different layers. Gzip and Brotli compress byte streams over the wire using sliding-window dictionaries, but long identifier names and redundant whitespace inflate token entropy and dictionary overhead; minifying reduces post-Brotli transfer sizes by an extra 20–30%. More importantly, compression only optimizes network download. The browser main thread (e.g. V8) must decompress and parse every raw character into bytecode. Minification directly reduces the raw volume that the JavaScript engine scanner and parser must process, significantly improving Interaction to Next Paint (INP) and Total Blocking Time (TBT).

How does the minifier prevent Automatic Semicolon Insertion (ASI) syntax breakage?

ECMA-262 specifications allow optional semicolons when statements terminate at line boundaries. Naively removing line breaks causes adjacent statements to collide into syntax errors. The minifier tracks token boundaries, restricted productions (return, throw, yield, await, break, continue), and leading token hazards ((, [, /, +, -, and backticks). When collapsing whitespace between tokens where a stripped newline would alter grammar interpretation or trigger an exception, an explicit semicolon is inserted automatically.

Why does Mangle mode only rename local variables instead of object properties?

JavaScript is dynamically typed. Object property names (e.g. user.id, config.timeout, { key: value }) are frequently accessed via dynamic bracket notation (obj[prop]), parsed from backend JSON payloads, or shared across third-party libraries and browser DOM APIs. Renaming property names without full-program static analysis and explicit property mapping breaks API contracts and runtime execution. Mangle mode only shortens variables and function parameters whose lexical scopes are strictly bounded within local functions or blocks.

Why does stripping console statements produce void 0 instead of deleting the line?

When console.log() appears as a standalone statement, the minifier eliminates the statement and its delimiter entirely. However, when a console.* call resides inside an expression (such as ternary operators isValid ? console.log(data) : null or logical short-circuits debug && console.warn(msg)), deleting the tokens leaves an incomplete syntax tree. The minifier replaces the call with void 0 (the standard JavaScript expression evaluating to undefined), ensuring syntactical validity while removing the debug invocation.

Why should /*! license */ comments be preserved in production distributions?

Open-source licenses—including MIT, BSD-2-Clause, BSD-3-Clause, and Apache 2.0—legally require that copyright notices and permission terms remain attached to all redistributions, including production web client assets. The /*! convention is the established open-source standard signaling minifiers and bundlers to retain the legal header banner while stripping all internal development comments and source annotations.

Can minified JavaScript be reversed or decompiled back to original source code?

Code formatters and beautifiers can reconstruct visual structure, indentation, and line breaks to make minified scripts readable and debuggable. However, stripped comments and mangled local identifiers (e.g. variables renamed from customerBillingAddress to a) cannot be algorithmically recovered because the original identifier names are discarded during compilation. To restore original file names, line numbers, and variable symbols in developer tools, original Source Maps (.map files) generated during the build process are required.