# JavaScript Coding Standards and Best Practices

### Core Principles

* Write functions that are easy to read.
* Prefer clarity and consistency over personal style preferences.
* Keep each function focused on one responsibility.
* Use names that communicate intent without requiring extra explanation.
* Return values should be predictable and consistent.

***

### Function Naming

Naming is one of the most important contributors to maintainability. A reader should understand what a function does from its name alone.

* Use camelCase for all function names, for example: `calculateTotal`, `getUserData`, `validateInvoiceDate`.

* Use descriptive names that clearly communicate the function’s purpose.

* Use verbs for action-oriented functions, such as get, set, calculate, build, format, validate, send, or update.

* Use nouns for variables or values rather than actions, such as `fullName`, `userAge`, `totalAmount`, or `invoiceDate`.

* Keep prefixes consistent across the codebase. For example, use get for retrieval, is or has for boolean checks, and set or update for state changes.

#### Recommended naming patterns

| Category          | Pattern                | Examples                                        |
| ----------------- | ---------------------- | ----------------------------------------------- |
| Action            | verb + noun            | `calculateTotal`, `printReport`, `buildPayload` |
| Retrieval         | get + noun             | `getUserName`, `getCustomerRecord`              |
| Assignment/update | set/update + noun      | `setStatus`, `updateInvoiceNumber`              |
| Boolean check     | is/has/can + condition | `isValidDate`, `hasAccess`, `canApprove`        |
| Formatting        | format + noun          | `formatCurrency`, `formatDisplayName`           |

#### Example

```javascript
function calculateTotal(items) {
  var total = 0;

  for (var i = 0; i < items.length; i++) {
    total += items[i].amount;
  }

  return total;
}
```

***

### Readability and Formatting

Consistent formatting lowers cognitive load. The goal is to make structure visible at a glance.

* Use consistent indentation throughout the codebase. Use either 2 spaces or 4 spaces, but do not mix them in the same file or project.

* Place opening braces on the same line as the function definition, conditional statement, or loop.

* Leave a blank line between function definitions to visually separate logical units.

* Use spacing consistently around operators, after commas, and between control blocks where readability benefits.

* Avoid deeply nested logic where a guard clause or helper function would make the flow easier to follow.

#### Example

```javascript
function getUserName(user) {
  if (!user) {
    return "";
  }

  return user.firstName + " " + user.lastName;
}

function printReport(reportName) {
  console.log(reportName);
}
```

#### Writting Comments

Comments should explain intent, business rules, assumptions, or non-obvious decisions. Do not use comments to restate what the code already says clearly.

* Write comments in clear, direct language and keep them concise.

* Explain why the code exists, any important constraint, or the reason for an unusual implementation choice.

* Place a short comment above the line or block it describes when that improves readability.

* Keep comments updated when the code changes. Outdated comments are worse than no comments.

* Avoid obvious comments such as “increment i” or “set total to total plus amount” when the code already makes that clear.

#### Example&#x20;

```javascript
// Validate the order before calculating any totals.
function processOrder(order) {
    validateOrder(order);

    var subtotal = calculateSubtotal(order.items);
    var tax = calculateTax(subtotal);

    return buildOrderSummary(subtotal, tax);
}

// Route invoices above the finance threshold for manual review.
function assignApprovalStatus(invoice) {
    if (invoice.totalAmount > 10000) {
        return "Manual Review";
    }

    return "Auto Approved";
}

```

#### Example to Avoid

```javascript
function calculateTotal(items) {
    var total = 0; // declare total variable and assign 0 to it

    for (var i = 0; i < items.length; i++) { // loop through items array
        total += items[i].amount; // add current item amount into total variable
    }

    return total; // return the total value
}
```

#### If/else formatting

If/else statements should be formatted so that each branch is visually clear. Always use braces, even for single-line branches, to reduce mistakes during future edits.

#### Example&#x20;

```javascript
function getAccessMessage(isLoggedIn, hasPermission) {
    if (!isLoggedIn) {
        return "Please log in.";
    } else if (!hasPermission) {
        return "Access denied.";
    } else {
        return "Access granted.";
    }
}
```

#### Example to Avoid

```javascript
function getStatus(code) {
    if (code === 1) {
        return "Open";
    } else {
        if (code === 2) {
            return "Closed";
        } else {
            if (code === 3) {
                return "Pending";
            } else {
                return "Unknown";
            }
        }
    }
}
```

***

### Function Length and Responsibility

Each function should do one thing well. Large functions that validate input, transform data, update state, and perform output in one block are harder to test and maintain.

* Keep functions focused on a single responsibility.

* Break overly long functions into smaller reusable helper functions when the logic naturally separates into steps.

* Avoid combining unrelated concerns such as data retrieval, formatting, and UI output in one function unless the scope is intentionally small.

* Where possible, make helper functions reusable and independently understandable.

#### Example

```javascript
function processOrder(order) {
  validateOrder(order);

  var subtotal = calculateSubtotal(order.items);
  var tax = calculateTax(subtotal);

  return buildOrderSummary(subtotal, tax);
}
```

***

### Return Values

A function that is expected to return a value should do so explicitly and consistently. Mixed return types make calling code harder to reason about.

* Always explicitly return a value when one is expected.

* Avoid mixing return types. For example, do not return a string in one branch and an object in another.

* Where no meaningful value needs to be returned, return nothing rather than returning inconsistent placeholders.

* Keep the return contract clear so that other developers know what to expect from the function.

#### Example

```javascript
function getStatusLabel(statusCode) {
  if (statusCode === 1) {
    return "Open";
  }

  if (statusCode === 2) {
    return "Closed";
  }

  return "Unknown";
}
```

#### Example to Avoid

```javascript
function getStatusData(statusCode) {
  if (statusCode === 1) {
    return "Open";
  }

  if (statusCode === 2) {
    return { label: "Closed" };
  }

  return false;
}
```

***

### Additional Best Practices

* Keep parameter names descriptive and aligned with the function’s purpose.
* Prefer early returns for invalid conditions when they simplify control flow.
* Avoid hidden side effects unless the function name clearly implies them.
* Use helper functions to remove repeated logic instead of copying blocks across multiple functions.
* During code review, evaluate whether a function can be understood quickly without needing surrounding context.

#### Code Review Checklist

| Area           | What to Verify                                                                                 |
| -------------- | ---------------------------------------------------------------------------------------------- |
| Naming         | Function name uses camelCase, starts with a verb where appropriate, and clearly states intent. |
| Responsibility | Function performs one logical task and does not bundle unrelated behavior.                     |
| Formatting     | Indentation, brace placement, spacing, and blank lines are consistent.                         |
| Parameters     | Inputs are clearly named and only required parameters are included.                            |
| Return value   | Return type is explicit and consistent across all execution paths.                             |
| Readability    | Variable names are meaningful and control flow is easy to follow.                              |
| Reusability    | Repeated logic has been extracted into smaller helper functions where useful.                  |
