JavaScript Linting with ESLint
Linting is the process of analyzing your code for potential errors, style issues, and bugs before you even run it. In JavaScript, the most popular linter is ESLint.
What is ESLint?
ESLint is a powerful linting tool for JavaScript that:
- Catches syntax and logic errors early
- Enforces coding standards
- Prevents bugs in large codebases
- Works with most modern editors (e.g. VS Code)
Why Use ESLint?
- Helps maintain clean and consistent code
- Flags common JavaScript mistakes
- Supports custom rules
- Integrates with build tools (Webpack, Babel, etc.)
How to Install ESLint
Using npm:
npm install eslint --save-dev
Or using yarn:
yarn add eslint --dev
Initialize ESLint
In your project root:
npx eslint --init
You’ll be asked:
- Type of project (CommonJS, ESModules, React, etc.)
- Language (JS/TS)
- Style guide (Airbnb, Standard, Prettier, etc.)
- Environment (browser, Node.js)
This creates a .eslintrc.js or .eslintrc.json config file.
Example .eslintrc.json Configuration
{
"env": {
"browser": true,
"es2021": true
},
"extends": ["eslint:recommended"],
"rules": {
"no-unused-vars": "warn",
"no-console": "off",
"eqeqeq": "error"
}
}
Example Code Before Linting
let a = 5
if(a == '5'){
console.log("Loose comparison")
}
Linting Output:
- Use === instead of ==
- Missing semicolon
After Linting Fix
let a = 5;
if (a === '5') {
console.log("Loose comparison");
}
Run ESLint on Your Code
Run manually:
npx eslint yourfile.js
Run and fix:
npx eslint yourfile.js --fix
VS Code + ESLint
Install the ESLint Extension in VS Code to get real-time linting feedback as you type!