Last updated
Example: Undefined Variables
// Code:
function calculateTotal(items) {
return items.reduce((sum, item) => sum + itm.price, 0);
}
// Linter output:
Line 2: 'itm' is not defined. Did you mean 'item'? (no-undef)
Example: == vs === (Type Coercion)
// Code:
function isAdmin(user) {
if (user.role == 'admin') {
return true;
}
if (user.id == 0) {
return false;
}
}
// Linter output:
Line 2: Use '===' instead of '=='. (eqeqeq)
Line 5: Use '===' instead of '=='. (eqeqeq)
// Why it matters:
'' == 0 // true (unexpected!)
'' === 0 // false (correct)
null == undefined // true (unexpected!)
null === undefined // false (correct)
Example: Unused Variables
// Code:
import { useState, useEffect, useCallback } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
const unusedValue = 'never used';
return <div>{count}
;
}
// Linter output:
Line 1: 'useEffect' is defined but never used. (no-unused-vars)
Line 1: 'useCallback' is defined but never used. (no-unused-vars)
Line 5: 'unusedValue' is assigned a value but never used. (no-unused-vars)
Example: Unhandled Promise Rejections
// Code:
function loadData() {
fetch('/api/data')
.then(res => res.json())
.then(data => processData(data));
// Missing .catch()
}
async function saveUser(user) {
await db.save(user); // unhandled rejection if db.save throws
}
// Linter output:
Line 2: Promise returned from fetch() is not handled. (no-floating-promises)
Line 9: Promise returned from db.save() is not handled. (no-floating-promises)
// Fixed:
async function loadData() {
try {
const res = await fetch('/api/data');
const data = await res.json();
processData(data);
} catch (err) {
console.error('Failed to load data:', err);
}
}
Example: Security Rules
// Code:
function renderUserContent(userInput) {
document.getElementById('output').innerHTML = userInput; // XSS risk!
}
function runUserCode(code) {
eval(code); // Code injection risk!
}
const query = `SELECT * FROM users WHERE name = '${userName}'`; // SQL injection!
// Linter output:
Line 2: Dangerous use of innerHTML with potentially untrusted data. (no-unsanitized/property)
Line 6: eval() is dangerous and can lead to code injection. (no-eval)
Line 9: Possible SQL injection via string concatenation. (security/detect-sql-injection)
// Fixed:
function renderUserContent(userInput) {
document.getElementById('output').textContent = userInput; // safe
}
Example: var vs let/const
// Code:
function processItems(items) {
for (var i = 0; i < items.length; i++) {
var item = items[i];
setTimeout(function() {
console.log(item); // bug: all iterations log the last item
}, 100);
}
}
// Linter output:
Line 2: Unexpected var, use let or const instead. (no-var)
Line 3: Unexpected var, use let or const instead. (no-var)
// Fixed with let (each iteration gets its own binding):
function processItems(items) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
setTimeout(() => console.log(item), 100);
}
}
Example: const for Non-Reassigned Variables
// Code:
function getUser(id) {
let url = `/api/users/${id}`;
let options = { method: 'GET' };
let result = fetch(url, options);
return result;
}
// Linter output:
Line 2: 'url' is never reassigned. Use 'const' instead. (prefer-const)
Line 3: 'options' is never reassigned. Use 'const' instead. (prefer-const)
Line 4: 'result' is never reassigned. Use 'const' instead. (prefer-const)
// Fixed:
function getUser(id) {
const url = `/api/users/${id}`;
const options = { method: 'GET' };
const result = fetch(url, options);
return result;
}
Example: Complexity Metrics
// Code:
function processOrder(order) {
if (order.status === 'pending') {
if (order.payment === 'credit') {
if (order.amount > 1000) {
if (order.user.verified) {
if (order.items.length > 0) {
return processHighValueOrder(order);
}
}
}
} else if (order.payment === 'debit') {
if (order.amount > 500) {
return processDebitOrder(order);
}
}
}
}
// Linter output:
Line 1: Function 'processOrder' has a complexity of 7. Maximum allowed is 5. (complexity)
Line 1: Function 'processOrder' has a cognitive complexity of 11. (cognitive-complexity)
Recommendation: Extract nested conditions into separate functions.
Example: Import Issues
// Code:
import React from 'react';
import lodash from 'lodash';
import { helper } from './utils';
import { unused } from './constants';
function App() {
return <div>{helper('test')}</div>;
}
// Linter output:
Line 2: 'lodash' is defined but never used. (no-unused-vars)
Line 4: 'unused' is defined but never used. (no-unused-vars)
Line 1: 'React' must be in scope when using JSX. (react/react-in-jsx-scope)
Note: Not needed with React 17+ new JSX transform.
Yes! JavaScript Linter is completely free to use with no registration required. All processing is done client-side in your browser.
Absolutely! All processing happens locally in your browser. Your data never leaves your device, ensuring complete privacy and security.