ToolActToolAct

JavaScript Formatting Tool

Input JavaScript
Output
Lines: 1Characters: 0Bytes: 0
Lines: 1Characters: 0

What is JavaScript Formatting?

The JavaScript Formatter turns JavaScript code into a consistent, readable shape. It organizes indentation, line breaks, blocks, object literals, arrays, function calls, and nested expressions so logic and data flow are easier to follow. This helps with debugging, code review, learning examples, pasted snippets, and files that were minified or generated. Formatting is not static analysis: it does not fix runtime errors, prove asynchronous logic is correct, detect every unsafe dependency, or replace linting. In real projects, the output should align with ESLint, Prettier, or the team’s existing conventions so style changes do not hide the meaningful code change.

How to Use

How to use

  1. Paste or type JavaScript code in the left input box
  2. Select indent size, quote style, and semicolon settings
  3. Click 'Format' to beautify code, or 'Validate' to check syntax
  4. View results on the right (with syntax highlighting)
  5. Click 'Copy' to copy to clipboard

Options Description

Indent SizeChoose between 2 spaces, 4 spaces, or Tab indentation
Quote StyleUnify to single or double quotes, or preserve original
SemicolonsAlways add, remove, or preserve semicolons

Keyboard Shortcuts

  • Ctrl + EnterFormat
  • Ctrl + Shift + CCopy result

JavaScript Tips

  • Formatting does not prove runtime correctness. Re-run tests or browser checks after changing JavaScript that depends on automatic semicolon insertion or build transforms.
  • When validating pasted code, remember that browser parser support may differ from your target runtime or bundler configuration.

Use Cases

