docs.rodeo

MDN Web Docs mirror

Guidelines for writing JavaScript code examples

The following guidelines cover writing JavaScript example code for MDN Web Docs. This article is a list of rules for writing concise examples that will be understandable by as many people as possible.

General guidelines for JavaScript code examples

This section explains the general guidelines to keep in mind while writing JavaScript code examples. The later sections will cover more specific details.

Choosing a format

Opinions on correct indentation, whitespace, and line lengths have always been controversial. Discussions on these topics are a distraction from creating and maintaining content.

On MDN Web Docs, we use Prettier as a code formatter to keep the code style consistent (and to avoid off-topic discussions). You can consult our configuration file to learn about the current rules, and read the Prettier documentation.

Prettier formats all the code and keeps the style consistent. Nevertheless, there are a few additional rules that you need to follow.

Using modern JavaScript features

You can use new features once every major browser — Chrome, Edge, Firefox, and Safari — supports them.

Arrays

Array creation

For creating arrays, use literals and not constructors.

Create arrays like this:

const visitedCities = [];

Don’t do this while creating arrays:

const visitedCities = new Array(length);

Item addition

When adding items to an array, use push() and not direct assignment. Consider the following array:

const pets = [];

Add items to the array like this:

pets.push("cat");

Don’t add items to the array like this:

pets[pets.length] = "cat";

Asynchronous methods

Writing asynchronous code improves performance and should be used when possible. In particular, you can use:

When both techniques are possible, we prefer using the simpler async/await syntax. Unfortunately, you can’t use await at the top level unless you are in an ECMAScript module. CommonJS modules used by Node.js are not ES modules. If your example is intended to be used everywhere, avoid top-level await.

Comments

Comments are critical to writing good code examples. They clarify the intent of the code and help developers understand it. Pay special attention to them.

Use single-line comments

Single-line comments are marked with //, as opposed to block comments enclosed between /* … */.

In general, use single-line comments to comment code. Writers must mark each line of the comment with //, so that it’s easier to notice commented-out code visually. In addition, this convention allows to comment out sections of code using /* … */ while debugging.

Output of logs

Multi-line comments

Short comments are usually better, so try to keep them in one line of 60–80 characters. If this is not possible, use // at the beginning of each line:

// This is an example of a multi-line comment.
// The imaginary function that follows has some unusual
// limitations that I want to call out.
// Limitation 1
// Limitation 2

Don’t use /* … */:

/* This is an example of a multi-line comment.
  The imaginary function that follows has some unusual
  limitations that I want to call out.
  Limitation 1
  Limitation 2 */

Use comments to mark ellipsis

Skipping redundant code using ellipses (…) is necessary to keep examples short. Still, writers should do it thoughtfully as developers frequently copy & paste examples into their code, and all of our code samples should be valid JavaScript.

In JavaScript, you should put the ellipses () in a comment. When possible, indicate what action somebody reusing this snippet is expected to add.

Using a comment for the ellipses (…) is more explicit, preventing errors when a developer copies and pastes a sample code. Write:

function exampleFunc() {
  // Add your code here
  // …
}

Don’t use ellipses (…) like this:

function exampleFunc() {
  …
}

Comment out parameters

When writing code, you usually omit parameters you don’t need. But in some code examples, you want to demonstrate that you didn’t use some possible parameters.

