JavaScript 代码整洁之道:变量、函数与并发最佳实践

作者:纸飞机

时间:2026-10-24

浏览:160

本文系统介绍编写干净 JavaScript 代码的核心原则,涵盖变量命名、函数设计、条件语句、并发处理及错误管理。通过对比反模式与最佳实践,帮助开发者提升代码可读性、可维护性与测试友好度,避免副作用与重复代码,构建更健壮的 Web 应用。

文章目录

编写高质量的代码能让后续的阅读、复用和重构过程更加顺畅。在团队协作中,代码不仅是为自己编写,更是为了供其他同事理解、维护和扩展,因此保持代码清晰至关重要。

1. 变量

使用有意义的名称

变量名应当具备描述性和语义明确性。在 JavaScript 中,变量命名应遵循驼峰式大小写(camelCase)规范。


// Don't ❌
const foo = "JDoe@example.com";
const bar = "John";
const age = 23;
const qux = true;

// Do ✅
const email = "John@example.com";
const firstName = "John";
const age = 23;
const isActive = true

布尔类型的变量通常用于回答特定问题,例如:

isActive didSubscribe hasLinkedAccount

避免添加不必要的上下文

当变量所属的对象或类已经提供了足够的上下文信息时,无需在变量名中重复添加冗余的前缀或后缀。


// Don't ❌
const user = {
  userId: "296e2589-7b33-400a-b762-007b730c8e6d",
  userEmail: "JDoe@example.com",
  userFirstName: "John",
  userLastName: "Doe",
  userAge: 23,
};

user.userId;

// Do ✅
const user = {
  id: "296e2589-7b33-400a-b762-007b730c8e6d",
  email: "JDoe@example.com",
  firstName: "John",
  lastName: "Doe",
  age: 23,
};

user.id;

避免硬编码值

应声明具有明确语义且易于搜索的常量,而非直接在代码中插入魔法数字或字符串。全局常量建议使用全大写下划线分隔(SCREAMING_SNAKE_CASE)风格进行命名。


// Don't ❌
setTimeout(clearSessionData, 900000);

// Do ✅
const SESSION_DURATION_MS = 15 * 60 * 1000;

setTimeout(clearSessionData, SESSION_DURATION_MS);

2. 函数

使用有意义的名称

函数名应准确反映其执行的操作,即使名称较长也无妨。通常函数名使用动词形式,但若函数返回布尔值,可采用疑问句形式(如“是否...”),且函数名同样需遵循驼峰式命名。


// Don't ❌
function toggle() {
  // ...
}

function agreed(user) {
  // ...
}

// Do ✅
function toggleThemeSwitcher() {
  // ...
}

function didAgreeToAllTerms(user) {
  // ...
}

使用默认参数

利用 ES6 默认参数语法比使用逻辑与/或(&& ||)运算符或在函数体内编写额外的条件判断更为简洁清晰。


// Don't ❌
function printAllFilesInDirectory(dir) {
  const directory = dir || "./";
  //   ...
}

// Do ✅
function printAllFilesInDirectory(dir = "./") {
  // ...
}

限制参数的数量

尽管此规则存在争议,但建议函数参数控制在 3 个以内。若参数过多,通常意味着以下两种情况之一:

  • 该函数承担了过多职责,应当进行拆分。
  • 传递给函数的数据存在关联,应封装为专用的数据结构或对象进行传递。

// Don't ❌
function sendPushNotification(title, message, image, isSilent, delayMs) {
  // ...
}

sendPushNotification("New Message", "...", "http://...", false, 1000);

// Do ✅
function sendPushNotification({ title, message, image, isSilent, delayMs }) {
  // ...
}

const notificationConfig = {
  title: "New Message",
  message: "...",
  image: "http://...",
  isSilent: false,
  delayMs: 1000,
};

sendPushNotification(notificationConfig);

避免在一个函数中做太多事情

遵循单一职责原则,一个函数只应执行一项任务。这有助于缩小函数体积、降低复杂度,从而简化测试、调试和重构过程。


/ Don't ❌
function pingUsers(users) {
  users.forEach((user) => {
    const userRecord = database.lookup(user);
    if (!userRecord.isActive()) {
      ping(user);
    }
  });
}

// Do ✅
function pingInactiveUsers(users) {
  users.filter(!isUserActive).forEach(ping);
}

