Beyond if‑else: 9 Cleaner JavaScript Patterns for Conditional Logic
This article presents nine practical JavaScript techniques—ranging from object maps and Array.includes to ternary chains, logical operators, switch statements, Proxy, functional patterns, state machines, and decorators—that replace verbose if‑else statements with cleaner, more maintainable code.
1. Object mapping instead of 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. Chained ternary operator
Traditional version
Alternative version
4. Clever use of && and || operators
5. Switch pattern matching
6. Using Proxy for condition interception
7. Functional programming methods
8. State machine pattern
9. Using decorators to handle permissions
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() {
// 编辑文档
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
