ESLint and Prettier: Lint and Format JavaScript Code Automatically
Code review time is precious. It should be spent on logic and test coverage, not on missing semicolons or a variable name typo that would crash at runtime. Two tools handle that automatically. ESLint is a linter: it reads your code without running it and reports bugs and risky patterns such as undefined variables, == comparisons and unused code. Prettier is a formatter: it rewrites your code into one consistent style. Almost every professional JavaScript and Playwright project uses both. In this lesson you will install them, configure ESLint’s flat config, read and fix real lint errors, format code, and wire both into npm scripts, VS Code and CI. The terminal output shown was captured from real runs (ESLint 10, Prettier 3).
📖 What You’ll Learn: what linting and formatting are, ESLint vs Prettier, installing both, eslint.config.js (flat config), rule severities, reading ESLint output, –fix, the bugs ESLint catches, running Prettier with –check and –write, .prettierrc and .prettierignore, avoiding conflicts between them, npm scripts, VS Code format on save and running both in CI.
🔍 Linting vs Formatting
| ESLint (linter) | Prettier (formatter) | |
|---|---|---|
| Job | Finds bugs and bad patterns | Makes code look consistent |
| Examples | Undefined variables, ==, unused variables, unreachable code | Semicolons, quotes, indentation, line breaks, spacing |
| Configurable | Hundreds of rules, each on or off | Only a few options, on purpose |
| Changes code? | Only with --fix, for some rules | Yes, that is its whole job (--write) |
They complement each other: Prettier decides how code looks, and ESLint decides whether it is correct. Neither replaces tests, but both catch problems in seconds, before the code ever runs.
⬇️ Installing ESLint and Prettier
Install them as dev dependencies of the project, so everyone and every CI machine uses the same versions (see the npm lesson):
⌨️ Terminal
npm install -D eslint @eslint/js globals prettier
🖥️ Output
added 81 packages, and audited 83 packages in 7s
19 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
eslint: the linter itself.@eslint/js: ESLint’s recommended rule set.globals: lists of global variables (Node.js, browser) so ESLint knowsprocessorwindowexist.prettier: the formatter.
💡 Tip: npm init @eslint/config@latest asks a few questions and writes a config for you. Writing it by hand, as below, shows you what every line does.
⚙️ Configuring ESLint: eslint.config.js
Current ESLint versions use a flat config: a file named eslint.config.js (or .mjs) in the project root that exports an array of config objects. Later objects override earlier ones.
📄 eslint.config.js
const js = require("@eslint/js");
const globals = require("globals");
module.exports = [
js.configs.recommended,
{
files: ["**/*.js"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "commonjs",
globals: { ...globals.node },
},
rules: {
"no-unused-vars": "warn",
eqeqeq: "error",
"prefer-const": "error",
},
},
];
| Part | Meaning |
|---|---|
js.configs.recommended | Turns on ESLint’s recommended rules (no-undef, no-unused-vars and more) |
files | Which files this object applies to |
languageOptions.sourceType | "commonjs" or "module", matching how your files are loaded |
globals | Variables that exist without being declared (globals.node, globals.browser) |
rules | Turn rules on or off, or change their severity |
Each rule has a severity: "off" (or 0), "warn" (1, reported but does not fail the run) or "error" (2, makes ESLint exit with code 1). Some rules take options: "max-len": ["warn", { code: 120 }].
⚠️ Watch out: Older tutorials use .eslintrc.json or .eslintrc.js. That format was removed in ESLint 10, so use eslint.config.js. In an ES module project ("type": "module") write the same config with import and export default.
🐞 Running ESLint and Reading the Output
Here is a small file with five real problems:
📄 src/checkout.js
const tax = 0.18
let total = 0
function addItem(price, qty) {
let unused = "debug";
total = total + price * qty
if (qty == "2") { console.log("two items") }
return totl;
}
addItem(499, 2)
Run ESLint on the src folder with npx:
⌨️ Terminal
npx eslint src
🖥️ Output
/home/you/demo-npm/src/checkout.js
1:7 warning 'tax' is assigned a value but never used no-unused-vars
5:7 warning 'unused' is assigned a value but never used no-unused-vars
5:7 error 'unused' is never reassigned. Use 'const' instead prefer-const
7:11 error Expected '===' and instead saw '==' eqeqeq
8:10 error 'totl' is not defined no-undef
✖ 5 problems (3 errors, 2 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
Each line shows line:column, the severity, the message and the rule name. Search for the rule name (for example “eslint eqeqeq”) to read why it exists. The most valuable catch here is totl: a typo that would only crash at runtime with ReferenceError: totl is not defined, and only when that line actually runs:
📄 checkout.js
let total = 0;
function addItem(price, qty) {
total = total + price * qty;
return totl; // typo that ESLint reports as no-undef
}
console.log("adding item...");
addItem(499, 2);
⌨️ Terminal
node checkout.js
🖥️ Output
adding item...
/home/you/js-course/checkout.js:5
return totl; // typo that ESLint reports as no-undef
^
ReferenceError: totl is not defined
at addItem (/home/you/js-course/checkout.js:5:3)
at Object.<anonymous> (/home/you/js-course/checkout.js:9:1)
Node.js v26.13.0
Auto-fixing with –fix
--fix repairs what can be fixed safely, here prefer-const, and reports the rest:
⌨️ Terminal
npx eslint src --fix
🖥️ Output
/home/you/demo-npm/src/checkout.js
1:7 warning 'tax' is assigned a value but never used no-unused-vars
5:9 warning 'unused' is assigned a value but never used no-unused-vars
7:11 error Expected '===' and instead saw '==' eqeqeq
10:10 error 'totl' is not defined no-undef
✖ 4 problems (2 errors, 2 warnings)
ESLint never guesses what you meant by totl or whether == was intentional; those need a human. (The line numbers moved because Prettier had reformatted the file before this run, as shown in the next section.)
| Rule | Catches |
|---|---|
no-undef | Typos and variables that were never declared |
no-unused-vars | Dead variables, imports and parameters |
eqeqeq | == / != with surprising type coercion |
prefer-const | let that is never reassigned |
no-unreachable | Code after return or throw |
require-await / no-floating-promises (TypeScript) | Async mistakes such as a forgotten await |
💡 Tip: For Playwright projects, add eslint-plugin-playwright. It flags test-specific mistakes such as a missing await before expect(...).toBeVisible(), focused test.only left in the code, and page.waitForTimeout hard waits.
To silence a rule on one line, add a comment with a reason: // eslint-disable-next-line no-console -- CLI output. Use this rarely; if you disable a rule everywhere, turn it off in the config instead.
🎨 Formatting with Prettier
--check reports files that are not formatted and exits with code 1, without changing anything. That is what CI runs:
⌨️ Terminal
npx prettier --check src
🖥️ Output
Checking formatting...
[warn] src/checkout.js
[warn] Code style issues found in the above file. Run Prettier with --write to fix.
--write rewrites the files in place:
⌨️ Terminal
npx prettier --write src/checkout.js
🖥️ Output
src/checkout.js 45ms
📄 src/checkout.js after Prettier
const tax = 0.18;
let total = 0;
function addItem(price, qty) {
let unused = "debug";
total = total + price * qty;
if (qty == "2") {
console.log("two items");
}
return totl;
}
addItem(499, 2);
Prettier added semicolons and put the if body on its own lines, but it left totl and == alone: it only changes how code looks, never what it does. That is exactly why you need ESLint as well.
Prettier options
Prettier has deliberately few options. Put the ones you change in .prettierrc (JSON), and list folders it should skip in .prettierignore:
📄 .prettierrc
{
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all"
}
📄 .prettierignore
node_modules/
playwright-report/
test-results/
package-lock.json
💡 Tip: Do not let ESLint and Prettier fight over style. Keep ESLint rules about correctness and leave layout (quotes, semicolons, indentation) to Prettier. ESLint’s recommended config already contains no formatting rules; if you add a style guide that does, add eslint-config-prettier last in the config array to switch those rules off.
▶️ npm Scripts, VS Code and CI
Give both tools short npm script names so nobody has to remember the flags:
📄 package.json (scripts)
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check ."
}
VS Code
- Install the ESLint and Prettier – Code formatter extensions.
- Open Settings and enable Format On Save, then choose Prettier as the Default Formatter.
- Lint problems now appear as red and yellow squiggles while you type, and every save formats the file.
📄 .vscode/settings.json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }
}
CI
Run the checks before the tests, so a pull request with lint errors or unformatted code fails fast:
📄 CI steps
- run: npm ci
- run: npm run lint
- run: npm run format:check
- run: npx playwright test
Teams often also run them on staged files before every commit with husky and lint-staged.
🧪 Tester Scenario: Bugs a Linter Finds in Test Code
This test helper has two bugs that ESLint’s recommended rules report before anyone runs the suite. When it does run, it reports a wrong count and crashes on the last step:
📄 report.js
function countFailed(results) {
let failed = 0;
for (const r of results) {
if (r.status = "failed") failed++; // no-cond-assign: = instead of ===
}
return failed;
}
const results = [{ status: "passed" }, { status: "failed" }, { status: "passed" }];
console.log("failed tests:", countFailed(results)); // wrong: every result was overwritten
console.log(results.map((r) => r.status));
console.log("summary:", sumary); // no-undef: typo crashes here
⌨️ Terminal
node report.js
🖥️ Output
failed tests: 3
[ 'failed', 'failed', 'failed' ]
/home/you/js-course/report.js:12
console.log("summary:", sumary); // no-undef: typo crashes here
^
ReferenceError: sumary is not defined
at Object.<anonymous> (/home/you/js-course/report.js:12:25)
Node.js v26.13.0
no-cond-assignflagsif (r.status = "failed"): an assignment inside a condition. It silently changed every result to “failed”, so the count is 3 instead of 1.no-undefflagssumary: a typo that throws aReferenceError.
Both lines look fine at a glance in code review. A linter in the editor underlines them the moment they are typed.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. What is the difference between ESLint and Prettier in one sentence each?
Show answer
ESLint analyses code for bugs and risky patterns (undefined variables, ==, unused code) and can fix some of them. Prettier rewrites code into a consistent format (spacing, quotes, semicolons, line breaks) without changing what it does.
Q2. Write the rules part of eslint.config.js that makes == an error, unused variables a warning and turns off no-console.
Show answer
rules: {
eqeqeq: "error",
"no-unused-vars": "warn",
"no-console": "off",
}Q3. ESLint reports 12:5 error 'page' is not defined no-undef in a Playwright test. What are the two most likely causes?
Show answer
Either page was not taken from the test arguments (test("x", async ({ page }) => ...)), or it is a typo or a variable used outside its scope. The rule is right: the code would throw a ReferenceError at runtime.
Q4. Run this function and explain why the output is wrong. Which ESLint rule would have caught it?
function isAdmin(user) {
if (user.role = "admin") return true;
return false;
}Show answer
📄 practice4.js
function isAdmin(user) {
if (user.role = "admin") return true; // assignment, not comparison
return false;
}
const guest = { role: "guest" };
console.log(isAdmin(guest), guest.role);🖥️ Output
true adminThe condition assigns "admin" (a truthy string) instead of comparing, so every user is an admin, and the user object is changed too. no-cond-assign (in the recommended config) reports it; the fix is user.role === "admin".
Q5. Which commands would you run in a CI pipeline to fail the build on lint errors and unformatted code, without changing any files?
Show answer
npx eslint . (exits with code 1 when there are errors) and npx prettier --check . (exits with code 1 when a file is not formatted). Do not use --fix or --write in CI, because they change files instead of reporting problems.
Q6. Your team keeps arguing about single vs double quotes in reviews. How do you end the discussion for good?
Show answer
Let a tool decide: add Prettier with a .prettierrc (for example {"singleQuote": true}), run npm run format once on the whole codebase, enable format on save, and add prettier --check to CI. Style then stops being a review topic.
🧠 MCQ Quiz: ESLint and Prettier
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does a linter such as ESLint do?Answer: Analyses code without running it to find bugs and risky patterns. It is static analysis.
- What does Prettier change?Answer: Only formatting: spacing, quotes, semicolons, line breaks. It never changes what code does.
- What is the name of the current ESLint config file?Answer: eslint.config.js. The flat config replaced .eslintrc files.
- Which severity makes ESLint exit with code 1?Answer: “error”. Warnings are reported but do not fail the run.
- Which rule reports
if (a == b)?Answer: eqeqeq. It requires === and !==. - Which rule catches a misspelled variable name?Answer: no-undef. An undeclared variable is usually a typo.
- What does
npx eslint . --fixdo?Answer: Fixes the problems that can be fixed safely and reports the rest. Logic problems still need a human. - Which Prettier command should CI run?Answer: prettier –check .. –check reports without changing files.
- How do you stop ESLint style rules from conflicting with Prettier?Answer: Add eslint-config-prettier last in the config. It disables ESLint rules that Prettier already handles.
- Where should ESLint and Prettier be installed?Answer: As devDependencies of the project. Then everyone uses the same version.
💼 Interview Questions and Answers
Q1. Why use ESLint and Prettier in a test automation project?
Test code is code. ESLint catches bugs that make tests lie or crash: missing await (tests that pass without checking anything), typos, assignments in conditions and leftover test.only. Prettier removes all style debate and noisy diffs. Running both in the editor and in CI keeps a large suite readable and reviewable, and reviews can focus on test logic and coverage.
Q2. What is the difference between “warn” and “error” in ESLint, and how do you use them?
Both are reported, but only errors make ESLint exit with a non-zero code, so only errors fail CI. Use "error" for rules that indicate real bugs (no-undef, eqeqeq, no-floating-promises) and "warn" for advice you want to see but not block on (unused variables while refactoring). Many teams add --max-warnings 0 in CI once the codebase is clean.
Q3. How would you introduce linting to an existing project with thousands of errors?
Start with the recommended config and run --fix and Prettier once, in a separate commit, to remove the mechanical issues. Turn noisy rules into warnings or disable them temporarily, fix the real bug categories first, and make CI fail only on errors. Lint new and changed files strictly (for example with lint-staged), then tighten the rules over time.
Q4. Does ESLint replace tests or TypeScript?
No. ESLint finds patterns in source code; it cannot know whether the logic is correct (tests do that) and it understands types only partly (TypeScript does that). They are layers: TypeScript for type errors, ESLint for risky patterns and conventions, Prettier for format, and tests for behaviour.
❓ Frequently Asked Questions
🤔 Do I need both ESLint and Prettier?
Yes, for most projects. ESLint catches bugs; Prettier handles formatting. Using ESLint only for formatting is slower and needs many more rules.
🤔 Can ESLint check TypeScript and Playwright tests?
Yes. Add typescript-eslint for TypeScript files and eslint-plugin-playwright for Playwright-specific rules, both as extra objects in eslint.config.js.
🤔 Why does ESLint say process is not defined?
ESLint does not know your files run in Node.js. Add globals: { ...globals.node } to languageOptions (or globals.browser for browser code).
🤔 What is Biome?
Biome is a newer, very fast tool that combines linting and formatting in one binary. ESLint plus Prettier remain the most widely used setup and the one you will meet in most jobs.
🏁 Summary
- ESLint finds bugs and risky patterns; Prettier formats code. Use both, installed as dev dependencies.
- Configure ESLint in
eslint.config.js(flat config) withjs.configs.recommended, globals and your rule severities. - Read output as line:column, severity, message, rule name;
--fixrepairs only the safe problems. - Prettier:
--checkin CI,--writelocally, options in.prettierrc; keep style rules out of ESLint. - Add npm scripts, enable format on save in VS Code, and run lint and format checks in CI before the tests.
Next, continue with Lesson 57: DOM Manipulation. This completes Module 11. Module 12 moves to the browser: the DOM, events, forms and storage.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in