26 個寫高效干凈JavaScript 的小技巧
作為開發人員,我們努力編寫不僅實用而且干凈高效的代碼。干凈的代碼對于可維護性、可擴展性和可讀性至關重要。在不斷發展的 JavaScript 世界中,采用編寫干凈代碼的最佳實踐可以顯著提高編程效率和項目質量。
今天這篇內容,我們將分享26個JavaScript技巧,可幫助你編寫更簡潔、更高效的 JavaScript 代碼,并附有示例來幫助您實現更好的代碼效果。
1.使用const并避免使用 var
避免使用 var 聲明變量。相反,對塊作用域變量使用 let 和 const 可以提高可讀性并減少運行時錯誤。
// Instead of
var name = 'Lokesh Prajapati';
// Use
const name = 'Lokesh Prajapati'; // for constants
let age = 24; // for variables that may change
2. 使用描述性變量名稱
選擇描述其用途或它們所持有的值的變量和函數名稱。
// Instead of
const d = new Date();
// Use
const currentDate = new Date();
3. 使用模板文字
模板文字使字符串連接更具可讀性。
const name = 'Lokesh';
console.log(`Hello, ${name}!`); // More readable
4. 解構賦值
解構使得從數組中提取值或從對象中提取屬性變得更加容易。
const person = { name: 'Lokesh', age: 24 };
const { name, age } = person;
5. 默認參數
使用默認參數使您的函數更加健壯。
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
6. 箭頭函數
箭頭函數提供簡潔的語法并按詞法綁定 this 值。
const add = (a, b) => a + b;
7. 在異步代碼中使用 Promise 和 Async/Await
Promise 和 async/await 語法使異步代碼更易于閱讀和管理。
async function fetchData() {
const data = await fetch('https://api.example.com');
return data.json();
}
8. 模塊
使用模塊有效地組織和重用您的代碼。
// math.js
export const add = (a, b) => a + b;
// app.js
import { add } from './math.js';
console.log(add(2, 3));
9. 短路評估
使用短路求值來表達簡潔的條件表達式。
const greet = name => console.log(name || 'Guest');
10.三元運算符
三元運算符可以簡化 if-else 語句。
const age = 20;
const canVote = age >= 18 ? 'Yes' : 'No';
11. 擴展運算符
擴展運算符允許迭代器在需要 0+ 參數的地方進行擴展。
const nums = [1, 2, 3];
const newNums = [...nums, 4, 5];
12. 其余參數
剩余參數允許函數接受不定數量的參數作為數組。
function sum(...nums) {
return nums.reduce((acc, curr) => acc + curr, 0);
}
13. Chain Promises Wisely
Chain 承諾避免“回調地獄”并保持代碼整潔。
fetchData()
.then(data => processData(data))
.then(result => displayData(result))
.catch(error => console.error(error));
14.使用數組(Array)和對象(Object)方法
利用數組和對象的內置方法來獲得更簡潔和描述性的代碼。
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2);
15. 提前返回
使用提前返回來避免深層嵌套并使您的函數更加清晰。
function processUser(user) {
if (!user) return;
// Process user
}
16.避免全局變量
盡量減少全局變量的使用,以減少潛在的沖突和錯誤。
17. 明智地評論
注釋應該解釋“為什么”要做某事,而不是“正在做什么”,因為代碼本身對于后者應該是不言自明的。好的注釋可以防止誤解,并為將來閱讀您代碼的任何人(包括您自己)節省時間。
// Bad: The comment is unnecessary as the code is self-explanatory
// Increment the counter by one
counter++;
// Good: The comment provides context that the code cannot
// We increment the counter here because the user has opened a new session
counter++;
// Bad: Comment restates the code
// Check if the user is logged in
if (user.isLoggedIn) {
// ...
}
// Good: Explains why the condition is important
// Check if the user is logged in because only logged-in users have access to premium features
if (user.isLoggedIn) {
// Code to provide access to premium features
}
18. 一致的編碼風格
采用一致的編碼風格或遵循風格指南(如 Airbnb 的 JavaScript 風格指南)以保持可讀性。命名、間距和語法的一致性將使您的代碼更易于遵循和維護。
// Bad: inconsistent spacing and naming
function calculatevalue(a,b){
const total=a+b
return total;
}
// Good: consistent naming and spacing, following a common style guide
function calculateValue(a, b) {
const total = a + b;
return total;
}
19. 保持職能小而集中
每個功能應該做一件事,并且做好。小型、集中的函數更容易測試和調試。
// Bad: doing too much in one function
function handleUserData(user) {
if (user.age < 18) {
console.log('User is a minor');
} else {
console.log('User is an adult');
}
// Additional unrelated tasks...
}
// Good: breaking down into smaller, focused functions
function logUserAgeCategory(age) {
const category = age < 18 ? 'minor' : 'adult';
console.log(`User is a ${category}`);
}
20. 模塊化你的代碼
將您的代碼分解為模塊或組件。這不僅使其更易于管理,而且增強了可重用性。
// userValidation.js
export function isValidUser(user) {
// Validation logic...
}
// app.js
import { isValidUser } from './userValidation.js';
if (isValidUser(user)) {
// Proceed...
}
21. 避免使用幻數
用命名常量替換幻數,使代碼更具可讀性和可維護性。
const MAX_USERS = 10;
// Instead of
if (users.length > 10) {
// Do something
}
// Use
if (users.length > MAX_USERS) {
// Do something
}
22.簡化條件表達式
為了清晰起見,將復雜的條件分解為變量或更小的函數。
const isEligibleForDiscount = (user) => user.age > 65 || user.memberStatus === 'VIP';
if (isEligibleForDiscount(user)) {
// Apply discount
}
23. 謹慎使用注釋
代碼應該盡可能不言自明。使用注釋來解釋“為什么”而不是“什么”。
// Bad: unnecessary comment
// adds one to the number
const increment = (number) => number + 1;
// Good: comment explaining why
// We add 1 to include the last day of the range
const inclusiveEnd = (start, end) => end - start + 1;
24. 更喜歡組合而不是繼承
組合提供了更大的靈活性,并降低了與深層繼承層次結構相關的復雜性。
const canEat = {
eat: function() {
console.log('Eating');
}
};
// Composition
const person = Object.assign({}, canEat);
person.eat(); // Eating
25. 封裝代碼塊
封裝處理特定任務的代碼部分。這提高了可讀性和可重用性。
function processOrder(order) {
const validateOrder = (order) => {
// Validation logic
};
26. 了解最新功能
JavaScript 不斷發展。及時了解最新功能可以幫助您編寫更高效、更簡潔的代碼。
// Old way: callbacks
fs.readFile(filePath, function(err, data) {
if (err) throw err;
console.log(data);
});
// New way: async/await
async function readFileAsync(filePath) {
try {
const data = await fs.promises.readFile(filePath);
console.log(data);
} catch (err) {
console.error(err);
}
}
總結
接受這些技巧不僅可以提高您的 JavaScript 編碼技能,還可以使您的代碼庫更易于維護且使用起來更愉快。請記住,編寫干凈代碼的目標不僅僅是遵守規則,而是讓您的代碼盡可能清晰易懂,讓其他人(包括未來的您)可以理解。