To do so, use /* … */ in the parameter list. This is an exception to the rule to only use single-line comments (//).

array.forEach((value /* , index, array */) => {
  // …
});

Functions

Function names

For function names, use {{Glossary("camel_case", "camel case")}} , starting with a lowercase character. Use concise, human-readable, and semantic names where appropriate.

The following is a correct example of a function name:

function sayHello() {
  console.log("Hello!");
}

Don’t use function names like these:

function SayHello() {
  console.log("Hello!");
}

function doIt() {
  console.log("Hello!");
}

Function declarations

Loops and conditional statements

Loop initialization

When loops are required, choose the appropriate one from for(;;), for...of, while, etc.

[!WARNING] Never use for...in with arrays and strings.

[!NOTE] Consider not using a for loop at all. If you are using an Array (or a String for some operations), consider using more semantic iteration methods instead, like map(), every(), findIndex(), find(), includes(), and many more.

Control statements

There is one notable case to keep in mind for the if...else control statements. If the if statement ends with a return, do not add an else statement.

Continue right after the if statement. Write:

if (test) {
  // Perform something if test is true
  // …
  return;
}

// Perform something if test is false
// …

Do not write:

if (test) {
  // Perform something if test is true
  // …
  return;
} else {
  // Perform something if test is false
  // …
}

Use braces with control flow statements and loops

While control flow statements like if, for, and while don’t require the use of braces when the content is made of one single statement, you should always use braces. Write:

for (const car of storedCars) {
  car.paint("red");
}

Don’t write:

for (const car of storedCars) car.paint("red");

This prevent forgetting to add the braces when adding more statements.

Switch statements

Switch statements can be a little tricky.

Error handling

[!NOTE] Keep in mind that only recoverable errors should be caught and handled. All non-recoverable errors should be let through and bubble up the call stack.

Objects

Object names

Object creation

For creating general objects (i.e., when classes are not involved), use literals and not constructors.

For example, do this:

const object = {};

Don’t create a general object like this:

const object = new Object();

Object classes

Methods

To define methods, use the method definition syntax:

const obj = {
  foo() {
    // …
  },
  bar() {
    // …
  },
};

Instead of:

const obj = {
  foo: function () {
    // …
  },
  bar: function () {
    // …
  },
};

Object properties

Operators

This section lists our recommendations of which operators to use and when.

Conditional operators

When you want to store to a variable a literal value depending on a condition, use a conditional (ternary) operator instead of an if...else statement. This rule also applies when returning a value. Write:

const x = condition ? 1 : 2;

Do not write:

let x;
if (condition) {
  x = 1;
} else {
  x = 2;
}

The conditional operator is helpful when creating strings to log information. In such cases, using a regular if...else statement leads to long blocks of code for a side operation like logging, obfuscating the central point of the example.

Strict equality operator

Prefer the strict equality (triple equals) and inequality operators over the loose equality (double equals) and inequality operators.

Use the strict equality and inequality operators like this:

name === "Shilpa";
age !== 25;

Don’t use the loose equality and inequality operators, as shown below:

name == "Shilpa";
age != 25;

If you need to use == or !=, remember that == null is the only acceptable case. As TypeScript will fail on all other cases, we don’t want to have them in our example code. Consider adding a comment to explain why you need it.

Shortcuts for boolean tests

Prefer shortcuts for boolean tests. For example, use if (x) and if (!x), not if (x === true) and if (x === false), unless different kinds of truthy or falsy values are handled differently.

Strings

String literals can be enclosed within single quotes, as in 'A string', or within double quotes, as in "A string". Don’t worry about which one to use; Prettier keeps it consistent.

Template literals

For inserting values into strings, use template literals.

Variables

Variable names

Good variable names are essential to understanding code.

[!NOTE] The only place where it’s allowed not to use human-readable, semantic names is where a very commonly recognized convention exists, such as using i and j for loop iterators.

Variable declarations

When declaring variables and constants, use the let and const keywords, not var. The following examples show what’s recommended and what’s not on MDN Web Docs:

Type coercion

Avoid implicit type coercions. In particular, avoid +val to force a value to a number and "" + val to force it to a string. Use Number() and String(), without new, instead. Write:

class Person {
  #name;
  #birthYear;

  constructor(name, year) {
    this.#name = String(name);
    this.#birthYear = Number(year);
  }
}

Don’t write:

class Person {
  #name;
  #birthYear;

  constructor(name, year) {
    this.#name = "" + name;
    this.#birthYear = +year;
  }
}

Web APIs to avoid

In addition to these JavaScript language features, we recommend a few guidelines related to Web APIs to keep in mind.

Avoid browser prefixes

If all major browsers (Chrome, Edge, Firefox, and Safari) support a feature, don’t prefix the feature. Write:

const context = new AudioContext();

Avoid the added complexity of prefixes. Don’t write:

const AudioContext = window.AudioContext || window.webkitAudioContext;
const context = new AudioContext();

The same rule applies to CSS prefixes.

Avoid deprecated APIs

When a method, a property, or a whole interface is deprecated, do not use it (outside its documentation). Instead, use the modern API.

Here is a non-exhaustive list of Web APIs to avoid and what to replace them with:

Use safe and reliable APIs

Use the appropriate log method

See also

JavaScript language reference - browse through our JavaScript reference pages to check out some good, concise, meaningful JavaScript snippets.

In this article

View on MDN