General Coding Standards
-
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) { ... }
-
Consistent Naming Conventions:
- Use camelCase for variables and functions.
- Use PascalCase for class names.
const userAge = 25;
function calculateTotalPrice(items) { ... }
class UserProfile { ... }
-
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;
-
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);
}
}
-
Edge Cases:
- Always consider edge cases and validate inputs.
function getUserAge(user) {
if (!user || !user.age) {
return 'Age not available';
}
return user.age;
}
-
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
-
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';
-
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
-
Use Strict Mode:
- Always enable strict mode to catch common coding errors.
'use strict';
-
Use Constants:
- Use constants for values that do not change.
const MAX_USERS = 100;
-
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';
-
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) { ... }
-
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));
}
-
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.
Top comments (0)