The foundational principles that guide all JavaScript development decisions.
Prettier eliminates debates about code formatting and ensures consistency across the entire codebase.
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"printWidth": 100,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "avoid"
} Beyond automatic formatting, follow consistent patterns for better code readability and maintenance.
// ✅ Good naming conventions
const userAge = 25;
const MAX_RETRY_COUNT = 3;
class UserService {
constructor() {}
async fetchUserProfile(userId) {
return await this.apiClient.get(`/users/${userId}`);
}
}
// ❌ Poor naming conventions
const a = 25; // What does 'a' represent?
const max_retry = 3; // Inconsistent naming style
class userservice {} // Should be PascalCase
function getUserProfile() {} // Fine, but fetchUserProfile is more descriptive // ✅ Well-organized imports
// Third-party libraries first
import axios from 'axios';
import { format, addDays } from 'date-fns';
// Internal modules
import { UserService } from './services/UserService';
import { validateEmail } from './utils/validation';
import { API_ENDPOINTS } from './constants/api';
// Components (if using a framework)
import Header from './components/Header';
import Footer from './components/Footer'; Write code that is easy to read, understand, and maintain by following these quality principles.
// ✅ Self-documenting approach
class OrderProcessor {
processOrder(order) {
if (this.isOrderValid(order)) {
this.calculateTotals(order);
this.applyDiscounts(order);
this.sendConfirmationEmail(order);
}
}
isOrderValid(order) {
return order.items.length > 0 && order.customer.email;
}
calculateTotals(order) {
order.subtotal = order.items.reduce((sum, item) => sum + item.price, 0);
order.tax = order.subtotal * 0.08;
order.total = order.subtotal + order.tax;
}
}
// ❌ Less clear approach
class OrderProcessor {
process(o) {
// Check if order is valid
if (o.items.length > 0 && o.customer.email) {
// Calculate subtotal
let st = 0;
for (let i = 0; i < o.items.length; i++) {
st += o.items[i].price;
}
o.subtotal = st;
// Add tax and total
o.tax = st * 0.08;
o.total = st + o.tax;
// Send email
this.sendEmail(o);
}
}
} // ✅ Proper error handling
async function fetchUserData(userId) {
try {
const response = await apiClient.get(`/users/${userId}`);
return response.data;
} catch (error) {
if (error.response?.status === 404) {
throw new Error(`User with ID ${userId} not found`);
}
throw new Error(`Failed to fetch user data: ${error.message}`);
}
}
// ✅ Input validation with clear error messages
function calculateBMI(weight, height) {
if (typeof weight !== 'number' || weight <= 0) {
throw new Error('Weight must be a positive number');
}
if (typeof height !== 'number' || height <= 0) {
throw new Error('Height must be a positive number');
}
return weight / (height * height);
}
// ❌ Poor error handling
async function fetchUserData(userId) {
try {
const response = await apiClient.get(`/users/${userId}`);
return response.data;
} catch (error) {
// Silent failure - bad!
return null;
}
}