JavaScript Whitespace Removal — Strip Unnecessary Spaces

Learn how JavaScript whitespace removal works as a lightweight minification step. Understand which spaces are safe to remove and which are syntactically required.

JavaScript

Detailed Explanation

JavaScript Whitespace Removal

Whitespace removal is the simplest and most common form of JavaScript minification. It strips spaces, tabs, and newlines that are not required by the language syntax, often reducing file size by 20-30% on its own.

Safe Whitespace to Remove

The following whitespace is always safe to strip:

// Before
function   add ( a ,   b ) {
    return   a + b ;
}

// After whitespace removal
function add(a,b){return a+b;}

Specifically, you can remove:

  • Leading and trailing whitespace on each line (indentation)
  • Multiple consecutive spaces between tokens (collapse to one or zero)
  • Empty lines (blank lines between statements)
  • Spaces around operators when not syntactically required (a + b becomes a+b)
  • Trailing whitespace after the last token on a line

Whitespace You Must Keep

Some whitespace is syntactically significant:

  • Between keywords and identifiersreturn value cannot become returnvalue; typeof x cannot become typeofx.
  • Inside string literals"hello world" must preserve the space.
  • Inside template literals — Backtick strings preserve all whitespace.
  • Inside regular expressions/ foo / is not the same as /foo/ (though this is rare).
  • After return, throw, yield, break, continue followed by a value on the same line.

ASI (Automatic Semicolon Insertion) Gotchas

JavaScript's ASI rules mean some newlines act as implicit semicolons. A naive whitespace remover that joins lines may accidentally merge two separate statements:

// Original (two statements due to ASI)
a = b
(function() {})()

// Incorrect whitespace removal (becomes one statement)
a=b(function(){})()

This is why production minifiers use a parser rather than simple regex to safely remove whitespace.

Whitespace Removal vs. Full Minification

Whitespace removal alone does not rename variables, eliminate dead code, or optimize expressions. It is a safe, low-risk first step, and full minifiers like Terser apply it as one of many passes.

Use Case

Whitespace removal is useful as a quick optimization for scripts that cannot undergo full minification — such as inline scripts in HTML templates, configuration files that must remain partially readable, or code that uses eval() where variable names must be preserved.

Try It — Code Minifier

Open full tool