0% found this document useful (0 votes)
2 views5 pages

JavaScript Coding Standards

This document outlines JavaScript coding standards based on Airbnb and Google conventions, emphasizing consistent style and quality across projects. It covers naming conventions, formatting, variable declarations, functions, error handling, module structure, testing standards, security considerations, common pitfalls, tooling, automation, version control, and code review practices. The guidelines aim to ensure maintainable and readable code while minimizing errors and enhancing collaboration among developers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

JavaScript Coding Standards

This document outlines JavaScript coding standards based on Airbnb and Google conventions, emphasizing consistent style and quality across projects. It covers naming conventions, formatting, variable declarations, functions, error handling, module structure, testing standards, security considerations, common pitfalls, tooling, automation, version control, and code review practices. The guidelines aim to ensure maintainable and readable code while minimizing errors and enhancing collaboration among developers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript Coding Standards

A comprehensive style and quality guide based on Airbnb / Google JavaScript


conventions

1. Purpose and Scope


This document defines a consistent set of conventions for writing JavaScript (and by extension
TypeScript) across projects and teams. JavaScript's flexibility makes consistent style especially
important — without agreed conventions, codebases quickly become a mix of incompatible patterns.
These guidelines draw on the most widely adopted community style guides, including Airbnb's and
Google's JavaScript style guides, along with common tooling defaults (ESLint, Prettier).

2. Naming Conventions
Element Convention

Variables / functions camelCase (e.g., userCount, getData())

Classes / Components PascalCase (e.g., UserProfile)

Constants UPPER_SNAKE_CASE for true constants (e.g., MAX_RETRIES)

Private class fields leading underscore or # private fields (e.g., #token)

Files kebab-case or camelCase depending on team convention

Boolean variables prefixed with is/has/can (e.g., isLoading, hasError)

3. Formatting
• Use 2-space indentation (the most common community standard).

• Always use semicolons to terminate statements to avoid automatic-semicolon-insertion pitfalls.

• Prefer single quotes for strings unless interpolation is needed (then use template literals).

• Limit line length to roughly 80–100 characters.

• Use a formatter like Prettier to enforce formatting automatically and remove style debates from
review.

• Use trailing commas in multi-line arrays and objects to keep diffs clean.

4. Variable Declarations
const maxRetries = 3; // use const by default
let attempts = 0; // use let only when reassignment is needed

// avoid var entirely — it has function scope and hoisting pitfalls

5. Functions
• Prefer arrow functions for callbacks and short functions; they also avoid `this`-binding surprises.

• Use default parameters instead of manual undefined checks inside the function body.

• Keep functions small and focused on a single responsibility — extract helpers for complex logic.

• Use async/await over raw Promise chains for readability and easier error handling.

• Avoid deeply nested callbacks ("callback hell"); prefer Promises or async/await.

5.1 Example
const fetchUser = async (id) => {

const response = await fetch(`/api/users/${id}`);

if (![Link]) {

throw new Error('User not found');

return [Link]();

};
6. Error Handling
• Never leave empty catch blocks — at minimum, log the error.

• Use try/catch around await calls that can fail, or handle rejection explicitly with .catch().

• Create custom Error subclasses for domain-specific error types when it aids debugging.

• Surface actionable error messages to calling code; avoid swallowing errors silently.

• Validate function inputs early and throw/return clear errors rather than letting bad data propagate.

7. Modules and Structure


• Use ES modules (import/export) rather than CommonJS (require) in new code where the
environment supports it.

• One default export per file is common for components; use named exports for utility functions.

• Avoid circular dependencies between modules.

• Group related files (component, styles, tests) together in feature-based folders rather than by file
type alone.

8. Testing Standards
• Use Jest, Vitest, or an equivalent test runner as the project standard.

• Name test files consistently, e.g., [Link] or [Link].

• Write unit tests for pure logic and integration/component tests for UI behavior.

• Mock network calls and timers in unit tests to keep them fast and deterministic.

• Avoid testing implementation details; test observable behavior instead.

9. Security Considerations
• Never insert unsanitized user input into the DOM via innerHTML; use safe APIs or a framework's
built-in escaping.

• Avoid eval() and the Function constructor on untrusted input.

• Store sensitive tokens outside of client-accessible storage where possible; be cautious with
localStorage.

• Validate and sanitize data on the server even if client-side validation also exists.

• Keep dependencies updated and audit them regularly (npm audit or equivalent).
10. Common Pitfalls
• Using == instead of === leads to confusing type coercion bugs.

• Forgetting that array and object methods like map/filter return new values rather than mutating in
place (except a few like sort, splice).

• Relying on var inside loops with closures captures the wrong variable value.

• Not handling Promise rejections, leading to unhandled rejection warnings or crashes.

• Mutating props or state directly in frameworks like React instead of using the provided update
mechanisms.

11. Tooling and Automation


• Use ESLint with a shared config (Airbnb, Standard, or Google) to catch style and correctness
issues.

• Use Prettier for automatic formatting, integrated with ESLint via eslint-config-prettier.

• Enable pre-commit hooks (e.g., via husky and lint-staged) so linting runs before code is committed.

• Run the full lint and test suite in CI on every pull request.

12. Version Control and Code Review


• Write descriptive commit messages following a consistent convention (e.g., Conventional
Commits).

• Keep pull requests focused and reasonably small to make review manageable.

• Require at least one review and a passing CI run before merging to the main branch.

• Reviewers should flag both correctness issues and deviations from these style conventions.

13. Summary Checklist


• Consistent camelCase / PascalCase naming.

• Formatted with Prettier, linted with ESLint.

• const/let used appropriately; var avoided.

• Errors handled explicitly, no empty catch blocks.

• Tests written for new logic and passing in CI.

• No sensitive data exposed in client-side code.


Compiled as an original summary of widely-followed community and vendor style guidelines, for internal reference use.

You might also like