Home  >  Article  >  Web Front-end  >  General Coding Standards JavaScript.

General Coding Standards JavaScript.

王林
王林Original
2024-08-06 18:33:401161browse

General Coding Standards JavaScript.

General Coding Standards

  1. Meaningful Names:
    • Use meaningful and descriptive variable and function names.
    • Avoid abbreviations and single-letter names except for loop counters.
   // Good
   const userAge = 25;
   function calculateTotalPrice(items) { ... }

   // Bad
   const a = 25;
   function calc(items) { ... }
  1. Consistent Naming Conventions:
    • Use camelCase for variables and functions.
    • Use PascalCase for class names.
   const userAge = 25;
   function calculateTotalPrice(items) { ... }
   class UserProfile { ... }
  1. Avoid Repetition:
    • Follow the DRY (Don't Repeat Yourself) principle by encapsulating repeated code into functions.
   // Good
   function calculateDiscount(price, discount) { ... }
   const price1 = calculateDiscount(100, 10);
   const price2 = calculateDiscount(200, 20);

   // Bad
   const price1 = 100 - 10;
   const price2 = 200 - 20;
  1. Error Handling:
    • Wrap API calls and other asynchronous operations in try-catch blocks.
   async function fetchData() {
     try {
       const response = await fetch('api/url');
       const data = await response.json();
       return data;
     } catch (error) {
       console.error('Error fetching data:', error);
     }
   }
  1. Edge Cases:
    • Always consider edge cases and validate inputs.
   function getUserAge(user) {
     if (!user || !user.age) {
       return 'Age not available';
     }
     return user.age;
   }
  1. Consistent Formatting:
    • Follow a consistent code formatting style (indentation, spacing, etc.). Use tools like Prettier to automate this.
   if (condition) {
     doSomething();
   } else {
     doSomethingElse();
   }

Code Organization

  1. Modularization:
    • Break down the code into small, reusable modules or functions.
   // utils.js
   export function calculateDiscount(price, discount) { ... }

   // main.js
   import { calculateDiscount } from './utils.js';
  1. Separation of Concerns:
    • Separate different concerns (e.g., UI logic, business logic, data handling) into different files or functions.
   // ui.js
   function updateUI(data) { ... }

   // data.js
   async function fetchData() { ... }

   // main.js
   import { updateUI } from './ui.js';
   import { fetchData } from './data.js';

Best Practices

  1. Use Strict Mode:
    • Always enable strict mode to catch common coding errors.
   'use strict';
  1. Use Constants:
    • Use constants for values that do not change.
   const MAX_USERS = 100;
  1. Avoid Global Variables:
    • Minimize the use of global variables to avoid conflicts and unintended behavior.
   // Good
   (function() {
     const localVariable = 'This is local';
   })();

   // Bad
   var globalVariable = 'This is global';
  1. Commenting and Documentation:
    • Write comments and documentation to explain the purpose and functionality of the code.
   /**
    * Calculates the total price after applying a discount.
    * @param {number} price - The original price.
    * @param {number} discount - The discount to apply.
    * @returns {number} - The total price after discount.
    */
   function calculateTotalPrice(price, discount) { ... }
  1. Use Promises and Async/Await with Error Handling:
    • Prefer using promises and async/await for asynchronous operations, and wrap them in try-catch blocks for error handling.
   // Good
   async function fetchData() {
     try {
       const response = await fetch('api/url');
       const data = await response.json();
       return data;
     } catch (error) {
       console.error('Error fetching data:', error);
     }
   }

   // Bad
   function fetchData(callback) {
     fetch('api/url')
       .then(response => response.json())
       .then(data => callback(data))
       .catch(error => console.error('Error fetching data:', error));
   }
  1. Object Destructuring:
    • Use object destructuring to extract multiple properties from an object in a concise way.
   // Good
   const vehicle = { make: 'Toyota', model: 'Camry' };
   const { make, model } = vehicle;

   // Bad
   const vehicleMake = vehicle.make;
   const vehicleModel = vehicle.model;

By following these standards, you can ensure that your JavaScript code is clean, maintainable, and efficient.

The above is the detailed content of General Coding Standards JavaScript.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn