Skip to content

JavaScript Style Guide

JavaScript Style Guide and Coding Conventions

Section titled “JavaScript Style Guide and Coding Conventions”

Adopting consistent coding conventions is crucial for writing readable, maintainable, and collaborative JavaScript code.

Coding conventions are a set of guidelines for the stylistic aspects of programming. They typically cover:

  • Naming and declaration rules for variables, functions, and classes.
  • Rules for the use of whitespace, indentation, and comments.
  • Best programming practices and principles.

Benefits of coding conventions:

  • Improved code readability and clarity.
  • Easier code maintenance and debugging.
  • Enhanced team collaboration and consistency.

These can be documented rules for teams (often enforced by linters like ESLint and formatters like Prettier) or your personal coding practice.

This page outlines common JavaScript coding conventions. Also, explore ‘Best Practices’ to avoid common pitfalls and write more robust code.

camelCase is the most common convention for naming variables and functions in JavaScript.

Names should start with a letter. They can also start with $ or _ (though _ often implies privacy by convention, it’s not enforced by the language).

Use const for variables that won’t be reassigned, and let for variables that will. Avoid var in modern JavaScript.

const firstName = "John";
const lastName = "Doe";
let price = 19.90;
const taxRate = 0.20; // Constants are often camelCase or UPPER_SNAKE_CASE
function calculateTotalPrice(price, tax) {
return price + (price * tax);
}
const fullPrice = calculateTotalPrice(price, taxRate);

For true constants (values that are fixed and widely used), UPPER_SNAKE_CASE is also a common convention (e.g., const MAX_USERS = 100;).

Always put spaces around operators (=, +, -, *, /, etc.) and after commas for better readability.

let x = y + z;
const values = ["Volvo", "Saab", "Fiat"];
for (let i = 0; i < 5; i++) {
// ...
}

Use consistent indentation for code blocks. 2 spaces or 4 spaces are common choices. This guide uses 4 spaces.

function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Do not use tabs for indentation, as different editors might interpret them differently. Configure your editor to insert spaces for tabs.

General rules for simple statements:

  • Always end simple statements with a semicolon. While JavaScript has Automatic Semicolon Insertion (ASI), explicit semicolons prevent ambiguity.
const items = ["Apple", "Banana", "Cherry"];
const user = {
firstName: "Jane",
lastName: "Doe",
age: 30,
email: "jane.doe@example.com"
};

General rules for complex (compound) statements (e.g., blocks for functions, loops, conditionals):

  • Put the opening curly brace { at the end of the first line.
  • Use one space before the opening brace.
  • Put the closing curly brace } on a new line, aligned with the beginning of the statement.
  • Do not end a complex statement block with a semicolon.
function greet(name) {
return `Hello, ${name}!`;
}
for (let i = 0; i < 5; i++) {
x += i;
}
if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

General rules for object literal definitions:

  • Place the opening brace on the same line as the object name (if assigned to a variable).
  • Use a colon plus one space between each property key and its value (e.g., key: value).
  • Use quotes around string property keys only if they are not valid identifiers (e.g., contain spaces or hyphens) or if consistency is desired. Modern JavaScript often omits quotes for valid identifier keys.
  • Use quotes around string values, not around numeric or boolean values.
  • Consider adding a trailing comma after the last property-value pair in multi-line objects. This makes version control diffs cleaner and adding new properties easier.
  • Place the closing brace on a new line, without leading spaces if it’s the end of a statement.
  • End an object assignment statement with a semicolon.
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue", // Trailing comma
};
// Shorter objects can be on one line
const point = { x: 10, y: 20 };

For readability, aim to keep lines shorter than 80-120 characters. Many teams set a limit (e.g., 100 characters) enforced by linters.

If a JavaScript statement doesn’t fit on one line, break it after an operator, comma, or opening parenthesis/brace.

document.getElementById("demo").innerHTML =
"Hello Dolly, this is a longer line that has been wrapped.";

Strive for consistency in your naming conventions:

  • Variable and function names: camelCase (e.g., myVariable, calculateValue).
  • Class names: PascalCase (also known as UpperCamelCase) (e.g., class UserAccount { ... }).
  • Constants (if you prefer this style for fixed values): UPPER_SNAKE_CASE (e.g., const API_KEY = "...";).
  • Private properties/methods (by convention, not enforced): Prefix with an underscore _ (e.g., _privateMethod()). Modern JavaScript has private class fields using # (e.g. #privateField).

Avoid hyphens in JavaScript identifiers, as they are interpreted as subtraction. Underscores are allowed but camelCase is more conventional for most JavaScript names.

Don’t start variable names with a $ sign unless you are working with a library that uses it by convention (like jQuery, historically). Modern JavaScript generally avoids this.

Use simple syntax for loading external scripts. The type="text/javascript" attribute is no longer necessary for <script> tags as JavaScript is the default.

<!-- Recommended: Place scripts at the end of the body for better perceived performance -->
<script src="myscript.js"></script>
<!-- Or use defer to ensure HTML parsing completes before script execution -->
<script src="anotherScript.js" defer></script>
<!-- Async loads script without blocking HTML parsing, executes as soon as ready -->
<script src="thirdScript.js" async></script>

Understand the async and defer attributes for optimizing script loading. defer is often preferred for scripts that need the full DOM.

When selecting HTML elements, use modern and efficient methods:

  • For a single element by ID: document.getElementById('myId')
  • For the first element matching a CSS selector: document.querySelector('.myClass') or document.querySelector('tag#id')
  • For all elements matching a CSS selector (returns a NodeList): document.querySelectorAll('p.article')

While older methods like getElementsByTagName and getElementsByClassName are still valid, querySelector and querySelectorAll offer more flexibility.

Using consistent naming conventions between your HTML (e.g., id="user-profile") and JavaScript (e.g., const userProfileElement = ...) can improve clarity.

Use standard file extensions:

  • HTML files: .html
  • CSS files: .css
  • JavaScript files: .js (or .mjs for ES modules in some contexts, .cjs for CommonJS)

Web servers can be case-sensitive (e.g., Apache, Nginx on Unix-like systems) or case-insensitive (e.g., IIS on Windows).

To avoid issues when deploying or moving projects between different server environments, always use lower-case file names (e.g., mainscript.js, styles.css, about-us.html). Using hyphens for separation is common.

Coding conventions primarily benefit human developers. Most stylistic rules (indentation, spacing) have negligible impact on raw execution performance for unminified code.

For development, readability is paramount. For production, JavaScript code should be minified to reduce file size and improve load times. Tools like Terser or Webpack’s built-in minification handle this.

Consider using linters (e.g., ESLint) and formatters (e.g., Prettier) to automatically enforce coding conventions and catch potential errors early.