JavaScript Code Formatting: Prettier, ESLint and Style Guides
Learn how Prettier and ESLint split formatting and linting, which JavaScript style guides matter, and how to automate consistent code style.
.jpg)
Few arguments waste as much engineering time as the one about tabs, spaces and semicolons. Every team has had it, and almost every team eventually learns the same lesson: stop debating style by hand and let tools enforce it. This guide explains why consistent JavaScript formatting matters, how Prettier and ESLint divide the work, which style guides are worth knowing, and how to set everything up so formatting stops being a topic in code review.
What is code formatting, and why does it matter?
Code formatting is the layout of source code: indentation, line breaks, quote style, spacing around operators and the placement of braces. JavaScript is especially tolerant here. The engine ignores nearly all whitespace, so these two snippets behave identically:
function total(items){let sum=0;for(const i of items){sum+=i.price*i.qty}return sum}
function total(items) {
let sum = 0;
for (const i of items) {
sum += i.price * i.qty;
}
return sum;
}
The machine does not care, but people do. Formatting pays off in four concrete ways.
Readability. Indentation shows structure. A reader can see where a block starts and ends without counting braces.
Smaller diffs. When everyone formats the same way, a pull request shows only real changes. Without a shared format, a one-line fix can arrive buried in hundreds of whitespace edits that hide the actual logic change.
Fewer review arguments. Style comments such as "add a space here" or "wrap this line" are noise. Automating them frees reviewers to discuss design, naming and bugs.
Easier onboarding. New contributors do not need to memorise a style document. They save the file and the tool does the rest.
Formatters versus linters
People often mix up two different kinds of tools. Understanding the difference is the key to a clean setup.
A formatter rewrites your code's layout. It parses the source into a syntax tree and prints it back using fixed rules. It never changes what the program does. Prettier is the best-known example.
A linter analyses your code for likely bugs and bad practices: unused variables, unreachable code, a missing await, or comparing with == where === was intended. ESLint is the standard linter for JavaScript and TypeScript.
The two overlap on style, which is where trouble used to start. ESLint once shipped many formatting rules (quotes, semicolons, indentation), and these fought with Prettier's output. The modern recommendation is simple: let the formatter own layout, and let the linter own correctness. Turn off any ESLint rule that only concerns style, or use a config such as eslint-config-prettier that does it for you. The Prettier documentation describes this split in its page on integrating with linters.
How Prettier works
Prettier is "opinionated" on purpose. Its rationale document explains the thinking: it offers very few options, because every option is another thing to argue about. The core idea is that Prettier throws away your original formatting and reprints the whole program from the syntax tree, wrapping lines to fit a target width.
A few behaviours are worth knowing:
- Line width. The default print width is 80 characters. Prettier fits as much as possible on one line, and breaks only when it must.
- Preserved decisions. Prettier keeps blank lines you added between statements (collapsing multiples into one), and it keeps an object on multiple lines if you put a newline between the opening brace and the first key.
- Semicolons and quotes. It adds semicolons by default and prefers double quotes, but both are configurable.
- Trailing commas. Modern defaults add trailing commas in multi-line structures, which produces cleaner diffs when you append items.
A minimal configuration lives in a .prettierrc file:
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2
}
The full list is short; see the official options reference. Resist the urge to tune every setting. The point of a formatter is agreement, not perfection.
How ESLint fits in
ESLint reads your code, applies a set of rules, and reports problems. Each rule can be set to "off", "warn" or "error", and many have automatic fixes. The current configuration format is the "flat config" file, eslint.config.js, described in the ESLint configuration docs. A small example:
import js from "@eslint/js";
import prettier from "eslint-config-prettier";
export default [
js.configs.recommended,
prettier, // disables rules that conflict with Prettier
{
rules: {
"no-unused-vars": "warn",
eqeqeq: "error",
"prefer-const": "error",
},
},
];
The rules above catch real defects rather than style: eqeqeq prevents surprising type coercion, prefer-const signals variables that never change, and no-unused-vars highlights dead code. The getting started guide walks through installation.
Popular JavaScript style guides
If you would rather adopt a convention than invent one, several well-known guides exist:
- Airbnb JavaScript Style Guide. One of the most widely used, with detailed rules and rationale. It is published on GitHub and has a matching ESLint config.
- Google JavaScript Style Guide. A thorough document covering formatting, naming and language features, available at google.github.io/styleguide.
- StandardJS. A zero-configuration style that famously omits semicolons. See standardjs.com.
The semicolon debate deserves a note. JavaScript has a feature called automatic semicolon insertion, where the parser inserts semicolons at certain line endings. It works most of the time, but a few edge cases (a line starting with ( or [, or a return followed by a newline) can change meaning silently. Whichever side you pick, a formatter removes the risk because it applies your choice consistently.
Another long-running argument is indentation placement. The indentation style article lists the historical variants (K&R, Allman and others). In JavaScript the overwhelming norm is the K&R-style "braces on the same line" layout, and tools default to it.
Real-world use cases
Cleaning up minified or inherited code. You open a bundled file, a pasted snippet from a chat, or a legacy script written in 2012. It is one long line or has inconsistent indentation. Beautifying it is the first step to understanding it. A quick online formatter is ideal here because you do not need a whole project setup.
Reviewing API or SDK snippets. Code in documentation and forums is often unformatted. Reformatting it before pasting into your project keeps the diff clean.
Enforcing a team standard. In a repository, run the formatter on save in the editor and again in a pre-commit hook, so unformatted code never reaches the main branch.
Teaching and writing. For blog posts, slides and documentation, consistently formatted code is far easier to read and copy.
Common mistakes
- Running the formatter and linter against each other. If ESLint style rules conflict with Prettier, you get a loop where each tool undoes the other. Disable the overlap.
- Formatting only some files. A half-formatted repository creates noisy diffs every time someone touches an old file. Format everything once, in a single dedicated commit.
- Bikeshedding config. Spending a meeting on
printWidthis exactly the waste the tool was meant to prevent. - Forgetting generated files. Add build output, vendor code and lockfiles to
.prettierignoreso they are left alone.
Step-by-step: format JavaScript with DevUtilX
When you just need to clean a snippet quickly, without installing anything, the DevUtilX JavaScript/TypeScript Beautifier does the job in your browser.
- Open the beautifier tool.
- Paste your JavaScript or TypeScript into the input editor.
- Choose the indentation you prefer (2 spaces, 4 spaces or tabs).
- Run the formatter and review the output in the result pane.
- Copy the cleaned code back into your project.
Because the work happens in the browser, your code is not uploaded anywhere, which matters when the snippet contains internal logic. If your goal is the opposite, shrinking code for production, pair this with the JavaScript minifier.
Setting up a project for automatic formatting
For a real project, make formatting automatic rather than manual. A reliable setup has four layers.
1. Install and configure. Add Prettier and ESLint as dev dependencies and commit the config files, so everyone shares the same rules.
npm install --save-dev prettier eslint eslint-config-prettier
2. Add scripts. Give the team obvious commands:
{
"scripts": {
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint": "eslint ."
}
}
3. Share editor settings. An EditorConfig file sets basic rules such as indent style and final newline for almost every editor, including people who do not use your formatter plugin.
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
4. Enforce in CI and on commit. Run format:check and lint in your continuous integration pipeline so a failing check blocks unformatted code. Optionally add a pre-commit hook with a tool like lint-staged so only changed files are processed locally.
Best practices
- Pick a standard and stop. The best style is the one everyone follows. Prefer Prettier defaults unless you have a strong reason.
- Separate concerns. Formatter for layout, linter for bugs. Never let the two own the same rule.
- Format on save. The faster the feedback, the less friction developers feel.
- Do one big formatting commit. When adopting a formatter on an existing codebase, apply it in a single commit and record that commit's hash in a
.git-blame-ignore-revsfile sogit blamestays useful. - Keep code readable beyond layout. A formatter cannot fix unclear names, giant functions or missing comments. Use the time saved on style to improve those.
- Version your tools. Pin the formatter version. Different versions can print code slightly differently, which creates diff noise between teammates.
Comparison and alternatives
Prettier is not the only choice, and it is worth knowing what else exists.
- Prettier: the dominant opinionated formatter, supporting JavaScript, TypeScript, CSS, HTML, JSON and Markdown. See the Prettier repository for its roadmap and issues.
- Biome: a fast, Rust-based tool that combines formatting and linting in one binary, and aims for Prettier-compatible output.
- dprint: another Rust-based formatter focused on speed and configurability.
- ESLint with stylistic plugins: possible, but you re-take responsibility for style rules the community has largely moved away from.
- Editor built-ins: convenient for solo work, but they differ between editors, which is why a project-level tool is preferable for teams.
The honest summary is that all of these produce readable code. What matters is that the whole team uses the same one and that it runs automatically.
What happens inside a formatter
Knowing the pipeline makes a formatter's odd decisions easier to predict. Most JavaScript formatters work in three stages.
Parse. The source text becomes an abstract syntax tree (AST), a nested structure of nodes such as "call expression", "arrow function" and "object literal". At this point the original whitespace is already gone. The parser also records where comments sit, because comments are not part of the grammar and must be reattached to nearby nodes.
Build a layout description. Instead of printing text directly, the formatter turns each node into an intermediate document made of a few primitives: plain text, an indented block, a line break that may or may not fire, and a "group" that says "keep everything inside on one line if it fits". Prettier's printer follows the approach in Philip Wadler's paper "A prettier printer", and its own docs credit that lineage.
Print. The printer walks the document and asks, group by group, whether the content fits in the remaining width. If it fits, the soft line breaks inside the group stay flat. If it does not, the group breaks, and its line breaks become real newlines with the right indentation. Nested groups are decided independently, which is why a long call can break its arguments while a short inner call stays on one line.
Three consequences follow from this design.
- Output depends on the tree, not on your layout. Two programs with the same AST print the same text. That is why a formatter ends style debates so effectively.
- A good formatter is idempotent. Formatting already-formatted code must change nothing. If a second run produces a different result, you have found a bug or an unstable plugin combination.
- Comments are the hard part. Because a comment can sit between almost any two tokens, formatters must guess which node it belongs to. If a comment lands somewhere surprising after formatting, move it to its own line above the code it describes.
A worked example: what changes and what stays
Here is a function written by someone in a hurry.
const config={retries:3,timeout:5000,
headers:{'Content-Type':'application/json'}}
async function fetchUser(id,options={}){
const response=await fetch(`/api/users/${id}`,{method:'GET',headers:config.headers,signal:options.signal,credentials:'same-origin'})
if(!response.ok)throw new Error('Request failed: '+response.status)
return response.json()
}
Run through Prettier with its default settings, the first statement looks like this.
const config = {
retries: 3,
timeout: 5000,
headers: { "Content-Type": "application/json" },
};
Prettier also normalised the quotes to double quotes, its default. With singleQuote: true the same string would print as 'Content-Type'. The formatter only swaps quote styles when doing so does not add escape characters.
Notice what happened to the object. The first key sat on the line after the opening brace, so Prettier kept the object expanded. The nested headers object was written on one line with no newline after its brace, so it stayed compact. This is the "preserved decision" described earlier: the first-key rule is the one place where your input layout influences the output.
The long fetch call is the more interesting case.
async function fetchUser(id, options = {}) {
const response = await fetch(`/api/users/${id}`, {
method: "GET",
headers: config.headers,
signal: options.signal,
credentials: "same-origin",
});
if (!response.ok) throw new Error("Request failed: " + response.status);
return response.json();
}
Three things deserve a closer look. The last argument is an object, so Prettier "hugs" it: the braces stay on the call's line instead of pushing every argument onto its own line. The if statement without braces stays braceless, because a formatter never adds or removes braces, and that is a job for a lint rule such as curly. And the string concatenation stayed as written, because rewriting it as a template literal would be a code change, not a layout change.
Run the output through the formatter a second time and nothing moves. That is the idempotence property at work.
Controlling Prettier when you need to
Defaults cover most code, but a few escape hatches exist for the rest.
Ignoring a statement. Put // prettier-ignore on the line above a node and Prettier leaves that node exactly as written. This is the right tool for hand-aligned data, such as a matrix or a lookup table, where the visual alignment carries meaning.
// prettier-ignore
const identity = [
1, 0, 0,
0, 1, 0,
0, 0, 1,
];
Use it sparingly. Every ignore comment is a place where the formatter no longer protects you, and a codebase full of them is a sign that the rules should change instead.
Ignoring files. A .prettierignore file uses the same pattern syntax as .gitignore. Add generated bundles, vendored libraries, snapshots and lockfiles. Recent Prettier major versions also read .gitignore by default, so build output you already ignore in git is typically skipped, but an explicit .prettierignore documents your intent.
Per-file overrides. The overrides key lets one config apply different options to matching paths.
{
"singleQuote": true,
"overrides": [
{ "files": "*.json", "options": { "tabWidth": 4 } },
{ "files": "legacy/**/*.js", "options": { "printWidth": 120 } }
]
}
Overrides are useful during a gradual migration, when one directory cannot take the team default yet. Treat them as temporary.
Choosing a config file format. Prettier looks for .prettierrc (JSON or YAML), .prettierrc.json, a prettier key in package.json, or a JavaScript config file. Pick one and delete the others. Two configs in one repository is a common cause of "it works on my machine" formatting differences, because the tool picks the first match by its own search order, and a stray file in a subfolder can shadow your root config.
ESLint rules that earn their place
A formatter cannot tell you that code is wrong. A short, deliberate rule set catches the mistakes that formatting hides. These rules are all part of core ESLint, and each one prevents a specific class of bug.
| Rule | What it prevents |
|---|---|
eqeqeq |
Loose equality, where 0 == "" and null == undefined are true |
no-unused-vars |
Dead variables and imports that confuse readers |
no-undef |
Typos in variable names that only fail at runtime |
prefer-const |
Reassignable bindings that are never reassigned |
no-shadow |
An inner variable silently hiding an outer one |
curly |
Braceless if bodies that break when a second statement is added |
no-fallthrough |
A switch case that runs into the next one by accident |
require-await |
async functions that never await anything |
no-return-await or no-await-in-loop |
Needless wrapping, or accidental serial network calls |
Two cautions apply. First, curly sits close to layout, but it changes code by adding braces, so it belongs in ESLint and not in the formatter. Some brace-related options can conflict with Prettier, so read both the rule's documentation and the eslint-config-prettier notes before enabling it. Second, do not enable a rule because a famous config includes it. Enable it because your team has been bitten by the problem it prevents.
Scoping rules by file type
Flat config makes it easy to apply a rule set only where it makes sense. Test files, build scripts and browser code have different globals and different tolerance for rough edges.
import js from "@eslint/js";
import globals from "globals";
import prettier from "eslint-config-prettier";
export default [
js.configs.recommended,
{
files: ["src/**/*.js"],
languageOptions: { globals: globals.browser },
},
{
files: ["scripts/**/*.js", "*.config.js"],
languageOptions: { globals: globals.node },
},
{
files: ["**/*.test.js"],
rules: { "no-unused-expressions": "off" },
},
prettier, // keep last so it can switch off conflicting rules
];
The order matters. Later entries override earlier ones, so the Prettier config goes at the end of the array. Putting it first lets later rule blocks quietly switch conflicting rules back on.
Making the whole thing automatic
The four-layer setup earlier gives you the pieces. This section shows how to connect them so that nobody has to remember anything.
Editor setup
In Visual Studio Code, install the Prettier extension and add a workspace settings file that commits your intent.
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
}
}
Format-on-save and ESLint auto-fix cover most local needs. Commit this file to .vscode/settings.json so new contributors get the behaviour without reading a wiki page. Other editors have equivalent plugins, and all of them read the same .prettierrc, which is the real source of truth.
Pre-commit hooks with lint-staged
A pre-commit hook catches formatting before it leaves the developer's machine. The lint-staged tool passes only the staged files to your commands, so the hook stays fast even in a large repository.
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["prettier --write", "eslint --fix"],
"*.{json,md,css,yml}": ["prettier --write"]
}
}
Run Prettier first and ESLint second. If ESLint's auto-fixes touch layout, Prettier would otherwise be the last word on formatting, and you want that order stable. A hook manager such as Husky then runs npx lint-staged from the pre-commit hook. Check the current Husky documentation for the install command, since the setup steps have changed between major versions.
Hooks are a convenience, not a guarantee. Developers can skip them with git commit --no-verify, and some tools never run them. That is why CI remains the real gate.
A CI check
A minimal GitHub Actions job runs the same two scripts you gave the team.
name: quality
on: [pull_request]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run format:check
- run: npm run lint
prettier --check exits with a non-zero status when any file differs from its formatted version, which fails the job. Using npm ci rather than npm install guarantees the exact locked versions, so CI and your laptop print identically. When the check fails, the fix is always the same: run npm run format, commit, push.
Migrating an existing codebase
Adopting a formatter on a repository with years of history is the moment teams fear most. The risk is not technical. It is the diff noise and the damage to git blame. A calm migration looks like this.
- Freeze merges briefly. Agree on a short window, and ask open branches to merge or rebase first. Formatting changes touch nearly every line, and unmerged branches will conflict.
- Commit the config alone. Add
.prettierrc,.prettierignoreand the scripts in one small commit. Reviewers can read it in a minute. - Format everything in one commit. Run
npm run formatand commit nothing else. A pure formatting commit is easy to verify, because you can check that behaviour did not change by running your test suite, or by comparing the compiled output before and after. - Record the commit in an ignore file. Add its full hash to
.git-blame-ignore-revs, then tell git about the file.
git log -1 --format=%H >> .git-blame-ignore-revs
git config blame.ignoreRevsFile .git-blame-ignore-revs
GitHub's blame view also honours a .git-blame-ignore-revs file at the repository root, so the web interface and the command line agree. Each teammate runs the git config line once per clone.
- Turn on enforcement. Enable the CI check and the pre-commit hook only after the big commit lands.
- Help open branches. A branch started before the migration can rebase onto the new base, then run the formatter and commit. If conflicts are heavy, a common trick is to rebase each branch commit with the formatter applied, or simply to reformat the branch and resolve the remaining conflicts by hand. Tools for comparing files, described in our guide to code diffs and comparing files, make those conflicts easier to read.
If the codebase is too large to convert in one go, a gradual approach works too. Run the formatter only on changed files through lint-staged, and let the repository converge over time. The trade-off is a longer period of mixed style and noisier diffs whenever someone touches an old file, so prefer the single commit when you can.
Troubleshooting guide
Formatting problems tend to repeat. Here are the common ones, as symptom, cause and fix.
Symptom: the formatter and ESLint keep undoing each other.
Cause: a style rule such as quotes, semi, indent or comma-dangle is still active in ESLint with settings that disagree with Prettier.
Fix: add eslint-config-prettier as the last entry in your config, or switch the offending rules off by hand. Then run both tools on one file twice and confirm nothing changes.
Symptom: the editor formats differently from the command line.
Cause: the editor extension is using a bundled Prettier version, a different config file, or no config at all.
Fix: install Prettier as a dev dependency so the extension uses the project copy, and make sure only one config file exists. Check the editor's output panel for the config path it loaded.
Symptom: CI fails on formatting but local runs pass.
Cause: a version mismatch, a different line-ending setting, or a file that is ignored locally but not in CI.
Fix: pin the Prettier version in package.json, use npm ci, set end_of_line = lf in EditorConfig, and add a .gitattributes rule such as * text=auto eol=lf so Windows checkouts do not rewrite line endings.
Symptom: every line shows as changed after a teammate saves a file.
Cause: line endings flipped between CRLF and LF, or the indentation setting differs.
Fix: set endOfLine explicitly, share EditorConfig, and ask the teammate to re-save with the project settings active.
Symptom: a file will not format and the tool reports a syntax error.
Cause: the file really does contain invalid syntax, or it uses a newer language feature than the parser understands, or the file extension chose the wrong parser.
Fix: read the line and column in the error first. If the syntax is valid, upgrade the formatter. For unusual extensions, set the parser option in an override.
Symptom: a long string or comment ignores the print width.
Cause: formatters do not split string literals or reflow comments, because doing so would change the code or its meaning.
Fix: break long strings yourself with concatenation or a template literal, and wrap comments by hand.
Symptom: formatting is slow in a large repository.
Cause: the tool is processing files it should skip, such as build output or node_modules contents.
Fix: tighten .prettierignore, run only on changed files in hooks, and use the --cache option so unchanged files are skipped on later runs.
Performance and scale
Formatting rarely shows up in build profiles, but a few habits keep it that way.
Run the whole-repository format only in CI and on demand. In developer hooks, process only staged files. Prettier's --cache flag stores a record of already-checked files and skips them when their contents and options have not changed, which helps repeated local --check runs. Be careful to keep the cache directory out of version control.
If a monorepo has thousands of files, split the check by package so CI jobs can run in parallel. The fastest runs come from tools written in compiled languages, which is a large part of why Biome and dprint exist. If your formatting step takes minutes, it is worth trying one of them on a branch and measuring on your own code, since the gain depends on repository size and hardware.
Memory use is seldom an issue, but a single enormous generated file, such as a bundled or minified output, can make a formatter slow and heavy. Exclude such files. If you need to read one, paste a section into a browser-based beautifier rather than formatting it in place. The reverse operation, shrinking code for delivery, is covered in JavaScript minification explained.
Security and privacy notes
Formatting tools read your whole source tree, so treat them like any other dependency.
- Pin and review versions. A formatter or ESLint plugin runs code on your machine, and ESLint plugins in particular can execute arbitrary JavaScript from a config. Add new plugins deliberately, and commit your lockfile.
- Be wary of config from unknown sources. A shared ESLint config is code. Review it the way you would review any package before adopting it.
- Keep secrets out of snippets. Before pasting code into any online tool, strip API keys, tokens and internal URLs. Local, in-browser tools reduce the exposure, but removing the secret removes the risk entirely.
- Formatters never sanitise. Reformatting a script does not make it safe. Unknown code you beautify in order to read it is still untrusted code, so read it, but do not run it.
- Beautified bundles are not original source. A minifier renames local variables, and no formatter can restore those names. Treat the result as readable, not as the author's intent.
Accessibility and readability for people
Formatting is also an accessibility topic, because developers read code in very different ways.
Tabs let each person choose an indent width that suits their eyesight, and screen-reader users can often tune how indentation is announced. Spaces give predictable alignment in tools that cannot change tab width. Neither choice is wrong; what hurts is a mix. A modest print width of 80 to 100 columns lets people zoom in, use large fonts, or place two files side by side without horizontal scrolling. Very long lines are harder to track for readers with low vision or dyslexia.
Consistent, semantic structure also helps people who navigate code by outline or by headings in a documentation tool. Descriptive function names and short functions give a screen reader something meaningful to announce, which a formatter alone cannot supply.
A team conventions checklist
Use this list when you write or review a repository's contributor guide.
- A formatter and a linter are installed as dev dependencies, with exact versions pinned.
- One config file per tool lives at the repository root, and no duplicates exist elsewhere.
.prettierignoreand ESLint ignores cover generated, vendored and build files.- EditorConfig defines indent style, line endings and the final newline.
- Format-on-save settings are committed for the main editors the team uses.
- A pre-commit hook processes staged files only.
- CI runs
format:checkandlinton every pull request and blocks merging on failure. .git-blame-ignore-revslists every bulk formatting commit.- The contributor guide states that style comments in review are not needed, because the tools decide.
- Disabling a rule requires a short comment explaining why.
- The team reviews config changes in their own pull requests, separate from feature work.
For a related look at keeping other file types tidy, see our guides on CSS formatting and architecture and HTML formatting and semantic markup.
A short history of the style debate
JavaScript style guides grew from the days when each project hand-wrote its rules, and enforcement meant reviewers pointing at lines. Early linters such as JSLint, and later JSHint, introduced automated checking. ESLint arrived with pluggable rules, and style rules were part of the mix. Then formatters changed the model: instead of reporting style violations and asking people to fix them, a tool simply rewrote the file. Prettier popularised that approach for JavaScript, and its adoption showed that most developers prefer a consistent result over a personally perfect one.
The lesson from that history is practical. Reporting problems costs human time, while rewriting costs none. Wherever a rule can be fixed mechanically, give it to a formatter. Reserve linters and reviewers for problems that need judgement.
FAQ
Should I use tabs or spaces?
Either works. Spaces give identical rendering everywhere, while tabs let each reader choose their own visual width and are friendlier for accessibility. Pick one in your config and let the formatter enforce it.
Do I need semicolons in JavaScript?
Not strictly, because of automatic semicolon insertion, but a few edge cases can bite. Using semicolons consistently, enforced by a formatter, is the lower-risk option.
What is the difference between Prettier and ESLint?
Prettier formats layout and never changes behaviour. ESLint analyses code for bugs and bad practices and can also enforce conventions. Use both, with Prettier in charge of style.
Does formatting change how my code runs?
No. A formatter only changes whitespace and punctuation that the language treats as equivalent. If behaviour changes, that is a bug in the tool, so report it.
Can I format TypeScript and JSX the same way?
Yes. Prettier and ESLint both support TypeScript and JSX, and the DevUtilX beautifier handles JavaScript and TypeScript.
Is it safe to paste proprietary code into an online formatter?
Only if the tool runs locally. Browser-based tools that process everything client-side, like DevUtilX, never send your code to a server. Always check a tool's privacy statement first.
Why does Prettier keep my object expanded even though it would fit on one line?
Because the first key starts on a new line after the opening brace. Prettier treats that newline as your request to keep the object expanded. Delete the newline and run the formatter again, and the object collapses if it fits within the print width.
Can a formatter break my code?
It should not, since it only rewrites layout from the syntax tree. Real risks are rare: a buggy plugin, a mismatch between parser and language version, or a comment moved to an unexpected place. Run your tests after a bulk format, and keep the formatting commit separate so it is easy to revert.
Should formatting rules be enforced on pull requests or only locally?
Both. Local hooks give fast feedback, while a CI check is the one gate nobody can skip with --no-verify.
How do I keep git blame useful after a bulk reformat?
List the formatting commit in .git-blame-ignore-revs and point blame.ignoreRevsFile at it. GitHub's blame view reads the file too.
Do I still need EditorConfig if I use Prettier?
It helps. Prettier reads some EditorConfig settings, such as indent style, when no Prettier option overrides them, and EditorConfig also covers file types and editors that Prettier does not touch.
Should I format Markdown and JSON with the same tool?
Often yes, since Prettier supports both. For data files, see the JSON formatting guide for details on structure and whitespace choices.
Is a printed line limit of 80 columns still sensible?
It remains a safe default for side-by-side diffs and code review panes. Many teams choose 100 or 120 for wide monitors. Pick a value once, and judge it by how your diffs read.
Conclusion
Consistent formatting is one of the cheapest quality improvements a JavaScript team can make. Let a formatter such as Prettier own the layout, let ESLint catch real mistakes, share a small set of config files, and enforce both on save and in CI. For quick one-off cleanups, the JavaScript/TypeScript Beautifier gives you tidy code in seconds. To continue, read our JSON Formatting Guide for the same ideas applied to data, and explore the JavaScript minifier when you are ready to ship.
.jpg)
.jpg)
.jpg)