JavaScript Coding Standards#

Reference#

Code Structure and Organization#

  1. File Organization - One concept per file - Clear, descriptive file names - Maximum ~400 lines per file

  2. Module Exports - Prefer named exports - Single responsibility principle - Clear import/export structure

// ❌ Bad
export default {
  helper1,
  helper2,
  someFunction
};

// ✅ Good
export const helper1 = () => {};
export const helper2 = () => {};

ES6+ Features#

  1. Modern Syntax - Use const/let, avoid var - Arrow functions for callbacks - Template literals for strings - Optional chaining and nullish coalescing

// ❌ Bad
var name = 'John';
function getUser() {
  return user != null ? user.name : 'Guest';
}

// ✅ Good
const name = 'John';
const getUser = () => user?.name ?? 'Guest';
  1. Destructuring & Spread - Use for object/array manipulation - Named parameters in functions - Immutable state updates

const { id, name } = user;
const newArray = [...oldArray, newItem];
const newObject = { ...oldObject, updated: true };

Function Usage#

  1. Function Style - Arrow functions for methods - Function declarations for components - Clear parameter naming

// ❌ Bad
function doSomething(x, y) {
  return x + y;
}

// ✅ Good
const calculateTotal = (price, tax) => {
  return price + tax;
};
  1. Pure Functions - Minimize side effects - Predictable returns - Immutable parameters

Error Handling#

  1. Try-Catch - Async/await with try-catch - Error boundaries in React - Custom error types

try {
  await apiCall();
} catch (error) {
  if (error instanceof NetworkError) {
    handleNetworkError(error);
  }
  throw error;
}
  1. Error Types - Descriptive error messages - Custom error classes - Proper error propagation

Linting and Formatting#

  1. ESLint Configuration

module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:react/recommended'
  ],
  rules: {
    'no-unused-vars': 'error',
    'no-console': 'warn'
  }
};
  1. Prettier Configuration

{
  "singleQuote": true,
  "trailingComma": "es5",
  "printWidth": 80,
  "tabWidth": 2
}

Testing#

  1. Unit Tests - Test pure functions - Clear test descriptions - Arrange-Act-Assert pattern

describe('calculateTotal', () => {
  it('should add tax to price', () => {
    // Arrange
    const price = 100;
    const tax = 20;

    // Act
    const total = calculateTotal(price, tax);

    // Assert
    expect(total).toBe(120);
  });
});
  1. Test Organization - Group related tests - Mock external dependencies - Test edge cases

  2. Coverage - Aim for meaningful coverage - Test critical paths - Integration tests for complex flows