JavaScript Code Standards
Code standards are essential factors for ensuring code quality, readability, and maintainability. Good coding standards help team members collaborate better, reduce errors, and improve development efficiency. In this chapter, we'll learn JavaScript best coding practices and code standards.
Why Code Standards Matter
The importance of code standards is reflected in the following aspects:
- Improved Readability: Unified code style makes code easier to read and understand
- Better Team Collaboration: Team members following the same standards reduces communication costs
- Fewer Errors: Good standards help avoid common programming mistakes
- Enhanced Maintainability: Standardized code is easier to maintain and modify
- Higher Code Quality: Unified standards help improve overall code quality
Naming Conventions
Variable Naming
javascript
// Good naming - use meaningful English words
const userName = "John";
const userAge = 25;
const isLoggedIn = true;
const userList = [];
// Avoid meaningless naming
// const a = "John";
// const b = 25;
// const c = true;
// Use camelCase
const firstName = "John";
const lastName = "Doe";
const emailAddress = "john@example.com";
// Boolean variables use is, has, can prefixes
const isActive = true;
const hasPermission = false;
const canEdit = true;
// Arrays use plural form
const users = [];
const items = [];
const messages = [];
// Constants use UPPER_SNAKE_CASE
const MAX_SIZE = 100;
const DEFAULT_TIMEOUT = 5000;
const API_BASE_URL = "https://api.example.com";Function Naming
javascript
// Start with a verb, describe the function's behavior
function getUserInfo() {
// ...
}
function calculateTotal() {
// ...
}
function validateForm() {
// ...
}
function handleClick() {
// ...
}
// Event handlers can use handle or on prefix
function handleInputChange() {
// ...
}
function onSubmit() {
// ...
}
// Functions returning boolean can use is, has prefixes
function isValid() {
// ...
}
function hasPermission() {
// ...
}Class and Constructor Naming
javascript
// Use PascalCase (first letter capitalized)
class UserManager {
// ...
}
class HttpRequest {
// ...
}
class DatabaseConnection {
// ...
}
// Constructors also use PascalCase
function Person(name, age) {
this.name = name;
this.age = age;
}Code Formatting Standards
Indentation and Spacing
javascript
// Use 2 or 4 spaces for indentation (2 spaces recommended)
function example() {
if (true) {
console.log("Use 2-space indentation");
}
}
// Add spaces around operators
const sum = a + b;
const isValid = age > 18 && name !== "";
// Add space after comma
const arr = [1, 2, 3];
const obj = { name: "John", age: 25 };
// Add spaces inside braces
const obj2 = { name: "Jane", age: 30 };
function greet(name) { return "Hello, " + name; }Brace Position
javascript
// Recommended: Put opening brace at end of line (Egyptian brackets)
function example() {
if (condition) {
// ...
} else {
// ...
}
}
// Not recommended: Put opening brace on next line
// function example()
// {
// if (condition)
// {
// // ...
// }
// else
// {
// // ...
// }
// }Line Length
javascript
// Keep each line within reasonable length (usually 80-120 characters)
const veryLongVariableName = "This is a long string that needs proper line breaks";
const anotherLongVariable = veryLongFunctionName(parameter1, parameter2,
parameter3, parameter4);
// Break lines when function has too many parameters
function createUser(firstName, lastName, email, age, address, phoneNumber,
department, position) {
// function body
}Comment Standards
Single-line Comments
javascript
// Good comment: Explain why, not what
const maxRetries = 3; // Prevent request failures due to network fluctuations
// Avoid meaningless comments
// const name = "John"; // Set user name (meaningless comment)
// Add comments before complex logic
// Using binary search algorithm, time complexity O(log n)
function binarySearch(arr, target) {
// ...
}Multi-line Comments
javascript
/*
* This is a multi-line comment example
* Used to explain complex algorithms or features
* Can span multiple lines
*/
/**
* Function documentation
* @param {string} name - User name
* @param {number} age - User age
* @returns {object} User object
*/
function createUser(name, age) {
return { name, age };
}Variable Declaration Standards
javascript
// Prefer const, use let when necessary
const userName = "John";
let userAge = 25;
userAge = 26; // Can be reassigned
// Avoid using var
// var oldStyle = "not recommended";
// Related variables can be declared together
const WIDTH = 800;
const HEIGHT = 600;
const ASPECT_RATIO = WIDTH / HEIGHT;
// Unrelated variables should be declared separately
const userName = "John";
let userAge = 25;
const isLoggedIn = true;
// Declare variables only when needed
function example() {
// other code...
const result = calculateSomething(); // Declare before use
return result;
}Function Standards
Function Length
javascript
// Keep functions short, one function does one thing
function validateUser(user) {
return validateName(user.name) &&
validateEmail(user.email) &&
validateAge(user.age);
}
function validateName(name) {
return name && name.length >= 2;
}
function validateEmail(email) {
return email && email.includes("@");
}
function validateAge(age) {
return age && age >= 0 && age <= 150;
}Function Parameters
javascript
// Keep parameter count low, recommend no more than 3
function createUser(name, email, age) {
// ...
}
// Use object parameter when there are too many parameters
function createAdvancedUser(options) {
const {
name,
email,
age,
address,
phone,
department
} = options;
// ...
}
// Use default parameters
function greet(name = "Guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}Object and Array Standards
Object Literals
javascript
// Shorthand property syntax
const name = "John";
const age = 25;
// Good practice
const user = {
name,
age,
isActive: true
};
// Method shorthand
const userActions = {
login() {
// ...
},
logout() {
// ...
}
};Array Operations
javascript
// Use array methods for functional programming
const numbers = [1, 2, 3, 4, 5];
// Good practice
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
// Avoid using for loops to modify arrays
// Prefer using array methodsError Handling Standards
javascript
// Always handle errors in async operations
async function fetchData() {
try {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Failed to fetch data:", error);
throw error; // Re-throw error or return default value
}
}
// Synchronous code should also handle possible errors
function parseJson(str) {
try {
return JSON.parse(str);
} catch (error) {
console.error("JSON parsing failed:", error);
return null;
}
}Comparison Operator Standards
javascript
// Use strict equality operators
if (value === null) {
// ...
}
if (value === undefined) {
// ...
}
// Avoid loose equality operators
// if (value == null) // Matches both null and undefinedString Standards
javascript
// Use template literals
const name = "John";
const age = 25;
const message = `Hello, I am ${name}, ${age} years old`;
// Use template literals for multi-line strings
const html = `
<div>
<h1>Title</h1>
<p>Content</p>
</div>
`;Conditional Statement Standards
javascript
// Extract complex conditions into variables
const isUserValid = user && user.name && user.email;
const isWithinAgeRange = user.age >= 18 && user.age <= 65;
if (isUserValid && isWithinAgeRange) {
// ...
}
// Use early return to reduce nesting
function processUser(user) {
if (!user) {
return;
}
if (!user.isActive) {
return;
}
// Process valid active user
// ...
}Loop Standards
javascript
// Prefer array methods over for loops
const users = [{ name: "John", age: 25 }, { name: "Jane", age: 30 }];
// Good practice
users.forEach(user => {
console.log(user.name);
});
const adultUsers = users.filter(user => user.age >= 18);
// Avoid modifying array length inside loops
// for (let i = 0; i < arr.length; i++) {
// if (someCondition) {
// arr.splice(i, 1); // May skip elements
// }
// }Module Standards
javascript
// Import statements at the top of the file
import React from "react";
import { useState, useEffect } from "react";
import utils from "./utils";
import "./App.css";
// Use ES6 export syntax
export function helperFunction() {
// ...
}
export default function Component() {
// ...
}
// Group related imports
// Third-party libraries
import React from "react";
import lodash from "lodash";
// Internal modules
import utils from "./utils";
import constants from "./constants";
// Style files
import "./Component.css";Code Organization Standards
File Structure
javascript
// Good file organization structure
class UserManager {
// Static properties
static DEFAULT_ROLE = "user";
// Private properties (using # or _ prefix)
#users = [];
// Constructor
constructor() {
// Initialization code
}
// Public methods
addUser(user) {
// ...
}
// Private methods (using _ prefix)
_validateUser(user) {
// ...
}
// Getter and Setter
get userCount() {
return this.#users.length;
}
}Best Practices Summary
1. Maintain Consistency
javascript
// Maintain consistent style throughout the project
// If the team chooses to use semicolons, use them everywhere
const name = "John";
console.log(name);
// If choosing not to use semicolons, don't use them anywhere
const age = 25
console.log(age)2. Use Modern JavaScript Features
javascript
// Use destructuring assignment
const user = { name: "John", age: 25 };
const { name, age } = user;
// Use spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
// Use optional chaining
const userName = user?.profile?.name;
// Use nullish coalescing operator
const displayName = user.name ?? "Anonymous";3. Avoid Common Pitfalls
javascript
// Avoid global variables
// Bad practice
// var globalCounter = 0;
// Good practice
const Counter = {
value: 0,
increment() {
this.value++;
}
};
// Avoid creating functions inside loops
// Bad practice
// for (var i = 0; i < 10; i++) {
// setTimeout(function() {
// console.log(i); // Outputs 10 ten times
// }, 100);
// }
// Good practice
for (let i = 0; i < 10; i++) {
setTimeout(() => {
console.log(i); // Outputs 0, 1, 2, ..., 9
}, 100);
}Tool Support
Code Formatter
json
// .prettierrc configuration example
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}Linter
json
// .eslintrc configuration example
{
"extends": ["eslint:recommended"],
"rules": {
"no-console": "warn",
"no-unused-vars": "error"
}
}Summary
Key points of JavaScript code standards:
- Naming Conventions: Use meaningful English names, follow camelCase
- Code Format: Maintain consistent indentation and spacing
- Comment Standards: Add meaningful comments, explain why not what
- Variable Declaration: Prefer const, use let when necessary, avoid var
- Function Standards: Keep functions short, moderate parameter count
- Error Handling: Always handle possible error cases
- Modern Features: Use ES6+ modern JavaScript features
- Tool Support: Use Prettier, ESLint and other tools to automate code standards
Following these standards will help you write higher quality, more maintainable JavaScript code. In the next chapter, we'll learn about JavaScript classes and objects.