Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for General Coding Standards JavaScript.
Dharmendra Kumar
Dharmendra Kumar

Posted on

     

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.
// GoodconstuserAge=25;functioncalculateTotalPrice(items){...}// Badconsta=25;functioncalc(items){...}
Enter fullscreen modeExit fullscreen mode
  1. Consistent Naming Conventions:
    • Use camelCase for variables and functions.
    • Use PascalCase for class names.
constuserAge=25;functioncalculateTotalPrice(items){...}classUserProfile{...}
Enter fullscreen modeExit fullscreen mode
  1. Avoid Repetition:
    • Follow the DRY (Don't Repeat Yourself) principle by encapsulating repeated code into functions.
// GoodfunctioncalculateDiscount(price,discount){...}constprice1=calculateDiscount(100,10);constprice2=calculateDiscount(200,20);// Badconstprice1=100-10;constprice2=200-20;
Enter fullscreen modeExit fullscreen mode
  1. Error Handling:
    • Wrap API calls and other asynchronous operations in try-catch blocks.
asyncfunctionfetchData(){try{constresponse=awaitfetch('api/url');constdata=awaitresponse.json();returndata;}catch(error){console.error('Error fetching data:',error);}}
Enter fullscreen modeExit fullscreen mode
  1. Edge Cases:
    • Always consider edge cases and validate inputs.
functiongetUserAge(user){if(!user||!user.age){return'Age not available';}returnuser.age;}
Enter fullscreen modeExit 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 modeExit fullscreen mode

Code Organization

  1. Modularization:
    • Break down the code into small, reusable modules or functions.
// utils.jsexportfunctioncalculateDiscount(price,discount){...}// main.jsimport{calculateDiscount}from'./utils.js';
Enter fullscreen modeExit fullscreen mode
  1. Separation of Concerns:
    • Separate different concerns (e.g., UI logic, business logic, data handling) into different files or functions.
// ui.jsfunctionupdateUI(data){...}// data.jsasyncfunctionfetchData(){...}// main.jsimport{updateUI}from'./ui.js';import{fetchData}from'./data.js';
Enter fullscreen modeExit fullscreen mode

Best Practices

  1. Use Strict Mode:
    • Always enable strict mode to catch common coding errors.
'use strict';
Enter fullscreen modeExit fullscreen mode
  1. Use Constants:
    • Use constants for values that do not change.
constMAX_USERS=100;
Enter fullscreen modeExit fullscreen mode
  1. Avoid Global Variables:
    • Minimize the use of global variables to avoid conflicts and unintended behavior.
// Good(function(){constlocalVariable='This is local';})();// BadvarglobalVariable='This is global';
Enter fullscreen modeExit 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.    */functioncalculateTotalPrice(price,discount){...}
Enter fullscreen modeExit 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.
// GoodasyncfunctionfetchData(){try{constresponse=awaitfetch('api/url');constdata=awaitresponse.json();returndata;}catch(error){console.error('Error fetching data:',error);}}// BadfunctionfetchData(callback){fetch('api/url').then(response=>response.json()).then(data=>callback(data)).catch(error=>console.error('Error fetching data:',error));}
Enter fullscreen modeExit fullscreen mode
  1. Object Destructuring:
    • Use object destructuring to extract multiple properties from an object in a concise way.
// Goodconstvehicle={make:'Toyota',model:'Camry'};const{make,model}=vehicle;// BadconstvehicleMake=vehicle.make;constvehicleModel=vehicle.model;
Enter fullscreen modeExit fullscreen mode

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

⚡I’m a curious coder who loves building things! Whether it’s creating beautiful website designs or making sure the behind-the-scenes stuff runs smoothly, I’m all in. Let’s turn code into magic! ⚡
  • Location
    Bihar- Bettiah
  • Education
    BE
  • Work
    Software Engineer at Qualminds
  • Joined

More fromDharmendra Kumar

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp