JS Formatter

Format, validate, and beautify your JavaScript and TypeScript code with custom semicolons, quotes, and indents.

Formatting
Indent:
Semicolons:
Quotes:
Braces:
Input JS/TS
Formatted JS/TS

Make an unfamiliar script readable before changing it

Formatting is often the safest first action when JavaScript arrives as a dense snippet. A readable layout exposes block boundaries, chained conditions, comments, and statement endings without requiring you to understand the program immediately. The JS Formatter accepts JavaScript or TypeScript text, displays transformed output live, and lets you choose indentation, semicolon handling, quote preference, brace position, and spacing before control-flow parentheses.

This tool uses a lightweight tokenizer rather than executing the code. It identifies comments, quoted strings, template literals, numbers, identifiers, whitespace, and individual symbols, then lays those tokens out according to the selected controls. That makes it convenient for ordinary functions, event handlers, configuration fragments, and interview-sized examples. It is not a substitute for a full JavaScript parser on syntax-heavy application code.

Walk through a small transformation

Paste a compact handler such as:

function submit(order){if(order.total>0){console.log('sending',order.id);return fetch("/orders",{method:'POST',body:JSON.stringify(order)});}else{return null;}}

Using two spaces, preserved semicolons, double quotes, same-line braces, and spacing before control parentheses produces a much more navigable result:

function submit(order) {
  if (order.total > 0) {
    console.log("sending", order.id);
    return fetch("/orders",  {
      method: "POST", body: JSON.stringify(order)
    });
  } else {
    return null;
  }
}

The exact output reflects a token formatter, not an opinionated tool such as Prettier. Object properties may remain on the same line, and spacing around complex constructs can differ from a repository style. Use the preview to improve legibility, then run the project’s canonical formatter before committing.

What each control actually changes

The Indent menu offers two spaces, four spaces, or a tab character for every nesting level introduced by braces. Match the existing codebase. Changing only one pasted file from tabs to spaces can bury functional edits in a whitespace-heavy diff.

Semicolons has Preserve, Add, and Remove choices. Remove suppresses semicolon tokens outside a detected for loop. Preserve emits semicolons that were present. Although Add is available in the interface, the current formatting routine does not synthesize missing statement terminators; it behaves like Preserve for absent semicolons. Automatic semicolon insertion is context-sensitive, so adding terminators correctly would require deeper syntax analysis.

Quotes can preserve source delimiters or prefer single or double quotes. Conversion happens only for a simple single- or double-quoted token when its content does not contain the target quote. A string containing the requested delimiter is left unchanged rather than being re-escaped. Backtick template literals stay backticks. Escape sequences are retained as token text, so review conversions involving escaped delimiters carefully.

Braces places an opening brace after the preceding construct or on a fresh line. Closing braces are indented by nesting depth, and else, catch, and finally are kept beside the preceding close brace. Space before Parens applies to recognized control keywords: if, for, while, catch, and switch. It does not add a space between an ordinary function name and its call parentheses.

Operators, commas, parentheses, braces, and comments receive specialized spacing. Because symbols are tokenized individually, multi-character operators are not always treated as a single unit despite the formatter’s operator list. This limitation is especially relevant to ===, =>, ?., ??, compound assignment, shifts, and TypeScript syntax.

A review workflow that avoids accidental rewrites

  1. Keep the original file open or committed so you can compare behavior and recover exact syntax.
  2. Paste the smallest complete function, class, or module region that provides enough context.
  3. Begin with Preserve for semicolons and quotes; change one preference at a time.
  4. Inspect regular expressions, comments, templates, optional chaining, generics, JSX, and object literals closely.
  5. Use Copy for an editor buffer or Download to save formatted.js.
  6. Run the repository formatter, TypeScript checker, linter, unit tests, and relevant runtime checks.

The formatter never evaluates input, imports dependencies, or follows URLs. Clear removes the current input and output. Download labels the blob as JavaScript even if the pasted text contains TypeScript, so rename the resulting file to .ts or .tsx when appropriate.

JavaScript constructs requiring caution

