條件判斷是程式碼的骨架,優化 if 不僅能縮減行數,更能提升可讀性與維護性。本文實戰演示三種優化模式,並給出「何時用、何時不宜用」的決策指南。
// 基礎形式
const result = condition ? valueIfTrue : valueIfFalse;
// 多層嵌套(慎用,超過兩層建議改用 if/else 或 switch)
const status = score >= 90 ? '優' :
score >= 60 ? '及格' : '不及格';
// 回傳/賦值/渲染均適用
return user.isAdmin ? renderAdminPanel() : renderUserPanel();
&& / || —— 單一條件副作用// 條件執行函式(副作用)
isLoggedIn && renderHeader();
hasError || showSuccessMessage();
// 預設值(注意:0、''、false 會觸發預設值,ES6 建議用 ??)
const limit = userInput || 10; // 0 會被視為 falsy
const limit = userInput ?? 10; // 僅 null/undefined 觸發預設值
適用場景: 條件式渲染、防禦性檢查、預設值賦值。
禁忌: 複雜邏輯、多條件組合、需要 else 分支時。
if/else if當條件為「根據離散值對應處理」時,物件或 Map 查找極具擴充性。
// 原始:冗長 if/else if
function getStatusText(code) {
if (code === 200) return '成功';
if (code === 400) return '請求錯誤';
if (code === 401) return '未授權';
if (code === 404) return '找不到';
return '未知狀態';
}
// 優化:物件查找表
const STATUS_MAP = {
200: '成功',
400: '請求錯誤',
401: '未授權',
404: '找不到'
};
function getStatusText(code) {
return STATUS_MAP[code] ?? '未知狀態';
}
// 複雜邏輯:對應處理函式
const HANDLERS = {
'GET': handleGet,
'POST': handlePost,
'PUT': handlePut,
'DELETE': handleDelete
};
function dispatch(req) {
const handler = HANDLERS[req.method] || handleNotAllowed;
return handler(req);
}
將每個條件分支封裝為獨立策略類別,符合開放封閉原則(OCP)。
class DiscountStrategy {
calculate(price) { throw new Error('Not implemented'); }
}
class VipDiscount extends DiscountStrategy {
calculate(price) { return price * 0.8; }
}
class SeasonalDiscount extends DiscountStrategy {
calculate(price) { return price - 100; }
}
const strategies = {
vip: new VipDiscount(),
seasonal: new SeasonalDiscount()
};
function getPrice(user, price) {
const strategy = strategies[user.type] || new DiscountStrategy();
return strategy.calculate(price);
}
需要條件判斷
│
├─► 只有 true/false 兩種結果,且是「賦值/回傳/渲染」 → 三元運算子
│
├─► 只有 true 才執行動作(副作用),無 else → && 短路
│
├─► 只有 false 才執行動作,無 else → || 短路
│
├─► 多個離散值對應不同結果/處理 → 查找表 (Object/Map)
│
├─► 條件涉及範圍、複雜邏輯、多重比較 → 完整 if/else if/else + 大括號
│
└─► 業務規則頻繁變動、需單元測試 → 策略模式 / 狀態模式
no-unneeded-ternary、no-lonely-if、curly優化 if 的終極目標不是「寫得少」,而是「意圖清晰、易於擴充、不易出錯」。選擇最能表達業務邏輯的模式,才是專業工程師的態度。