JavaScript Coding Standards#
Reference#
MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript
Google Style Guides: https://google.github.io/styleguide/
Code Structure and Organization#
File Organization - One concept per file - Clear, descriptive file names - Maximum ~400 lines per file
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#
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';
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#
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;
};
Pure Functions - Minimize side effects - Predictable returns - Immutable parameters
Error Handling#
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;
}
Error Types - Descriptive error messages - Custom error classes - Proper error propagation
Linting and Formatting#
ESLint Configuration
module.exports = {
extends: [
'eslint:recommended',
'plugin:react/recommended'
],
rules: {
'no-unused-vars': 'error',
'no-console': 'warn'
}
};
Prettier Configuration
{
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80,
"tabWidth": 2
}
Testing#
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);
});
});
Test Organization - Group related tests - Mock external dependencies - Test edge cases
Coverage - Aim for meaningful coverage - Test critical paths - Integration tests for complex flows