JavaScript Best Practices

Learn industry standards and professional coding techniques

1Code Organization

Key Tips:

  • Keep functions small and focused on a single responsibility
  • Use meaningful variable and function names
  • Organize code into modules or components
  • Group related functionality together
  • Use comments for complex logic

Example:

// ✓ Good
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// ✗ Bad
function calc(x) {
  let t = 0;
  for (let i = 0; i < x.length; i++) {
    t = t + x[i].price;
  }
  return t;
}

2Error Handling

Key Tips:

  • Always handle errors with try-catch blocks
  • Provide meaningful error messages
  • Use proper error types
  • Log errors for debugging
  • Clean up resources in finally blocks

Example:

// ✓ Good
async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error('Failed to fetch:', error);
    throw error;
  }
}

3Performance Optimization

Key Tips:

  • Avoid unnecessary re-renders in React
  • Use debouncing and throttling for frequent events
  • Lazy load components and modules
  • Minimize bundle size
  • Cache expensive computations

Example:

// Debouncing example
function debounce(fn, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), delay);
  };
}

const handleSearch = debounce((query) => {
  console.log('Searching:', query);
}, 300);

4State Management

Key Tips:

  • Keep state as close to where it's needed as possible
  • Use useState for simple local state
  • Use useReducer for complex state logic
  • Consider Context API for global state
  • Avoid prop drilling

Example:

// ✓ Good - Local state
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

5Asynchronous Code

Key Tips:

  • Prefer async/await over .then() chains
  • Handle promise rejections properly
  • Use Promise.all for parallel operations
  • Avoid callback hell (callback pyramid)
  • Clean up subscriptions and timers

Example:

// ✓ Good - async/await
async function getUserData(userId) {
  try {
    const user = await fetchUser(userId);
    const posts = await fetchUserPosts(userId);
    return { user, posts };
  } catch (error) {
    console.error('Error:', error);
  }
}

6Testing Best Practices

Key Tips:

  • Test behavior, not implementation
  • Write tests before or alongside code (TDD)
  • Use descriptive test names
  • Test edge cases and error scenarios
  • Aim for 80%+ code coverage

Example:

// Jest example
describe('Calculator', () => {
  it('should add two numbers correctly', () => {
    expect(add(2, 3)).toBe(5);
  });

  it('should handle negative numbers', () => {
    expect(add(-2, 3)).toBe(1);
  });
});

7Security

Key Tips:

  • Sanitize user input to prevent XSS attacks
  • Use HTTPS for all communications
  • Never hardcode sensitive data
  • Validate data on both client and server
  • Use environment variables for secrets

Example:

// ✓ Good - Sanitize input
function createUserElement(username) {
  const div = document.createElement('div');
  div.textContent = username; // Safe - text content
  return div;
}

// ✗ Bad
function createUserElement(username) {
  const div = document.createElement('div');
  div.innerHTML = username; // Unsafe - XSS risk
  return div;
}

8Naming Conventions

Key Tips:

  • Use camelCase for variables and functions
  • Use PascalCase for classes and components
  • Use CONSTANT_CASE for constants
  • Avoid single letter variable names (except loops)
  • Use descriptive names that explain purpose

Example:

// ✓ Good naming
const MAX_ATTEMPTS = 3;
const isUserLoggedIn = true;

class UserAccount { }

function calculateTotalPrice(items) { }

// ✗ Bad naming
const a = 3;
const u = true;
function calc(x) { }

Want to Learn More?

Explore our comprehensive lessons and interactive projects to master these best practices in action.