Enforcing Consistent Whitespace in JavaScript: The no-irregular-whitespace Rule


  • Debugging challenges
    Inconsistent whitespace, like mixing tabs and spaces, can make code harder to read and debug.
  • Parsing problems
    Some uncommon whitespace characters might confuse the parser, especially in older ECMAScript 5 parsers, leading to errors.

Customizing the Rule

While the rule aims for cleaner code, it offers flexibility through options:

  • skipRegExps (default: true)
    Enables irregular whitespace within regular expressions, where some special characters might be valid for patterns.
  • skipComments (default: true)
    Permits irregular whitespace in comments, where formatting might be less critical.
  • skipStrings (default: true)
    Allows any whitespace characters within string literals, which might be necessary for special formatting.


Invalid Code (Irregular Whitespace)

function greet() {  // Notice the non-breaking space after the function name
\u00A0console.log("Hello, world!");
}

This code uses a non-breaking space (represented by \u00A0) after the function name. ESLint would flag this as an error because it's not a regular space or tab.

Valid Code (Regular Whitespace)

function greet() {
  console.log("Hello, world!");
}

This code uses regular spaces for indentation, which is what no-irregular-whitespace enforces.

Example with Options

const message = "This string has   a   triple space" // Allowed due to skipStrings

// This comment can have any whitespace because of skipComments
/* 
  This comment uses a mix of tabs and spaces, 
  which wouldn't be allowed in non-commented code.
*/

const regex = /\t\w+\t/; // Allowed due to skipRegExps (tab characters in the pattern)

In this example:

  • The regular expression can have tab characters because skipRegExps is enabled by default.
  • The comment can have mixed tabs and spaces because skipComments allows it.
  • The string literal can have triple spaces because skipStrings is enabled by default.


  1. no-mixed-spaces-and-tabs
    This rule enforces consistent indentation using either spaces or tabs, preventing the mix that can cause issues.

  2. no-trailing-spaces
    This rule disallows trailing whitespace (spaces or tabs) at the end of lines, promoting cleaner code.

  3. prettier
    This is a popular code formatter that can be integrated with ESLint. It automatically formats your code according to a chosen style guide, ensuring consistent whitespace and formatting throughout your project.

  • prettier takes a more comprehensive approach, handling all aspects of code formatting, including whitespace, indentation, and other stylistic elements based on the chosen configuration.

  • no-trailing-spaces tackles a specific type of irregular whitespace, removing unnecessary spaces at the end of lines.

  • no-mixed-spaces-and-tabs focuses solely on indentation consistency, ensuring you use either spaces or tabs throughout your codebase.