Control Flow
Use early returns to reduce nesting - Handle edge cases first
const processUser = (user) => { if (!user) return null; if (!user.isActive) return null; return { id: user.id, name: user.name, }; };
Avoid nested ternary operators - Use if statements or early returns
const getUserDisplay = (user) => { if (!user.name) return 'Anonymous'; if (!user.isActive) return 'Inactive User'; return user.name; };
Use switch statements or lookup objects - Keep conditions flat
const getStatusColor = (status) => { switch (status) { case 'success': return 'green'; case 'warning': return 'yellow'; case 'error': return 'red'; default: return 'gray'; } }; // Or using a lookup object const statusColors = { success: 'green', warning: 'yellow', error: 'red', };
javascript const userName = user?.name; const userAddress = user?.address?.street;
Keep functions small and single-purpose - Extract complex logic into helper functions
const validateUser = (user) => { if (!isValidName(user.name)) return false; if (!isValidEmail(user.email)) return false; if (!isValidAge(user.age)) return false; return true; }; const isValidName = (name) => { return name.length >= 2 && /^[a-zA-Z\s]*$/.test(name); }; const isValidEmail = (email) => { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); }; const isValidAge = (age) => { return age >= 18 && age <= 120; };
javascript const isUserActive = user.status === 'active'; const hasRequiredPermissions = user.permissions.includes('admin'); const userDisplayName = user.name || 'Anonymous';
return (amount * daysLeft) / totalDays; }; ``` ## Error Handling ### Proper Error Handling - Use try-catch blocks appropriately - Provide meaningful error messages ```javascript const fetchUserData = async (userId) => { try { const response = await api.get(`/users/${userId}`); return response.data; } catch (error) { logger.error('Failed to fetch user data', { userId, error: error instanceof Error ? error.message : 'Unknown error', }); throw new UserFetchError('Failed to fetch user data'); } }; ``` ## Code Organization ### Logical Grouping - Group related code together - Maintain consistent organization ```javascript class UserService { // Properties private readonly api; private readonly logger; // Constructor constructor(api, logger) { this.api = api; this.logger = logger; } // Public methods public async getUser(id) { // Implementation } public async updateUser(user) { // Implementation } // Private helpers private validateUser(user) { // Implementation } } ```