缩进:使用 2 个空格 作为缩进,禁止使用 Tab。
空格:
在操作符前后添加空格,如 a + b
。
在逗号后添加空格,如 function(a, b, c)
。
在花括号前添加空格,如 if (condition) {
。
在注释符 //
后添加空格,如 // 注释
。
每行代码长度:不超过 80 个字符,超出时换行。
换行规则:
在操作符后换行。
在逗号后换行。
保持代码块清晰,避免过度换行。
const result = someVeryLongFunctionName(argument1, argument2, argument3) .then(data => { // 处理数据 }) .catch(error => { // 处理错误 }); |
变量和函数:使用 camelCase
命名法,如 userName
、getUserInfo
。
常量:使用 UPPER_SNAKE_CASE
命名法,如 MAX_COUNT
。
类:使用 PascalCase
命名法,如 UserModel
。
私有成员:使用 _
前缀,如 _privateMethod
。
const MAX_COUNT = 100; function getUserInfo(userId) { // 逻辑 } class UserModel { constructor() { this._privateProperty = 'private'; } _privateMethod() { // 私有方法 } } |
使用 单引号 '
作为字符串的引号,除非字符串中包含单引号。
const name = 'John'; const message = "He's a developer"; |
必须使用分号,避免因自动插入分号导致的潜在问题。
const a = 1; const b = 2; |
始终使用花括号,即使代码块只有一行。
if (condition) { doSomething(); } |
单行注释:使用 //
,注释内容与符号之间保留一个空格。
多行注释:使用 /* ... */
。
函数注释:使用 JSDoc 格式。
/ 单行注释 /* * 多行注释 */ /** * 获取用户信息 * @param {string} userId - 用户 ID * @returns {Object} 用户信息 */ function getUserInfo(userId) { // 逻辑 } |
使用 const
声明常量,使用 let
声明变量,避免使用 var
。
每个声明语句只声明一个变量。
const MAX_COUNT = 100; let userName = 'John'; |
尽量在声明时初始化变量。
let count = 0; const name = 'John'; |
避免使用全局变量,尽量将变量限制在局部作用域内。
使用 camelCase
命名法,函数名应清晰描述其功能。
function calculateTotalPrice(items) { // 逻辑 } |
参数数量不宜过多(建议不超过 5 个),过多时使用对象传递。
function createUser({ name, age, email, address }) { // 逻辑 } |
优先使用箭头函数,尤其是回调函数和匿名函数。
const numbers = [1, 2, 3]; const doubled = numbers.map(num => num * 2); |
使用默认参数替代函数内部的默认值逻辑。
function greet(name = 'Guest') { console.log(`Hello, ${name}`); } |
使用字面量创建对象,避免使用 new Object()
。
const user = { name: 'John', age: 30, }; |
属性名使用 camelCase
命名法。
动态属性名使用 []
。
const key = 'name'; const user = { [key]: 'John', }; |
使用字面量创建数组,避免使用 new Array()
。
const numbers = [1, 2, 3]; |
优先使用 map
、filter
、reduce
等函数式方法。
const doubled = numbers.map(num => num * 2); |
使用 class
关键字定义类,避免使用原型链。
class User { constructor(name) { this.name = name; } greet() { console.log(`Hello, ${this.name}`); } } |
使用 ES Module
进行模块化开发。
// user.js export class User { // 类定义 } // main.js import { User } from './user.js'; |
使用 Promise
处理异步操作,避免回调地狱。
function fetchData() { return new Promise((resolve, reject) => { // 异步操作 }); } |
优先使用 async/await
替代 Promise.then
。
async function getUser() { try { const user = await fetchData(); console.log(user); } catch (error) { console.error(error); } } |
使用 try/catch
捕获同步代码中的错误。
try { doSomething(); } catch (error) { console.error(error); } |
使用 .catch()
或 try/catch
捕获异步错误。
fetchData() .then(data => { // 处理数据 }) .catch(error => { console.error(error); }); |