Code Quality
Magic Numbers in JavaScript: Why They're a Problem
Magic numbers are unexplained numeric literals embedded directly in code. They reduce readability and cause maintenance bugs when the same value appears in multiple places.
❌ Code with Magic Numbers
function getStatusLabel(status) {
if (status === 1) return 'Active';
if (status === 2) return 'Pending';
if (status === 3) return 'Cancelled';
}
setTimeout(syncData, 86400000); // How many days?✅ Named Constants
const ORDER_STATUS = { ACTIVE: 1, PENDING: 2, CANCELLED: 3 };
const MS_PER_DAY = 24 * 60 * 60 * 1000;
function getStatusLabel(status) {
const labels = {
[ORDER_STATUS.ACTIVE]: 'Active',
[ORDER_STATUS.PENDING]: 'Pending',
[ORDER_STATUS.CANCELLED]: 'Cancelled',
};
return labels[status] ?? 'Unknown';
}
setTimeout(syncData, MS_PER_DAY);💡
Pro tip: Use TypeScript enums for related constants to get naming benefits plus compile-time type safety.
Paste this code into LearnCodeGuide
Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.
Analyze JavaScript Code →