JavaScript Tooling: Linting with ESLint and Formatting with Prettier
Catch bugs and end style debates automatically: what a linter finds, ESLint's flat config, rules, severities, --fix and inline disables, plugins and typescript-eslint, Prettier's opinionated formatting and few options, making the two cooperate, and running them in editors, hooks and CI.
kvi5hnuCode Sprout team member7 min readOn this page
This last part of the course covers the tools that professional JavaScript projects use alongside the language: linters, formatters, test frameworks, package managers, bundlers and transpilers, plus two widely used extensions to the language itself, JSX and TypeScript. You'll see them in almost every codebase, so it's worth knowing what each does and when to use it. This article covers the two tools that check and clean up code as you write it.
Linting with ESLint
Lint is code that runs but is suspicious: probably a bug, a leftover, or a confusing pattern. A linter analyzes source code without running it and reports such problems. For JavaScript, the standard linter is ESLint (version 10 at the end of 2026). Consider this file:
// stats.js: small helpers for a report
var total = 'unused';
export function average(values) {
let sum = 0;
for (let i = 0; i <= values.length; i++) {
sum += values[i];
}
if (values.length == 0) return 0;
return sum / values.length
}
export function label(n) {
const kind = n > 0 ? "positive" : "negative";
switch (n) {
case 0:
kind = "zero";
case 1:
return "one";
}
return kind;
}
Running npx eslint src/stats.js with the configuration shown in the next section prints:
src/stats.js
2:1 error Unexpected var, use let or const instead no-var
2:5 error 'total' is assigned a value but never used no-unused-vars
9:21 error Expected '===' and instead saw '==' eqeqeq
17:7 error 'kind' is constant no-const-assign
17:7 error The value assigned to 'kind' is not used in subsequent statements no-useless-assignment
18:5 error Expected a 'break' statement before 'case' no-fallthrough
✖ 6 problems (6 errors, 0 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
Each line gives the position, severity, message and rule name. Some findings are style preferences (var), but others are real bugs: assigning to a const throws at run time, and the missing break makes case 0 fall through into case 1. ESLint found them without running anything. The command exits with a nonzero code when there are errors, which lets scripts and CI fail on them.
ESLint didn't notice everything, though:
// ESLint reported no problem in this function: it is valid, tidy code with a logic bug
function average(values) {
let sum = 0;
for (let i = 0; i <= values.length; i++) { // <= reads one element past the end
sum += values[i];
}
return values.length === 0 ? 0 : sum / values.length;
}
console.log(average([2, 4, 6])); // sum += undefined makes NaN
console.log(2 + undefined);
NaN
NaN
i <= values.length is valid, tidy code that's simply wrong. Linters find suspicious patterns; finding wrong logic is the job of tests (article 134) and, for many type mistakes, a type checker (article 138).
Configuration
Since ESLint 9, configuration is a JavaScript file, eslint.config.js, called the "flat config". It exports an array of configuration objects that apply in order; later ones override earlier ones. ESLint 10 no longer supports the older .eslintrc files you'll still find in older projects and tutorials.
// eslint.config.js
import js from "@eslint/js";
import globals from "globals";
export default [
js.configs.recommended, // ESLint's recommended rules
{
files: ["**/*.js"],
languageOptions: { globals: globals.node }, // process, Buffer, ... are defined
rules: {
"no-var": "error",
eqeqeq: "error",
"prefer-const": "warn",
},
},
{ ignores: ["dist/", "coverage/"] },
];
- Each rule is
"off","warn"(reported, doesn't fail the run) or"error", optionally with options:eqeqeq: ["error", "smart"]. js.configs.recommendedturns on rules that catch likely bugs, such asno-undef,no-unused-vars,no-const-assign,no-fallthroughandno-dupe-keys. Most projects start from it and adjust.languageOptions.globalsdeclares which global variables exist (browser, Node, test framework), sono-undefdoesn't flag them.filesandignoresscope each object to particular files, so tests or scripts can have different rules.
Fixing and silencing
npx eslint --fix .automatically fixes what it safely can, such asvartolet/constorprefer-const. Review the changes like any other edit.- To accept one specific violation, add a comment with a reason:
// eslint-disable-next-line no-console -- CLI output. Use this sparingly; a codebase full of disable comments has effectively turned the rule off.
Plugins and TypeScript
ESLint is extensible. Plugins add rules for frameworks and libraries: eslint-plugin-react-hooks checks React's rules of hooks, and plugins exist for Vue, testing libraries, imports, accessibility and security. typescript-eslint lets ESLint parse TypeScript and adds type-aware rules, such as no-floating-promises, which reports promises whose errors nobody handles.
Newer linters written in Rust are much faster on large codebases: Oxlint implements many ESLint rules, and Biome combines a linter and a formatter in one tool. They're worth knowing; ESLint remains the most widely used and the most extensible.
Formatting with Prettier
Linters used to enforce formatting too: indentation, quotes, semicolons, spacing. That produced endless warnings and code-review arguments about style. Prettier takes a different approach: it parses the code and prints it again from scratch in one consistent style, ignoring the original layout. ESLint has deprecated its own formatting rules (indent, semi, quotes and others) in favor of this approach.
Given this working but messy code:
function clamp(value,min, max)
{
if(value<min){return min}
else if (value>max) {return max}
return value }
const user={name:'Ada',roles:['admin','editor'],address:{city:'London',zip:'N1 9GU'},active:true}
npx prettier src/messy.js prints:
function clamp(value, min, max) {
if (value < min) {
return min;
} else if (value > max) {
return max;
}
return value;
}
const user = {
name: "Ada",
roles: ["admin", "editor"],
address: { city: "London", zip: "N1 9GU" },
active: true,
};
It fixed the indentation, added spaces and semicolons, switched to double quotes, and split the long object across lines because it exceeded the default line width of 80 characters, adding a trailing comma.
prettier --write .reformats files in place;prettier --check .only reports unformatted files and fails, which suits CI.- Prettier is deliberately opinionated, with few options:
printWidth,tabWidth,useTabs,semi,singleQuote,trailingCommaand a handful more, set in a.prettierrcfile. Withsemi: false,singleQuote: trueandprintWidth: 60, the same input loses its semicolons and uses single quotes. - It formats much more than JavaScript: TypeScript, JSX, JSON, CSS, HTML, Markdown and YAML.
- A
.prettierignorefile excludes generated files.
The value isn't in any particular style, but in never discussing style again: diffs show only real changes, and nobody reformats code by hand. The trade-off is that you lose hand-tuned layouts such as vertically aligned comments.
ESLint and Prettier together
Use each for its strength: Prettier for formatting, ESLint for code quality. If your ESLint config includes any formatting rules, for example from an older shared config, add eslint-config-prettier last in the config array to turn them off, so the two tools don't fight.
Running the tools automatically

- Editor: install the ESLint and Prettier extensions (VS Code, WebStorm and others), and enable format on save.
- Commit: a git pre-commit hook, typically set up with husky and lint-staged, formats and lints only the staged files.
- CI: run
prettier --check .,eslint ., the type checker and the tests on every push and pull request. CI is the only stage that can't be skipped.
Put the commands in package.json scripts so everyone runs the same thing:
"scripts": {
"lint": "eslint .",
"format": "prettier --write .",
"check": "prettier --check . && eslint . && tsc --noEmit"
}
Common questions
Isn't ESLint's recommended config enough?
It's a good start: it catches common bugs without style opinions. Teams usually add a few rules such as eqeqeq and no-var, plus framework plugins and typescript-eslint for TypeScript projects.
Why use Prettier if ESLint can fix formatting?
ESLint's formatting rules are deprecated, and Prettier formats everything consistently, including long lines and nested structures that rules can't handle well. Let Prettier own formatting and ESLint own correctness.
My old project has .eslintrc.json. What changed?
ESLint 9 made the flat config (eslint.config.js) the default, and ESLint 10 removed support for .eslintrc. ESLint provides a migration guide and the @eslint/migrate-config tool to convert old files.
Summary
- ESLint reports suspicious code by rule, with severities
off/warn/error, configured ineslint.config.js(flat config). Start fromjs.configs.recommended, add plugins and typescript-eslint as needed, and use--fixfor automatic fixes. - Linters catch patterns, not logic errors; tests and type checkers cover the rest.
- Prettier reprints code in one consistent, opinionated style with few options; use
--writelocally and--checkin CI. - Let Prettier handle formatting and ESLint handle code quality, and run both in the editor, in a pre-commit hook and in CI.
Practice Questions
Which ESLint rules from the recommended set would flag these two lines, and what's wrong with each?
const limit = 10;
limit = 20;
if (status = "done") finish();
Answer
no-const-assign flags limit = 20, which throws a TypeError at run time. no-cond-assign flags status = "done", an assignment where a comparison (===) was almost certainly intended; the condition is always truthy.
What's the difference between prettier --write . and prettier --check ., and where would you use each?
Answer
--write reformats files in place, which you run locally or in a pre-commit hook. --check only reports files that aren't formatted and exits with an error, which suits CI because it fails the build without changing files.
Write a flat config that uses ESLint's recommended rules, treats console calls as warnings, and ignores the build/ folder.
Answer
import js from "@eslint/js";
export default [
js.configs.recommended,
{ rules: { "no-console": "warn" } },
{ ignores: ["build/"] },
];
Previous: Worker Threads in Node: Parallel JavaScript, Messages and Shared Memory
Next: Testing JavaScript: Unit Tests, Mocks and Coverage with node, Vitest and Jest

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.