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) { ... }
Enter fullscreen mode Exit fullscreen mode
  1. Consistent Naming Conventions:

    • Use camelCase for variables and functions.
    • Use PascalCase for class names.
 const userAge = 25; function calculateTotalPrice(items) { ... } class UserProfile { ... }
Enter fullscreen mode Exit fullscreen mode
  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;
Enter fullscreen mode Exit fullscreen mode
  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); } }
Enter fullscreen mode Exit fullscreen mode
  1. Edge Cases:

    • Always consider edge cases and validate inputs.
 function getUserAge(user) { if (!user || !user.age) { return 'Age not available'; } return user.age; }
Enter fullscreen mode Exit fullscreen mode
  1. Consistent Formatting:

    • Follow a consistent code formatting style (indentation, spacing, etc.). Use tools like Prettier to automate this.
 if (condition) { doSomething(); } else { doSomethingElse(); }
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode
  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';
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Use Strict Mode:

    • Always enable strict mode to catch common coding errors.
 'use strict';
Enter fullscreen mode Exit fullscreen mode
  1. Use Constants:

    • Use constants for values that do not change.
 const MAX_USERS = 100;
Enter fullscreen mode Exit fullscreen mode
  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';
Enter fullscreen mode Exit fullscreen mode
  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) { ... }
Enter fullscreen mode Exit fullscreen mode
  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)); }
Enter fullscreen mode Exit fullscreen mode
  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;
Enter fullscreen mode Exit fullscreen mode

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


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Free & easy ad network.