Skip to content

JavaScript Formatter

Updates as you type 0 lines · 0 B

Formatted JavaScript

Paste JavaScript on the left

Clean, indented code will appear here
Nothing to format yet

JavaScript Formatter & Minifier

What is a JavaScript formatter?

A JavaScript formatter (or JS beautifier) takes code that’s squashed onto one line, or indented five different ways, and lays it out cleanly: one statement per line, every block indented, a space around each operator. Nothing about what the code does changes. It just becomes readable.

A minifier goes the other way. It strips the comments and spaces, shortens local variable names and rewrites small bits of code to fewer characters, so the file downloads faster. This page does both. Switch between Format and Minify above the result. It all runs in your browser, and your code isn’t uploaded.

Format in one picture

Before:

const prices={latte:3.8,mocha:4.2};function total(order){let sum=0;for(const item of order){sum+=prices[item]}return sum}

After (2 spaces):

const prices = {
  latte: 3.8,
  mocha: 4.2
};

function total(order) {
  let sum = 0;
  for (const item of order) {
    sum += prices[item]
  }
  return sum
}

How to use it

Step 1 Paste or open your code

Paste JavaScript into the left panel, open a .js file with the upload button, or drop a file onto the tool. Sample loads a small, messy coffee-shop script if you want to see it work first. The result updates a moment after you stop typing.

Step 2 Pick how it should look

In Format mode the row above the result has the options. Indent is 2 spaces, 4 spaces or a tab. Braces decides where the { goes. Here’s the same if three ways:

{ on the same line (most common)

if (cups > 2) {
  say("Big order, Sam!")
} else {
  say("Thanks, Sam")
}

{ on its own line

if (cups > 2)
{
  say("Big order, Sam!")
}
else
{
  say("Thanks, Sam")
}

else on a new line

if (cups > 2) {
  say("Big order, Sam!")
}
else {
  say("Thanks, Sam")
}
  • Empty lines: keeps up to 1 or 2 of your own blank lines in a row, or removes them all.
  • Wrap: breaks lines longer than 80, 100 or 120 characters at a comma or operator. It can split things in slightly odd places, so leave it off unless your team’s style asks for a limit.
  • Keep array indentation: leaves arrays the way you lined them up by hand, which suits a grid of numbers or a lookup table.

Quotes stay as you typed them. A 'single' string stays single.

Step 3 Or switch to Minify

Click Minify and you’ll see the original size, the minified size, how much you saved and the gzipped size (roughly what a server sends when compression is on). The options are explained in the next section.

Try it: a small function, minified

Before (217 bytes):

// Works out the price of an order, with a tip
function orderTotal(items, tipPercent) {
  let total = 0;
  for (const item of items) {
    total += item.price * item.qty;
  }
  return total * (1 + tipPercent / 100);
}

After (86 bytes, 60% smaller):

function orderTotal(o,r){let t=0;for(const r of o)t+=r.price*r.qty;return t*(1+r/100)}

With “Shorten variable names” off (133 bytes):

function orderTotal(items,tipPercent){let total=0;for(const item of items)total+=item.price*item.qty;return total*(1+tipPercent/100)}

Dropping the comment and the spaces did most of the work here (84 bytes). The short names took off another 47. Notice that items, total and tipPercent became single letters, but orderTotal didn’t. That’s on purpose, more on it below.

Step 4 Copy or download

Copy puts the result on your clipboard. Download saves it as script.js, or script.min.js when minified. Your code and options are remembered in this browser, so a reload doesn’t lose them.

What the minify options do

Shorten variable names

Removing spaces and comments always does the bulk of the shrinking. Shorter names take a further bite on top: local variables and parameters get one-letter names, because nothing outside the function can see them anyway. Names that other code might call stay the same: functions and variables at the top level of a normal script, object properties, and globals. That’s why this still works after minifying:

Your HTML calls the function by name:

<button onclick="addToCart('Latte')">Add a latte</button>
<script src="cart.min.js"></script>

cart.min.js keeps addToCart:

function addToCart(t){const a=JSON.parse(localStorage.getItem("cart")||"[]");a.push(t),localStorage.setItem("cart",JSON.stringify(a))}

If your file has import or export in it, the tool reads it as an ES module. Top-level names inside a module are private to that file, so those get shortened too. Exported names are kept.

Remove console calls

Takes out every console.log, console.warn and friends. It’s a quick way to clear out debug logging you forgot to delete. Be careful with one thing: the whole call goes, including whatever is inside the brackets.

Before:

let cups = 0;
console.log('Cups so far:', cups++);
alert('Cups: ' + cups);

After, with Remove console calls on:

let cups=0;alert("Cups: "+cups);

The cups++ lived inside the log, so it’s gone too, and the alert now says “Cups: 0” instead of “Cups: 1”. If a log line does real work like that, move the work onto its own line before you minify.

Keep function names

Turn this on when your code reads a function’s or class’s own name, for example fn.name, this.constructor.name or a logging helper that prints which function called it. It also keeps error stack traces a bit more readable. The file gets a little bigger.

Output for

Tells the minifier the newest syntax it may use in its output. With ES2020 it can write { price } instead of { price: price }. Pick ES5 if the code has to run in a very old browser. It only limits what the minifier adds, though. Your own modern code isn’t converted down: an arrow function you wrote stays an arrow function, even with ES5 picked. Converting old syntax is a job for a compiler, not a minifier.

License comments stay

Normal comments are removed, but ones that start with /*! or contain @license or @preserve are kept, since many licenses ask you to keep the notice with the code.

Before:

/*! Corner Cup menu v2.1 | MIT License */
// Shows today's special
function showSpecial() {
  document.querySelector('#special').textContent = 'Pumpkin latte';
}

After:

/*! Corner Cup menu v2.1 | MIT License */
function showSpecial(){document.querySelector("#special").textContent="Pumpkin latte"}

Do you need to minify by hand?

Often not. If your project has a build step (a bundler, or a framework’s build command), it almost certainly minifies your JavaScript already when you build for production. Check the files it outputs: if they’re one long line, you’re done.

Minifying by hand makes sense for a small site without a build step: one script.js next to your HTML, a snippet you paste into a website builder or an email platform, or a bookmarklet that needs to fit on one line. Keep the readable file as your source and treat the .min.js as something you regenerate, never something you edit.

Why minified code is hard to debug

When minified code breaks, the browser reports something like “TypeError at script.min.js:1:4825”. Line 1, because the whole file is one line. And the variable it complains about is called e. Not much to go on.

JSX and TypeScript

Format works on React-style JSX. Tags like <Card title="Hi"> are left as they are, and the JavaScript around them is indented as usual. It doesn’t re-indent the inside of a long JSX block, so a component that was all on one line stays on one line where the tags are.

TypeScript is a different story. Type annotations confuse the formatter:

type Order = {
  drink: string;size ? : string
};
const order: Order = {
  drink: 'Latte'
};

Spot the size ? : string? That’s not valid anywhere. Strip the types first in the TypeScript Playground, then format or minify the JavaScript it gives you. Minify only reads plain JavaScript. For JSX and the usual TypeScript (types, interfaces, private and other class modifiers) it stops with an error and a hint. It can’t spot every TypeScript feature, though, and one it misses may come out as code that means something else. So strip the types first rather than relying on the error.

What it can’t do

Related tools

Tidying the HTML and CSS around your script too? The formatters and minifiers below work the same way, and the playgrounds let you run code:

Frequently asked questions

Is a JavaScript formatter the same as a JavaScript beautifier?

Yes. Formatter, beautifier and pretty printer are three names for the same job: taking cramped or messy code and laying it out with line breaks and indentation. You’ll also see “code beautifier” used for tools that do this for several languages. For HTML and CSS there’s an HTML Formatter and a CSS Formatter on this site.

Will formatting change what my code does?

No. Format only changes whitespace: line breaks, indentation and the spaces around things like = and {. Names, strings, quotes and comments stay exactly as you wrote them. One thing to know: it doesn’t add or remove semicolons, so code that relied on a line break in an odd spot stays as it was.

Can I turn minified JavaScript back into readable code?

Partly. Paste a .min.js file and Format gives you one statement per line with proper indentation, which is a big help. What it can’t bring back is what the minifier threw away: comments are gone, and shortened names like e, t and n stay short, because the original names aren’t in the file any more. If the site ships a source map, your browser’s developer tools can show the original code instead.

What does “Shorten variable names” do?

It renames local variables and function parameters to one or two letters, so function orderTotal(items) becomes function orderTotal(e). Removing spaces and comments does most of the shrinking; shorter names save a bit more on top. Names that other code might use stay as they are: top-level functions and variables in a normal script (so onclick="addToCart()" in your HTML keeps working), object properties and anything global. In an ES module, with import or export, top-level names can be shortened too, since nothing outside the file can see them.

Is it safe to remove console calls?

For plain logging, yes. Just know that each console call is removed as a whole, arguments included. A line like console.log(saveOrder()) would stop saving the order too, so scan your logs for anything that does real work before you switch it on.

Does the minifier keep license comments?

Yes. Comments that start with /*! or contain @license or @preserve stay in the minified file, because many open source licenses ask you to keep them. All other comments are removed.

Can it format or minify JSX and TypeScript?

Format handles JSX: tags like <Card title="Hi"> are kept as they are, and the JavaScript around them gets indented. It doesn’t re-indent the inside of a long JSX block, though. TypeScript types can come out mangled (age?: number turns into age ? : number), so strip the types first in the TypeScript Playground. Minify only reads plain JavaScript. It stops with an error for JSX and for common TypeScript like types, interfaces and private fields, but it can’t catch every TypeScript feature, so strip the types before minifying.

Is my code uploaded anywhere?

No. Formatting and minifying both happen in your browser, so the code never leaves your computer. The code you paste and your options are remembered in this browser, so they’re still there after a reload. Very large pastes (over about 500,000 characters) aren’t saved, and Clear removes the saved copy.