function isUserActive(user) {
  const userRecord = database.lookup(user);
  return userRecord.isActive();
}

避免使用布尔标志作为参数

如果函数包含布尔类型的标志参数,通常暗示该函数逻辑过于复杂,应当被进一步简化和拆分。


// Don't ❌
function createFile(name, isPublic) {
  if (isPublic) {
    fs.create(`./public/${name}`);
  } else {
    fs.create(name);
  }
}

// Do ✅
function createFile(name) {
  fs.create(name);
}

function createPublicFile(name) {
  createFile(`./public/${name}`);
}

避免写重复的代码

若代码中存在重复逻辑,每次业务规则变更时都需修改多个位置,极易遗漏并引发错误。


// Don't ❌
function renderCarsList(cars) {
  cars.forEach((car) => {
    const price = car.getPrice();
    const make = car.getMake();
    const brand = car.getBrand();
    const nbOfDoors = car.getNbOfDoors();

    render({ price, make, brand, nbOfDoors });
  });
}

function renderMotorcyclesList(motorcycles) {
  motorcycles.forEach((motorcycle) => {
    const price = motorcycle.getPrice();
    const make = motorcycle.getMake();
    const brand = motorcycle.getBrand();
    const seatHeight = motorcycle.getSeatHeight();

    render({ price, make, brand, nbOfDoors });
  });
}

// Do ✅
function renderVehiclesList(vehicles) {
  vehicles.forEach((vehicle) => {
    const price = vehicle.getPrice();
    const make = vehicle.getMake();
    const brand = vehicle.getBrand();

    const data = { price, make, brand };

    switch (vehicle.type) {
      case "car":
        data.nbOfDoors = vehicle.getNbOfDoors();
        break;
      case "motorcycle":
        data.seatHeight = vehicle.getSeatHeight();
        break;
    }

    render(data);
  });
}

避免副作用

在 JavaScript 开发中,推荐采用函数式编程风格而非命令式风格。大多数情况下,函数应保持纯净(Pure)。副作用会修改共享状态或资源,可能导致难以追踪的 Bug。所有涉及全局变量修改或文件操作的副作用应集中管理,例如通过专门的工具模块(util)处理。


// Don't ❌
let date = "21-8-2021";

function splitIntoDayMonthYear() {
  date = date.split("-");
}

splitIntoDayMonthYear();

// Another function could be expecting date as a string
console.log(date); // ['21', '8', '2021'];

// Do ✅
function splitIntoDayMonthYear(date) {
  return date.split("-");
}

const date = "21-8-2021";
const newDate = splitIntoDayMonthYear(date);

// Original vlaue is intact
console.log(date); // '21-8-2021';
console.log(newDate); // ['21', '8', '2021'];

此外,若需修改传入的可变值,应返回该值的新副本,而非直接修改原对象。


// Don't ❌
function enrollStudentInCourse(course, student) {
  course.push({ student, enrollmentDate: Date.now() });
}

// Do ✅
function enrollStudentInCourse(course, student) {
  return [...course, { student, enrollmentDate: Date.now() }];
}

3. 条件语句

使用非负条件


// Don't ❌
function isUserNotVerified(user) {
  // ...
}

if (!isUserNotVerified(user)) {
  // ...
}

// Do ✅
function isUserVerified(user) {
  // ...
}

if (isUserVerified(user)) {
  // ...
}

尽可能使用简写形式,如逻辑非(!)或空值合并(??)等。


// Don't ❌
if (isActive === true) {
  // ...
}

if (firstName !== "" && firstName !== null && firstName !== undefined) {
  // ...
}

const isUserEligible = user.isVerified() && user.didSubscribe() ? true : false;

// Do ✅
if (isActive) {
  // ...
}

if (!!firstName) {
  // ...
}

const isUserEligible = user.isVerified() && user.didSubscribe();

避免过多分支

尽早返回(early return)可以使代码逻辑线性化,提高可读性并降低嵌套复杂度。


// Don't ❌
function addUserService(db, user) {
  if (!db) {
    if (!db.isConnected()) {
      if (!user) {
        return db.insert("users", user);
      } else {
        throw new Error("No user");
      }
    } else {
      throw new Error("No database connection");
    }
  } else {
    throw new Error("No database");
  }
}

