Skip to content

Javascript Coding Standards

Adam Szablya edited this page Jun 2, 2024 · 1 revision

Metrolla has adopted Google's coding standards for Javascript

Google's JavaScript style guide outlines best practices and conventions for writing JavaScript code to ensure consistency, readability, and maintainability across projects. Here is a summary of the key points:

Google JavaScript Style Guide

1. General Principles

  • Clarity: Write clear and readable code.
  • Consistency: Follow the established coding conventions.
  • Simplicity: Prefer simple solutions and avoid unnecessary complexity.

2. Source Code Structure

  • File Names: Use lowercase_with_underscores.js for file names.
  • Line Length: Limit lines to 80 characters.
  • Indentation: Use 2 spaces per indentation level.

3. Comments

  • Comment Style:
    • Use // for single-line comments.
    • Use /* ... */ for multi-line comments.
  • Documentation Comments: Use JSDoc-style comments (/** ... */) for documenting APIs.
  • Function Comments: Place comments before function definitions to describe what the function does and its parameters.

4. Naming Conventions

  • Variable Names: Use camelCase for variable names.
  • Function Names: Use camelCase for function names.
  • Class Names: Use PascalCase for class names.
  • Constants: Use CONSTANT_CASE for constant values.

5. Variables

  • Declaration: Use const for constants and let for variables that need to be reassigned. Avoid using var.
  • Initialization: Initialize variables at the point of declaration if possible.
  • Scope: Minimize the scope of variables by declaring them in the smallest scope possible.

6. Functions

  • Arrow Functions: Prefer arrow functions for anonymous functions, especially for short callbacks.
  • Default Parameters: Use default parameters instead of modifying function arguments.
  • Rest Parameters: Use rest parameters (...args) for variadic functions.

7. Objects and Arrays

  • Object Literals: Use the shorthand syntax for properties when possible.
  • Destructuring: Use destructuring for accessing properties of objects and elements of arrays.
  • Spread Operator: Use the spread operator to copy objects and arrays.

8. Strings

  • Quotes: Use single quotes (') for strings. Use template literals (`) for strings that contain variables or multiline strings.
  • Concatenation: Prefer template literals over string concatenation.

9. Control Statements

  • Braces: Always use braces for control statements (if, for, while), even for single statements.
  • Switch Statements: Use default cases in switch statements and include break statements in each case.

10. Modules

  • Imports: Use import statements for importing modules.
  • Exports: Use export statements to export functions, objects, or primitives from a module.

11. Error Handling

  • Exceptions: Use try, catch, and finally for handling exceptions.
  • Error Objects: Use Error objects for throwing and catching errors.

12. Testing

  • Unit Tests: Write unit tests for all new code using frameworks like Jasmine or Mocha.
  • Test Coverage: Aim for high test coverage, but prioritize meaningful tests over achieving 100% coverage.

Example Code

Here is an example that illustrates some of these standards:

// utils.js

/**
 * Generates a random integer between min and max (inclusive).
 * @param {number} min - The minimum integer.
 * @param {number} max - The maximum integer.
 * @return {number} A random integer between min and max.
 */
export function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
// main.js
import { getRandomInt } from './utils.js';

/**
 * Updates the content of an HTML element with a random number.
 * @param {string} elementId - The ID of the HTML element.
 */
function updateRandomNumber(elementId) {
  const element = document.getElementById(elementId);
  if (!element) {
    throw new Error(`Element with ID ${elementId} not found.`);
  }

  const randomNumber = getRandomInt(1, 100);
  element.textContent = `Random number: ${randomNumber}`;
}

// Run the update function when the document is fully loaded
document.addEventListener('DOMContentLoaded', () => {
  updateRandomNumber('random-number');
});

For the most detailed and up-to-date information, refer to the full Google JavaScript Style Guide.

Clone this wiki locally