Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 156 ยท Modules and Tooling

ESLint, Prettier and JSDoc Types

Set up ESLint to catch bugs, Prettier to format code and JSDoc comments with checkJs to type-check plain JavaScript without leaving the language.

Writing code that works today is only half the job. The other half is keeping it readable, consistent and correct as the project and team grow. Three small tools do most of that work for JavaScript: ESLint finds bugs and risky patterns, Prettier formats code so nobody argues about style, and JSDoc comments describe your functions well enough that your editor, and the TypeScript checker, can catch type mistakes in plain .js files.

The earlier tooling lesson introduced linters and formatters in a paragraph. Here you will see how to configure them, what each is good at, and how to get type checking without converting a single file to TypeScript. You need Node and npm for the commands in this lesson (see Node basics), so the setup steps appear as read-only blocks; the runnable examples show the ideas behind the tools.

flowchart LR
  A["Your code"] --> B["Prettier<br/>(how it looks)"]
  A --> C["ESLint<br/>(what it might do wrong)"]
  A --> D["tsc --checkJs<br/>(what types it uses)"]
  B --> E["Consistent, reviewable code"]
  C --> E
  D --> E

Each tool has one job; together they remove whole classes of review comments.

ESLint: catch problems before they run

ESLint reads your source into a syntax tree and applies rules. Some rules find real bugs (no-undef flags a variable that was never declared, no-unreachable flags code after a return), others enforce practices (eqeqeq demands ===). Install it in a project and let its initializer create a config:

Terminal
npm install --save-dev eslint @eslint/js globals

Modern ESLint (version 9 and later) uses a flat config file, eslint.config.js, which exports an array of config objects:

JavaScript
// eslint.config.js
import js from "@eslint/js";
import globals from "globals";

export default [
  js.configs.recommended,
  {
    files: ["**/*.js"],
    languageOptions: {
      ecmaVersion: "latest",
      sourceType: "module",
      globals: { ...globals.browser },
    },
    rules: {
      eqeqeq: "error",
      "no-var": "error",
      "prefer-const": "warn",
      "no-unused-vars": ["warn", { argsIgnorePattern: "^_" }],
    },
  },
  { ignores: ["dist/", "node_modules/"] },
];

A few things to notice:

  • js.configs.recommended turns on ESLint's own set of "this is almost certainly a mistake" rules. Start there and add rules only when you have a reason.
  • Each rule is set to "off", "warn" or "error" (or 0, 1, 2). Some take options in an array.
  • globals tells ESLint which global names exist. Without globals.browser, document would be reported as undefined; with globals.node you get process and require.
  • Objects later in the array override earlier ones for the files they match, so you can have different rules for tests or config scripts.

Run it from the terminal, optionally with --fix to let ESLint repair what it safely can (for example prefer-const):

Terminal
npx eslint .
npx eslint src --fix

A typical report looks like this:

TEXT
src/cart.js
  4:7   warning  'discount' is assigned a value but never used  no-unused-vars
  9:12  error    Expected '===' and instead saw '=='            eqeqeq

What a rule really is

A rule is a small function that visits syntax-tree nodes and reports. The toy version below works on a list of tokens instead of a real tree, but the shape is the same: look at a node, decide whether it is a problem, report a message.

JS The idea behind a lint rule

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Writing your own rule for a real project follows exactly this pattern, with the real parser supplying the nodes.

Useful habits with ESLint

  • Fail the build on errors. Run eslint . in your CI and your pre-commit hook so warnings do not pile up unseen.
  • Disable narrowly. If a rule is wrong for one line, use // eslint-disable-next-line no-console with a short reason, not a file-wide switch.
  • Do not lint style. Let Prettier handle layout, and use ESLint for correctness. If both fight over the same thing, add eslint-config-prettier to switch off the style rules that conflict.
  • Keep the editor integration on. Seeing a squiggle as you type is far cheaper than reading a CI log.

Prettier: stop arguing about formatting

Prettier takes your code, ignores how you wrapped it, and prints it again in one consistent style. Its main idea is a print width (80 columns by default): if a construct fits on one line it stays on one line, and otherwise Prettier breaks it up. Because the output depends only on the syntax tree and a handful of options, two developers always get identical results.

Terminal
npm install --save-dev --save-exact prettier
npx prettier . --check
npx prettier . --write

Options live in .prettierrc (JSON) and there are very few of them on purpose:

JSON
{
  "printWidth": 80,
  "tabWidth": 2,
  "semi": true,
  "singleQuote": false,
  "trailingComma": "all"
}

Which values you choose matters much less than the fact that everyone uses the same ones. Add a .prettierignore for generated files and run Prettier on save in your editor.

The fits-on-one-line rule is easy to see. This function does a simplified version for arrays of numbers:

JS How a formatter decides to break lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same data prints on one line or many, depending only on the width. That is why Prettier diffs are usually small and why moving to a bigger screen never changes your commit.

Running them together

A common package.json setup adds scripts so everyone uses the same commands:

JSON
{
  "scripts": {
    "lint": "eslint .",
    "format": "prettier . --write",
    "format:check": "prettier . --check"
  }
}

Run format:check and lint in CI. Many teams also run them on staged files before each commit with a tool such as lint-staged, so broken style never reaches the repository.

JSDoc: types without TypeScript

JSDoc is a comment format: a block starting with /** placed right above a function, class or variable. Tools read it to show documentation in your editor, and the TypeScript compiler can read the types in it to check plain JavaScript.

JavaScript
/**
 * Add tax to a price.
 * @param {number} price - Price before tax, in cents.
 * @param {number} [rate=0.2] - Tax rate between 0 and 1.
 * @returns {number} Price including tax, rounded to whole cents.
 */
export function withTax(price, rate = 0.2) {
  return Math.round(price * (1 + rate));
}

The tags you will use most:

Tag Meaning
@param {type} name A parameter; [name] marks it optional, [name=5] gives a default.
@returns {type} The return type.
@type {type} The type of a variable or property.
@typedef Defines a reusable named type.
@template T Declares a generic type parameter.
@throws {Error} Documents an exception.

Types use TypeScript's syntax inside braces: , {number[]}, {string | null}, {Promise<User>}, {(a: number) => boolean} and object shapes like {{ id: number, name: string }}. Named shapes are easier to read with @typedef:

JavaScript
/**
 * @typedef {object} User
 * @property {number} id
 * @property {string} name
 * @property {string} [email] - Optional.
 */

/**
 * @param {User[]} users
 * @param {string} prefix
 * @returns {User[]}
 */
export function namesStartingWith(users, prefix) {
  return users.filter((user) => user.name.startsWith(prefix));
}

JSDoc comments are plain comments, so the code runs unchanged. Nothing is checked while the program executes; the checking happens in your editor or in a separate command. The next example shows both sides: it runs a documented function, and a few lines of code read the tags back out of the source text, which is roughly how documentation tools get their data.

JS JSDoc is only comments, but tools can read it

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice withTax("1000") happily returns a number: JavaScript coerces the string at run time, which is exactly the kind of accidental conversion a type checker would have caught before the program ran.

Turning on the checker

To get errors for type mistakes in .js files, install TypeScript as a development tool (it only analyzes; your code is not compiled) and add a tsconfig.json:

JSON
{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "strict": true,
    "target": "ES2022",
    "module": "NodeNext",
    "lib": ["ES2022", "DOM"]
  },
  "include": ["src"]
}
Terminal
npm install --save-dev typescript
npx tsc -p .

Now the call withTax("1000") is reported:

TEXT
src/price.js:12:20 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Editors such as VS Code run the same checker as you type, so you see the squiggle immediately. checkJs also tells you when you use a possibly-null value without checking it or call a function that does not exist.

If a whole project is too noisy to check at once, add // @ts-check as the first line of individual files, or // @ts-nocheck to opt a file out while you migrate. For one stubborn line, // @ts-expect-error suppresses it and warns you if the error ever goes away. Types can also be imported from other files, for example @type {import("./types.js").User}, and the shared @typedef blocks can live in a dedicated types.js.

JSDoc or TypeScript?

JSDoc typing suits small libraries, scripts and teams that want editor help and checks without a build step: the files you write are the files that run. For large applications, TypeScript gives a nicer syntax, stronger tooling and a gradual path (you can add .ts files next to JSDoc-typed .js files). Both use the same checker underneath, so what you learn here carries over directly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the best division of work between ESLint and Prettier?

    Prettier owns layout (line breaks, quotes, indentation). ESLint owns correctness rules such as no-undef and eqeqeq.
  2. 2. What does the 'globals' setting in an ESLint config do?

    Without it, rules like no-undef would report browser or Node globals as undefined.
  3. 3. What happens to a JSDoc type like @param {number} price at run time?

    JSDoc is just a comment. Tools such as the TypeScript checker read it before the program runs.
  4. 4. Which tsconfig options let tsc type-check .js files that use JSDoc without producing output?

    allowJs lets TypeScript read .js files, checkJs reports errors in them, and noEmit stops it from writing files.
  5. 5. What does Prettier's printWidth control?

    If a construct fits within printWidth it stays on one line; otherwise Prettier breaks it across several lines.

Summary

  • ESLint (flat config in eslint.config.js) applies rules to find bugs; start from js.configs.recommended, set globals, and run eslint --fix for safe repairs.
  • Prettier formats everything the same way based on a few options such as printWidth; let it handle style and keep ESLint for correctness.
  • Add lint, format and format:check scripts and run them in CI or a pre-commit hook.
  • JSDoc comments (@param, @returns, @typedef, @template) describe types without changing how code runs.
  • With allowJs, checkJs and noEmit, tsc type-checks plain JavaScript; // @ts-check opts in single files.
  • JSDoc typing needs no build step; move to TypeScript when the project outgrows it.

Next: The DOM - how the browser turns HTML into objects you can read and change.