Sign In Create Account
Core Principles

JavaScript Core Principles

The foundational principles that guide all JavaScript development decisions.

Use Prettier for Consistent Code Formatting

Prettier eliminates debates about code formatting and ensures consistency across the entire codebase.

  • • 2 spaces for indentation (not tabs)
  • • 100 character line width
  • • Prefer single quotes over double quotes
  • • Automatic semicolon insertion handling
  • • Trailing commas for cleaner diffs

Prettier Configuration Example

{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "printWidth": 100,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "arrowParens": "avoid"
}

Why Prettier?

  • Consistency: Same formatting across all team members
  • No Debates: Eliminates formatting discussions in code reviews
  • Focus on Logic: Developers can focus on functionality, not formatting
  • IDE Integration: Formats on save automatically

Consistent Code Style

Beyond automatic formatting, follow consistent patterns for better code readability and maintenance.

Naming Conventions

  • • Use camelCase for variables and functions
  • • Use PascalCase for classes and constructors
  • • Use UPPER_SNAKE_CASE for constants
  • • Use descriptive names that explain intent

Naming Examples

// ✅ 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

File Organization

  • • One class per file (when using classes)
  • • Group related functions in modules
  • • Use meaningful file names that reflect contents
  • • Organize imports at the top of files

Import Organization

// ✅ 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';

Code Quality Principles

Write code that is easy to read, understand, and maintain by following these quality principles.

Write Self-Documenting Code

  • • Choose descriptive function and variable names
  • • Break complex operations into smaller functions
  • • Use comments only when code can't be made clearer
  • • Prefer explicit over implicit behavior

Self-Documenting Code Example

// ✅ 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);
    }
  }
}

Handle Errors Gracefully

  • • Use try/catch blocks for error handling
  • • Provide meaningful error messages
  • • Fail fast when appropriate
  • • Don't ignore errors silently

Error Handling Examples

// ✅ 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;
  }
}