10 Clean Alternatives to If‑Else in JavaScript for Maintainable Code
When traditional if‑else chains become verbose and hard to maintain, JavaScript offers several concise alternatives—including object mapping, Array.includes, ternary chains, logical operators, switch pattern matching, Proxy interception, functional programming, state machines, and decorators—each illustrated with clear code snippets to improve readability and scalability.
When traditional if‑else statements become lengthy and hard to maintain, JavaScript provides several cleaner alternatives that improve readability and scalability.
1. Object Mapping to Replace if‑else
Traditional version
function getPrice(user) {
if (user.type === 'vip') {
return 'VIP价格';
} else if (user.type === 'svip') {
return 'SVIP价格';
} else if (user.type === 'vvip') {
return 'VVIP价格';
} else {
return '普通价格';
}
}Alternative version
const priceStrategy = {
vip: () => 'VIP价格',
svip: () => 'SVIP价格',
vvip: () => 'VVIP价格',
default: () => '普通价格'
};
function getPrice(user) {
return (priceStrategy[user.type] || priceStrategy.default)();
}2. Using Array.includes for Multiple Conditions
Traditional version
if (status === 'failed' || status === 'error' || status === 'rejected') {
handleError();
}Alternative version
const errorStatus = ['failed', 'error', 'rejected'];
if (errorStatus.includes(status)) {
handleError();
}3. Chaining Ternary Operators
4. Clever Use of && and || Operators
5. Switch Pattern Matching
6. Using Proxy for Conditional Interception
7. Functional Programming Techniques
8. State Machine Pattern
9. Decorator for Permission Checks
function checkPermission(target, name, descriptor) {
const original = descriptor.value;
descriptor.value = function(...args) {
if (this.user?.hasPermission) {
return original.apply(this, args);
}
throw new Error('No permission');
};
return descriptor;
}
class Document {
@checkPermission
edit() {
// 编辑文档
}
}JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