// Do ✅
function addUserService(db, user) {
  if (!db) throw new Error("No database");
  if (!db.isConnected()) throw new Error("No database connection");
  if (!user) throw new Error("No user");

  return db.insert("users", user);
}

优先使用 map 而不是 switch 语句

这种方式既能降低代码复杂度,又能提升运行性能。


// Don't ❌
const getColorByStatus = (status) => {
  switch (status) {
    case "success":
      return "green";
    case "failure":
      return "red";
    case "warning":
      return "yellow";
    case "loading":
    default:
      return "blue";
  }
};

// Do ✅
const statusColors = {
  success: "green",
  failure: "red",
  warning: "yellow",
  loading: "blue",
};

const getColorByStatus = (status) => statusColors[status] || "blue";

使用可选链接


const user = {
  email: "JDoe@example.com",
  billing: {
    iban: "...",
    swift: "...",
    address: {
      street: "Some Street Name",
      state: "CA",
    },
  },
};

// Don't ❌
const email = (user && user.email) || "N/A";
const street =
  (user &&
    user.billing &&
    user.billing.address &&
    user.billing.address.street) ||
  "N/A";
const state =
  (user &&
    user.billing &&
    user.billing.address &&
    user.billing.address.state) ||
  "N/A";

// Do ✅
const email = user?.email ?? "N/A";
const street = user?.billing?.address?.street ?? "N/A";
const street = user?.billing?.address?.state ?? "N/A";

4.并发

避免回调

回调函数容易导致代码嵌套过深(回调地狱),建议使用 Promise 或 async/await 替代传统回调。


// Don't ❌
getUser(function (err, user) {
  getProfile(user, function (err, profile) {
    getAccount(profile, function (err, account) {
      getReports(account, function (err, reports) {
        sendStatistics(reports, function (err) {
          console.error(err);
        });
      });
    });
  });
});

// Do ✅
getUser()
  .then(getProfile)
  .then(getAccount)
  .then(getReports)
  .then(sendStatistics)
  .catch((err) => console.error(err));

// or using Async/Await ✅✅

async function sendUserStatistics() {
  try {
    const user = await getUser();
    const profile = await getProfile(user);
    const account = await getAccount(profile);
    const reports = await getReports(account);
    return sendStatistics(reports);
  } catch (e) {
    console.error(err);
  }
}

5. 错误处理

妥善处理抛出的异常(throw)和被拒绝(reject)的 Promise。


/ Don't ❌
try {
  // Possible erronous code
} catch (e) {
  console.log(e);
}

// Do ✅
try {
  // Possible erronous code
} catch (e) {
  // Follow the most applicable (or all):
  // 1- More suitable than console.log
  console.error(e);

  // 2- Notify user if applicable
  alertUserOfError(e);

  // 3- Report to server
  reportErrorToServer(e);

  // 4- Use a custom error handler
  throw new CustomError(e);
}

6.注释

只注释业务逻辑

代码本身应具备高可读性,从而减少对注释的依赖。仅对复杂或晦涩的业务逻辑添加注释。


// Don't ❌
function generateHash(str) {
  // Hash variable
  let hash = 0;

  // Get the length of the string
  let length = str.length;

  // If the string is empty return
  if (!length) {
    return hash;
  }

  // Loop through every character in the string
  for (let i = 0; i < length; i++) {
    // Get character code.
    const char = str.charCodeAt(i);

    // Make the hash
    hash = (hash << 5) - hash + char;

    // Convert to 32-bit integer
    hash &= hash;
  }
}

// Do ✅
function generateHash(str) {
  let hash = 0;
  let length = str.length;
  if (!length) {
    return hash;
  }

  for (let i = 0; i < length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash; // Convert to 32bit integer
  }
  return hash;
}

使用版本控制

无需在代码中保留历史版本的注释,若需追溯历史,直接使用 git log 命令查询即可。


// Don't ❌
/**
 * 2021-7-21: Fixed corner case
 * 2021-7-15: Improved performance
 * 2021-7-10: Handled mutliple user types
 */
function generateCanonicalLink(user) {
  // const session = getUserSession(user)
  const session = user.getSession();
  // ...
}

// Do ✅
function generateCanonicalLink(user) {
  const session = user.getSession();
  // ...
}

好了,去写出你漂亮的代码吧!🌈

总结

到此这篇关于如何写出干净的JavaScript代码的文章就介绍到这了,更多相关写干净的JavaScript代码内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章