JavaScript 條件語句的最佳實踐
本文將介紹 JavaScript 條件語句的最佳實踐。
YouTube Video
JavaScript 條件語句的最佳實踐
if 語句是 JavaScript 程式中的基本控制結構。然而,隨著程式變得更加複雜,if 語句的數量可能會增加,從而使程式更難閱讀。這次,我們將深入探討如何在 JavaScript 中正確設計 if 語句,以提高程式的可讀性和可維護性。
使用標誌簡化代碼
通過使用布林值來簡化涉及多個條件的邏輯。
需要避免的範例
1// Bad Example
2if (isUserLoggedIn && user.hasPaymentInfo && user.cartItems.length > 0) {
3 console.log('Proceed to checkout');
4}改進後的範例
使用標誌來明確條件。
1// Good Example
2const canProceedToCheckout = isUserLoggedIn && user.hasPaymentInfo && user.cartItems.length > 0;
3
4if (canProceedToCheckout) {
5 console.log('Proceed to checkout');
6}保持條件語句簡單
當條件表達式變得複雜時,代碼的可讀性會降低,因此有必要保持條件簡單。
需要避免的範例
1// Bad example
2if (user && user.isLoggedIn &&
3 user.permissions && user.permissions.includes('admin')) {
4 console.log('Welcome, admin!');
5}改進後的範例
通過將條件分解為具有明確含義的變數,您可以明確其意圖。
1// Good Example
2const isUserLoggedIn = user?.isLoggedIn;
3const hasAdminPermission = user?.permissions?.includes('admin');
4
5if (isUserLoggedIn && hasAdminPermission) {
6 console.log('Welcome, admin!');
7}釐清邏輯運算符的優先順序
在 JavaScript 的 if 語句中,誤解邏輯運算符的優先順序可能會導致意外的行為。
需要避免的範例
1// Bad example
2if (isAdmin && isActive || isPremium) {
3 // The precedence of `&&` is higher than `||`,
4 // so this expression is interpreted as
5 // ((isAdmin && isActive) || isPremium)
6 console.log("Access granted");
7} else {
8 console.log("Access denied");
9}改進後的範例
當運算符的優先順序不明確時,可以適當使用括號來進行釐清。
1// Good Example
2if (isAdmin && (isActive || isPremium)) {
3 console.log("Access granted");
4} else {
5 console.log("Access denied");
6}使用短路評估
JavaScript 支援 &&(AND)和 ||(OR)運算符的短路求值。短路求值是指當某條件的結果已經確定時,剩餘部分將不再被求值。
AND(&&):如果左側被判定為 false,則右側不會被求值並直接返回其值。OR(||):如果左側被判定為 true,則右側不會被求值並直接返回其值。
需要避免的範例
1// Bad Example
2if (user?.someComplexFunction() && user?.isLoggedIn) {
3 // ...
4}改進後的範例
在這段程式碼中,即使 user?.isLoggedIn 為 false,仍會執行 user?.someComplexFunction() 函數。
理解短路求值可以幫助您避免不必要的計算,並撰寫高效的程式碼。
1// Good Example
2if (user?.isLoggedIn && user?.someComplexFunction()) {
3 // ...
4}盡量減少使用 else 語句
else 語句在追蹤程式碼時可能增加認知負擔。相反,請考慮使用提前返回(early returns)。
需要避免的範例
1// Bad Example
2function getUserRole(user) {
3 if (!user) {
4 return 'Guest';
5 } else {
6 return user.role;
7 }
8}改進後的範例
通過提前返回來明確條件。
1// Good Example
2function getUserRole(user) {
3 if (!user) return 'Guest';
4 return user.role;
5}正確使用三元運算符
對於簡單的條件,使用三元運算符可以縮短代碼。但是,應避免嵌套或複雜的邏輯。
需要避免的範例
1// Bad Example
2let message = user.isLoggedIn ? user.isAdmin ?
3 'Welcome, admin!'
4 : 'Welcome, user!'
5 : 'Please log in.';改進後的範例
通過分解條件來優先考慮可讀性。
1// Good Example
2if (!user.isLoggedIn) {
3 message = 'Please log in.';
4} else if (user.isAdmin) {
5 message = 'Welcome, admin!';
6} else {
7 message = 'Welcome, user!';
8}使用默認值和短路評估
使用默認值和短路運算來減少分支並簡化代碼。
需要避免的範例
1// Bad Example
2let displayName;
3if (user && user.name) {
4 displayName = user.name;
5} else {
6 displayName = 'Guest';
7}改進後的範例
在此情況下,使用邏輯運算符可以讓程式碼更簡潔。
1// Good Example
2displayName = user?.name || 'Guest';正確區分何時使用 switch 語句
當需要多個條件時,switch 語句可以使意圖更加清晰。
需要避免的範例
1// Bad Example
2if (status === 'success') {
3 console.log('Operation was successful.');
4} else if (status === 'error') {
5 console.error('There was an error.');
6} else if (status === 'pending') {
7 console.log('Operation is still pending.');
8} else {
9 console.log('Unknown status.');
10}改進後的範例
使用 switch 語句可以幫助組織代碼。
1// Good Example
2switch (status) {
3 case 'success':
4 console.log('Operation was successful.');
5 break;
6 case 'error':
7 console.error('There was an error.');
8 break;
9 case 'pending':
10 console.log('Operation is still pending.');
11 break;
12 default:
13 console.log('Unknown status.');
14}使用警戒條款與提前退出條件
保護性語句是一種使用 if 語句提前退出函數的技術。
需要避免的範例
1// Bad Example
2function processOrder(order) {
3 if (order && order.isValid) {
4 if (order.items && order.items.length > 0) {
5 // Continue processing
6 }
7 }
8}改進後的範例
使用保護性語句來減少嵌套。
1// Good Example
2function processOrder(order) {
3 if (!order?.isValid) return;
4 if (!order.items?.length) return;
5
6 // Continue processing
7}撰寫註解以闡明意圖
針對複雜條件或關鍵分支,添加簡明清晰的註解以傳達代碼的意圖。
需要避免的範例
1// Bad Example
2if (stock > 10 && !isRestricted) {
3 console.log('Available for purchase.');
4}改進後的範例
添加註解以明確意圖。
1// Good Example
2// The product must have at least 10 items in stock
3// and not be on the restricted list.
4if (stock > 10 && !isRestricted) {
5 console.log('Available for purchase.');
6}結論
有效使用 JavaScript 的 if 語句可以大幅提升代碼的可讀性和可維護性。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。