This guide outlines the recommended coding style and best practices for writing JavaScript code.
- General Guidelines
- Naming Conventions
- Spacing and Indentation
- Variables
- Functions
- Conditional Statements and Loops
- Error Handling
- Comments
- Modules
- Testing
- Use descriptive names for variables, functions, classes, and other identifiers.
- Keep functions short and focused on a single task.
- Avoid deep nesting of code blocks.
- Use proper error handling and avoid swallowing exceptions.
- Write self-explanatory code and avoid unnecessary comments.
- Follow the SOLID principles when designing classes and modules.
- Use camelCase for variables, functions, and object properties.
- Use PascalCase for classes and constructor functions.
- Use uppercase snake_case for constants and enum values.
- Use 2 spaces for indentation.
- Use spaces around operators and after commas.
- Place an opening brace on the same line as the statement or declaration.
- Use a space between the
ifkeyword and the opening parenthesis.
- Use
constfor variables that will not be reassigned, andletfor variables that will be reassigned. - Declare each variable on a separate line to improve readability.
- Initialize variables at the point of declaration whenever possible.
- Avoid global variables and minimize the scope of variables.
- Use function declarations or arrow function expressions for named functions.
- Use concise arrow function syntax (
() =>) for callbacks and anonymous functions. - Use meaningful and descriptive function names.
- Limit the number of function arguments to improve readability.
- Avoid unnecessary side effects in functions.
- Use strict equality (
===and!==) for comparisons. - Avoid unnecessary negations (
!) in conditions. - Use
for...ofloops for iterating over arrays and other iterable objects. - Prefer
for...ofoverfor...infor iterating over object keys. - Use
Array#forEachor higher-order array methods when appropriate.
- Use
try...catchblocks for catching and handling exceptions. - Avoid catching generic
Errorobjects unless necessary. - Always provide informative error messages when throwing exceptions.
- Use comments to explain complex algorithms, business rules, or any non-obvious code.
- Write self-explanatory code and avoid excessive comments.
- Remove commented-out code before committing changes.
- Use ES6 modules (
importandexport) for managing dependencies. - Avoid using the
importstatement without a correspondingexportstatement. - Prefer default exports for single exports and named exports for multiple exports.