A slash can begin division, a line comment, a block comment, or a regular-expression literal depending on grammatical context. The tokenizer recognizes the two comment forms but has no dedicated regular-expression token. A regex containing braces, semicolons, or escaped slashes may therefore format incorrectly. This is the most important reason not to treat the output as validated code.

Template literals are collected through the next unescaped backtick, which preserves their text as one token. The formatter does not parse ${...} substitutions inside that token, so nested expressions are not independently indented. Tagged templates likewise receive no language-specific handling.

TypeScript adds type annotations, generics, interfaces, enums, decorators, as expressions, and overload declarations. JSX adds angle-bracket syntax whose meaning differs from comparison operators. The tool accepts this text, but it does not build a TypeScript or JSX abstract syntax tree. Prefer a parser-backed formatter for production .ts, .tsx, or .jsx files.

Whitespace can affect JavaScript through automatic semicolon insertion. A newline after return, throw, break, or continue can change meaning. Formatting a comment near one of those statements can also matter. Always execute tests after transforming code that relies on line-sensitive grammar.

Quote conversion is stylistic, not semantic normalization. It does not rewrite escape sequences to the shortest equivalent and cannot know whether snapshot output or generated source requires exact delimiters. Comments are retained, but their placement may move to a separate line. Source-map comments and tool directives deserve manual verification.

When this formatter is the right size

Use the JS Formatter to inspect code copied from a browser console, make a compact reproduction readable, untangle a generated callback while debugging, or present a short example in documentation. It is also helpful for comparing brace and indentation conventions before configuring a repository tool.

For a full project, use the formatter already encoded in package.json, editor settings, or CI. Prettier, Biome, ESLint formatting rules, and language-aware IDEs parse broader syntax and produce deterministic changes across many files. Their configuration can be reviewed and shared by every contributor. An online JavaScript beautifier is a focused scratchpad, not a replacement for that repeatable pipeline.

Do not format third-party bundles and commit the expanded result. Bundles are generated artifacts, may include license constraints, and become difficult to update after wholesale cosmetic changes. If a production bundle needs investigation, beautify a copy and use source maps to locate canonical source.

Diagnosing surprising results

Selecting Add did not create missing semicolons. The current option preserves existing semicolon tokens but does not infer new statement boundaries. Use a parser-aware formatter or linter autofix when explicit semicolons are required.

An arrow function has strange spaces. => is seen as individual symbols, so modern multi-character operators can expose tokenizer limitations. Revert that region and format it with project tooling.

A regular expression was broken across structure. The tokenizer does not distinguish regex literals from division. Do not use the transformed result for that snippet.

Single quotes were requested, but one string stayed double-quoted. Conversion is skipped when the content already contains a single quote. This avoids producing an invalid unescaped delimiter.

TypeScript output is not conventionally wrapped. The tool performs general token layout and has no TypeScript AST or print-width engine. Run the repository’s TypeScript-capable formatter.

JS Formatter FAQ

Does it validate JavaScript syntax?

No. Output appearing structured does not prove that braces, declarations, modules, or expressions are valid. Use the runtime parser, TypeScript compiler, or lint tool appropriate to the source.

Can it beautify TypeScript?

It can make simple TypeScript text more readable, but advanced types, generics, decorators, and TSX require careful review. A TypeScript-aware formatter is safer.

Are comments and template literals preserved?

Line and block comments are retained, and backtick-delimited text is kept as a string token. Placement can change, and embedded template expressions are not recursively formatted.

Why protect semicolons inside for loops?

The separators in for (init; condition; update) are structural and cannot be removed like optional statement terminators. The formatter tracks the outer control parentheses to keep them.

Does formatting improve runtime performance?

No meaningful runtime optimization is intended. Formatting improves human readability. Use a tested bundler and minifier for delivery-size and optimization work.

Is downloaded output ready to deploy?

Treat formatted.js as an intermediate file. Compare it with the source, then pass it through normal parsing, formatting, linting, testing, bundling, and review.

Learn More

Read our comprehensive guide to master this utility.

Read Guide →