Making browser JavaScript readable againUse it when a bookmarklet, analytics snippet, console helper, or copied inline script arrives as one long line. The formatter restores line breaks around blocks and statements, while the syntax check uses the browser JavaScript engine to catch mistakes before you reuse the code.
Compressing small scripts for embeddingFor short pieces of plain JavaScript that need to live inside HTML, CMS settings, or a tag manager field, minify mode strips comments and unnecessary whitespace. It is a quick local workflow for deployment snippets where bringing in a full bundler would be heavier than the job requires.
Checking examples before sharing themBefore sending a reproduction to a teammate or posting a concise answer, paste the code to verify that it parses and to normalize its layout. The tool is best for browser-compatible JavaScript snippets rather than TypeScript, JSX, or project-level transforms.
Reformat vendor minified scripts for auditExpand a shipped min.js bundle to inspect obfuscated logic, dead branches, or unexpected network calls before adding it to a tag manager. Pair the read with the source map when available, because variable renaming in the minified file is not reversible from formatting alone. Watch the output around return statements, template literals, and chained `.then()` calls: automatic semicolon insertion (ASI) rules from ECMA-262 §11.9.1 mean the formatter must not break a line directly before a statement that begins with `(`, `[`, `` ` ``, `+`, `-`, or `/`, or it will silently change program semantics.
Compare formatted output against Prettier defaultsRun a snippet through this formatter and through the project's Prettier config to see where spacing around arrow functions, ternaries, and chained calls differ. Use it as a quick sanity check, not a replacement, since Prettier handles JSX, TypeScript, and import ordering in ways the standalone browser formatter does not. Prettier's `printWidth` of 80 versus 100 versus 120 changes where a long chained call wraps, and the single-quote versus double-quote switch re-renders string literals without touching the comments attached to them; JSX attributes, however, must stay on double quotes because browsers parse them as HTML, which this standalone formatter does not understand.

Technical Principle

A JavaScript pretty-printer is a three-stage pipeline defined against the ECMA-262 grammar: a lexer produces a token stream of IdentifierName, NumericLiteral, StringLiteral, TemplateHead/Middle/Tail, Punctuator, Keyword and LineTerminator; a parser builds an ESTree-compatible AST (the shape used by @babel/parser, acorn and esprima); a printer walks the tree and emits text by rules driven by indent size and target print width. Prettier compiles the AST into a Doc intermediate representation built from group, indent, line and softline primitives, then a layout algorithm chooses break points so the output fits the printWidth (80, 100, 120). ESLint --fix instead rewrites tokens in place against the original source, preserving comments more aggressively but only fixing rules that opt in to autofix. The printer cannot freely insert line breaks: ECMA-262 §11.9.1 Automatic Semicolon Insertion ends a statement at any LineTerminator unless the next token is a continuation. Concretely, breaking before a line that begins with `(`, `[`, `` ` ``, `+`, `-`, `/` or a `++`/`--` token will silently change semantics, and a newline directly after `return`, `throw`, `break`, `continue` or `yield` inserts a semicolon and discards the operand. Template literals (backticks) preserve their interior bytes verbatim, including embedded `${}` expressions whose interior is reformatted as JS but whose surrounding whitespace is not. Comments are reattached to neighboring AST nodes through leading/trailing/innerComments arrays so they survive the round-trip. Lexing and printing are both O(n) over source length with a small constant; the parser is effectively linear for well-formed code thanks to single-token lookahead in the ECMA-262 LR(1)-style grammar. Standard JavaScript parsing does not cover JSX, TypeScript type annotations, decorators or Flow, which require @babel/parser plugins or @typescript-eslint/parser; running plain-JS tooling over a .tsx file will reject `: type` annotations. Source maps (Source Map v3) can preserve original line/column mapping when a build step needs to keep stack-trace fidelity, and line endings (LF vs CRLF) are normalized at write time, not at parse time.

  • Pipeline: lexer (token stream per ECMA-262 §12) -> ESTree AST (acorn/@babel/parser/esprima) -> printer; lexer and printer are O(n), parser O(n) with single-token lookahead.
  • ASI traps from ECMA-262 §11.9.1: never break a line before a token starting with `(`, `[`, `` ` ``, `+`, `-`, `/`, or before `++`/`--`, and never break immediately after `return`/`throw`/`break`/`continue`/`yield`.
  • Prettier vs ESLint --fix: Prettier lowers the AST to a Doc IR (group/indent/line) and picks layouts that fit printWidth (80/100/120); ESLint --fix rewrites tokens in place and only applies fixer-tagged rules.
  • Comment preservation: leading/trailing/innerComments are bound to AST nodes; JSDoc blocks immediately above declarations are kept attached so the printer does not orphan them onto a previous statement.
  • Template literals (backticks) are byte-preserved; only the JS inside `${}` is re-printed. Regex literals and string-literal quoting are normalized to the chosen single/double-quote style with `\` escapes recomputed.
  • Dialect coverage: plain JS parsers reject JSX, TypeScript types, decorators and Flow; .tsx/.ts files need @babel/parser plugins ['jsx','typescript','decorators-legacy'] or @typescript-eslint/parser.
  • Output normalization: line endings written as LF or CRLF per config (independent of input), trailing comma policy applied to multiline arrays/objects/calls, and Source Map v3 emitted when the toolchain needs to retain original line/column information.

Examples

Before Formatting

function greet(name){if(!name){return 'Hello, stranger';}const greeting=`Hello, ${name}!`;console.log(greeting);return greeting;}

After Formatting (2 spaces)

function greet(name) {
  if (!name) {
    return 'Hello, stranger';
  }
  const greeting = `Hello, ${name}!`;
  console.log(greeting);
  return greeting;
}

After Minification

function greet(n){if(!n)return"Hello, stranger";const e=`Hello, ${n}!`;return console.log(e),e}

FAQ

What style does the formatter use?

Most builds use Prettier with default settings: 80-column line width, semicolons, double quotes, 2-space indent, trailing commas where ES5-valid. Switch options if your project uses a different style. The result is deterministic for a given config - same input, same output.

Does it run my JS?

No. It only parses and reprints the source code. Side effects, network calls, and runtime errors are irrelevant - the formatter never executes the script.

Will it fix syntax errors?

No. The parser refuses to format invalid JavaScript and shows where parsing failed. Fix the syntax error first; common causes are missing brackets, missing semicolons after a return-from-IIFE, or template literals with mismatched backticks.

Is JSX/TypeScript supported?

Most modern builds parse JavaScript with JSX and TypeScript syntax (.ts, .tsx). The formatter detects which syntax based on what it parses. If you're working in plain ES5, disable TypeScript mode to avoid false-positive errors.

Can it minify JS?

Some builds offer a minify (Terser-style) mode that renames variables, removes whitespace, and dead-code eliminates. The output is small but unreadable. Use minification for production builds, formatting for source code review.

Is my code uploaded?

No. Parsing and printing run in your browser using a JavaScript-based parser. Pasted code is not transmitted.

Why are my comments slightly moved?

Prettier and similar formatters attach comments to the nearest AST node. A comment between two functions might 'belong' to the function below in the AST and end up reattached. Inline trailing comments are usually preserved exactly; floating ones may shift.