阿里云主机折上折
  • 微信号
Current Site:Index > Naming rules

Naming rules

Author:Chuan Chen 阅读数:63862人阅读 分类: JavaScript

The Importance of Naming Conventions

Good naming conventions enhance code readability, maintainability, and reduce communication costs in team collaboration. As a weakly typed language, naming conventions are particularly important in JavaScript, as they compensate for the lack of information due to the absence of a type system.

Variable Naming

Basic Rules

Variable names should use camelCase and consist of meaningful English words. Avoid abbreviations unless they are widely recognized:

// Good  
const userList = [];  
let isLoading = false;  

// Bad  
const ul = [];  // Meaningless abbreviation  
let isld = false; // Obscure abbreviation  

Boolean Naming

Boolean variables should use prefixes like is, has, or can:

const isVisible = true;  
const hasPermission = false;  
const canEdit = true;  

Special Value Naming

For variables that may be null or undefined, explicitly express their state:

let selectedUser = null;  // Better than let user = null  
let currentPageIndex = undefined;  

Constant Naming

Regular Constants

Use SCREAMING_SNAKE_CASE (all uppercase with underscores) for values that do not change:

const MAX_RETRY_COUNT = 3;  
const API_TIMEOUT = 5000;  

Module-Level Constants

For constants used within a module, still use camelCase but prefix with k:

const kDefaultPageSize = 10;  
const kCacheExpiryTime = 60 * 60 * 1000;  

Function Naming

Regular Functions

Use camelCase and start with a verb to indicate functionality:

function getUserById(id) { /*...*/ }  
function calculateTotalPrice() { /*...*/ }  

Return Type Hints

Use names that hint at the return type:

// Returns a boolean  
function isValidEmail(email) { /*...*/ }  

// Returns an array  
function getActiveUsers() { /*...*/ }  

Callback Functions

Callback function names should include the on or handle prefix:

function onButtonClick() { /*...*/ }  
function handleInputChange() { /*...*/ }  

Class Naming

Classes and Constructors

Use PascalCase:

class UserModel {  
  constructor() { /*...*/ }  
}  

function DatabaseConnection() { /*...*/ }  

Private Members

For ES2019+ private fields, use the # prefix:

class User {  
  #passwordHash;  
    
  constructor() {  
    this.#passwordHash = '';  
  }  
}  

File and Directory Naming

File Naming

Use all lowercase letters, with multiple words connected by hyphens:

user-service.js  
date-utils.js  

Component Files

React/Vue components use PascalCase:

UserProfile.vue  
NotificationList.jsx  

Test Files

Name test files the same as the tested file, with a .test suffix:

utils.js → utils.test.js  
User.spec.js (Vue testing convention)  

Special Naming Scenarios

Event Naming

DOM events should be all lowercase, while custom events use kebab-case:

element.addEventListener('click', handler);  

// Custom event  
emitter.emit('user-logged-in', data);  

Configuration Objects

Configuration items use camelCase, consistent with API parameters:

const chartConfig = {  
  showLegend: true,  
  animationDuration: 300  
};  

Type Variables

TypeScript types use PascalCase:

interface UserProfile {  
  id: number;  
  name: string;  
}  

type HttpResponse<T> = {  
  data: T;  
  status: number;  
};  

Controlling Naming Length

Ideal Length

Variable names should ideally consist of 2-3 words, and function names 3-4 words:

// Just right  
const recentOrders = [];  
function formatCurrencyValue() { /*...*/ }  

// Too long  
const listOfRecentlyPlacedCustomerOrders = [];  
function convertMonetaryValueToLocalCurrencyFormat() { /*...*/ }  

Contextual Abbreviations

Abbreviations are acceptable in clear contexts:

// Inside a User class  
class User {  
  saveToDb() { /*...*/ }  // More concise than saveToDatabase  
}  

Naming Practices to Avoid

Misleading Names

Avoid names that conflict with language features:

// Bad  
const new = getNewObject(); // Keyword conflict  
let obj = {}; // Meaningless  

// Good  
const freshInstance = getNewObject();  
let userData = {};  

Single-Letter Variables

Use only in short-lived scopes:

// Acceptable  
array.forEach((item) => { /*...*/ });  

// Bad  
function calculate(a, b, c) { /*...*/ }  

Underscore Prefixes

No longer recommended for "private" members (use # instead):

// Old way (not recommended)  
class User {  
  _internalId;  
}  

// New way  
class User {  
  #internalId;  
}  

Naming Consistency

Project-Wide Uniformity

Use the same naming for the same concept throughout the project:

// Consistent across the project  
let cartItems = [];  // Not shoppingCartProducts  

// Uniform API response handling  
function handleApiError() { /*...*/ } // Not processHttpFailure  

Language Conventions

Follow traditional JavaScript naming styles:

// jQuery style (outdated)  
const $container = $('#main');  

// Modern standard  
const mainContainer = document.querySelector('#main');  

Naming and Refactoring

Signals for Renaming

Consider renaming in these cases:

// 1. Adding comments to explain variable purpose  
const d; // Distance in meters → Should be renamed to distanceInMeters  

// 2. Function content does not match its name  
function processData() {  
  // Actually validates data  
  return isValid;  
}  

Safe Refactoring Techniques

Use IDE refactoring tools:

// WebStorm/VS Code supports:  
// Right-click → Refactor → Rename  
class BadName {  
  // When renamed to GoodName, all references update automatically  
}  

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:文件组织结构

下一篇:变量声明规范

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.