Last updated
JavaScript Validator Examples
The JavaScript Validator checks code for syntax errors, runtime error patterns, security issues, and best practice violations. Below are examples of common validation results.
Example: Syntax Errors
// Code with syntax errors:
function greet(name {
return `Hello, ${name}!`
}
const obj = {
key: 'value'
other: 'data'
};
// Validator output:
Line 1, Col 21: SyntaxError — Expected ')' but found '{'
Line 7, Col 3: SyntaxError — Expected ',' or '}' but found identifier 'other'
Example: Runtime Error Patterns
// Code:
function processUser(user) {
const name = user.profile.name; // user.profile may be null/undefined
const email = user.contact.email; // user.contact may be null/undefined
return `${name} - ${email}`;
}
function getFirstItem(arr) {
return arr[0].value; // arr may be empty, arr[0] may be undefined
}
// Validator output:
Line 2: Possible TypeError — 'user.profile' may be null or undefined.
Use optional chaining: user?.profile?.name
Line 3: Possible TypeError — 'user.contact' may be null or undefined.
Use optional chaining: user?.contact?.email
Line 8: Possible TypeError — 'arr[0]' may be undefined if array is empty.
Add a length check or use optional chaining: arr[0]?.value
Example: == vs === Issues
// Code:
function checkStatus(status) {
if (status == 0) return 'inactive';
if (status == '1') return 'active';
if (status == null) return 'unknown';
}
// Validator output:
Line 2: Use '===' instead of '=='. (eqeqeq)
'0 == false' is true, '0 === false' is false.
Line 3: Use '===' instead of '=='. (eqeqeq)
Line 4: Acceptable — 'x == null' checks for both null and undefined.
Consider using explicit: status === null || status === undefined
// Demonstration of why == is dangerous:
0 == false // true ← unexpected
0 == '' // true ← unexpected
'' == false // true ← unexpected
null == undefined // true ← sometimes intentional
Example: Security Vulnerabilities
// Code:
function renderComment(userInput) {
document.getElementById('comments').innerHTML = userInput;
}
function executeUserScript(code) {
eval(code);
}
function buildQuery(username) {
return `SELECT * FROM users WHERE name = '${username}'`;
}
// Validator output:
Line 2: SECURITY — innerHTML with user input enables XSS attacks.
Use textContent or sanitize input with DOMPurify.
Line 6: SECURITY — eval() with user input enables code injection.
Avoid eval() entirely; use JSON.parse() for data, not code.
Line 10: SECURITY — SQL query built with string concatenation.
Use parameterized queries or prepared statements.
// Fixed:
function renderComment(userInput) {
document.getElementById('comments').textContent = userInput; // safe
}
Example: var vs let/const
// Code:
function processItems() {
var results = [];
for (var i = 0; i < 5; i++) {
var item = i * 2;
setTimeout(function() {
results.push(item); // bug: all push the same value (8)
}, 100);
}
}
// Validator output:
Line 2: Use 'const' or 'let' instead of 'var'. (no-var)
Line 3: Use 'let' instead of 'var' in for loop. (no-var)
Line 4: Use 'const' instead of 'var' (never reassigned). (prefer-const)
Line 5: Closure captures 'var item' — all callbacks will use the final value.
Use 'const item = i * 2' to capture each iteration's value.
Example: Unhandled Promises
// Code:
function loadUserData(userId) {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => updateUI(data));
// No .catch() — unhandled rejection!
}
async function saveData(data) {
await db.save(data); // if this throws, error is silently swallowed
}
// Validator output:
Line 2: Unhandled Promise rejection — add .catch() or use try/catch.
Line 8: Unhandled Promise rejection — wrap in try/catch.
// Fixed:
async function loadUserData(userId) {
try {
const res = await fetch(`/api/users/${userId}`);
const data = await res.json();
updateUI(data);
} catch (err) {
console.error('Failed to load user:', err);
}
}
Example: Deprecated Features
// Code:
function getArgs() {
return arguments.callee; // deprecated
}
with (Math) {
console.log(sqrt(16)); // with statement — deprecated
}
// Validator output:
Line 2: 'arguments.callee' is deprecated and forbidden in strict mode.
Use a named function expression instead.
Line 5: 'with' statement is deprecated and forbidden in strict mode.
Access Math.sqrt() directly.
Example: ES Version Compatibility
// Code (using ES2022 features):
const arr = [1, 2, 3, 4, 5];
const last = arr.at(-1); // ES2022
const obj = { a: 1 };
const hasA = Object.hasOwn(obj, 'a'); // ES2022
// Validator output (target: ES2019):
Line 2: 'Array.prototype.at()' requires ES2022. Not available in ES2019.
Alternative: arr[arr.length - 1]
Line 4: 'Object.hasOwn()' requires ES2022. Not available in ES2019.
Alternative: Object.prototype.hasOwnProperty.call(obj, 'a')
Full Validation Report
File: app.js — Validation Results
Errors (2):
Line 15, Col 8: SyntaxError — Unexpected token '}'
Line 42: 'undeclaredVar' is not defined (no-undef)
Warnings (4):
Line 8: Use '===' instead of '==' (eqeqeq)
Line 23: Unhandled Promise rejection (no-floating-promises)
Line 31: innerHTML with user input — XSS risk (security/no-inner-html)
Line 55: 'var' used — prefer 'const' or 'let' (no-var)
Info (2):
Line 12: Function complexity: 8 (max recommended: 5)
Line 67: Unused import 'lodash' (no-unused-vars)
Summary: 2 errors, 4 warnings, 2 info messages
Paste your JavaScript code to validate it against syntax rules, runtime error patterns, security checks, and best practices. Fix errors before they reach production.