26 个写高效干净JavaScript 的小技巧

开发 前端
作为开发人员,我们努力编写不仅实用而且干净高效的代码。干净的代码对于可维护性、可扩展性和可读性至关重要。在不断发展的 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 编码技能,还可以使您的代码库更易于维护且使用起来更愉快。请记住,编写干净代码的目标不仅仅是遵守规则,而是让您的代码尽可能清晰易懂,让其他人(包括未来的您)可以理解。

责任编辑:华轩 来源: web前端开发
相关推荐

2020-09-26 21:50:26

JavaScript代码开发

2018-11-28 12:30:58

Python命令行编程语言

2019-07-31 10:24:16

JavaScript浏览器口袋妖怪

2024-03-28 14:29:46

JavaScript编程

2020-12-14 08:30:02

JavaScript开发代码

2019-12-20 14:32:55

JavaScript函数开发

2021-03-15 08:13:19

JavaScript开发代码

2017-10-30 17:25:11

javascript

2016-05-10 10:16:13

JavaScript技巧

2020-05-17 16:19:59

JavaScript代码开发

2024-01-30 08:54:05

JavaScript技巧代码

2023-07-19 15:16:33

远程办公技巧

2021-12-27 14:33:47

Python语言开发

2017-09-14 12:45:35

2020-11-11 08:22:40

前端开发JavaScript

2019-01-29 15:40:06

云应用开发云环境

2023-10-09 18:13:14

MySQL数据库查询

2009-10-27 09:09:06

Eclipse技巧

2023-10-23 15:02:53

JavaScript

2022-08-16 10:53:56

JavaScript前端技巧
点赞
收藏

51CTO技术栈公众号