This document outlines the coding standards and best practices we use for writing demos, sample code, code snippets, and so forth, for use on MDN.

The goal isn't to recommend one way of coding as being "the right way," because there are so many different technologies, practices, styles, tools, frameworks, and libraries to use, and different people have different favorites. Instead, this article presents a way that works; it's a single minimalist way that is predictable, transparent, and simple enough to not get in the way of learning the main aspects of web development that each demo (and associated article) is trying to teach.

The biggest advantage to adhering to these guidelines is that it will foster consistency across our samples and demos on MDN, which increases readability and comprehension overall.

Note: This article contains guidelines on actually writing code examples for using on or with MDN articles. If you want advice on the styling/formatting of code as it appears on an MDN article, see our Writing style guide.

General guidelines

This section provides quick general guidelines for creating an understandable minimal code sample to demonstrate usage of a specific feature or function.

Code samples need to be:

  • simple enough to be understandable, but
  • complex enough to do something interesting, and preferably useful.

There is one overarching consideration that you need to keep in mind:

Note: Readers will copy and paste the code sample into their own code, and may put it into production.

Therefore, you need to make sure that the code example is usable, and does not do anything that will cause an application to be insecure, grossly inefficient, or bloated. If the code example is not runnable or production-worthy, be sure to include a warning in a code comment and in the explanatory text — if it is a snippet and not a full example, make this clear. This also means that you should provide all of the information necessary to run the example including any dependencies and setup.

Code samples should be as self-contained and easy to understand as possible. The aim is not necessarily to produce efficient, clever code that impresses experts and has great functionality. More important is to produce reduced working examples that can be understood as quickly as possible, by as many people as possible, and plugged into their own examples with the minimum of fuss.

Here are a few links to some good examples of sample code on MDN: 

  • The sample should be short, and only show the feature you are immediately interested in.
  • Only include code that is essential for the example. A large amount of non-relevant code can easily distract or confuse the audience. If you want to provide a full example, put it in one of our Github repos (or a JSBin, Codepen, or similar) and then provide the link to the full version above or below the sample.
  • Don't include unnecessary server-side code and other such dependencies, as they make the code less portable, and harder to run.
  • Write your code as cleanly and understandably as possible, even if it is not the most efficient way to do it.
    • Include loose spacing, and write the code in an expanded form, so it is easy to see what everything is doing.
    • Include comments to explain anything complex or non-obvious
    • When writing JavaScript, don't use libraries/frameworks like jQuery, Ember, Angular, etc. You may love them, but it immediately increases the knowledge barrier required to understand the sample.
    • When writing CSS or HTML, use semantic names for classes. When writing JavaScript, also observe best practices such as lower camel case for variables.
    • When writing CSS, don't use a preprocessor language like Sass — use pure CSS.
  • Don't use bad practices for brevity (such as presentational elements like <big> or document.write()); do it correctly.
  • Make sure you use resources that you have the rights to use. Copyrighted images and videos, for example, could cause legal problems.
  • In the case of API demos, if you are using multiple APIs together point out what APIs are included, and what features come from where.
  • The main content column in MDN pages is quite narrow. Try to ensure that lines of code are short enough that they fit the column. If you don't do this, then the code block gets horizontal scrollbars, and the user has to scroll to see the whole line. Having said this, if it's a choice between long lines and bad-practice code, choose long lines.

Client-side web technologies

Client-side technologies are the core focus of what many of us do, and of most of the docs on MDN. The following guidelines are not hard and fast rules, but they make sense to us.

Note: You should of course comment all your code to make it as clear as possible how your app works, and what you are intending with each major section. There is no such thing as too many comments, as long as they are concise, clear comments, and you can always strip them out as part of your build process, before you deploy your app.


Here are some guidelines about writing HTML documents that make sense to us.


Unless you are working on some kind of CMS system where you don't get to choose such page fundamentals, you should use the HTML5 DOCTYPE. It is short, easy to remember, and backwards compatible:

<!DOCTYPE html>

See Introduction to HTML5 for further information.

Include a basic document structure

Include <html>, <head>, <body>, and static HTML for elements that don't need dynamic updating. It is tempting in this day and age to just generate everything with JavaScript, but this is bad for backwards compatibility and graceful degredation and just makes your browser work harder.

<!DOCTYPE html>

  <p>This is my content!</p>

Include a document language

In your <html> element, set a document language with the lang attribute:

<html lang="en-us">

This is good for accessibility and search engines, and helps with localizing content.

Define your document's character set

In HTML5, you can define a document's character set like so:

<meta charset="utf-8">

Use UTF-8 unless you have a very good reason not to; it will cover your character needs pretty much regardless of what language you are using in your document. In addition, you should always specify the character set as early as possible within your HTML's <head> block (within the first kilobyte), as it protects against a rather nasty Internet Explorer security vulnerability.

General element coding style

HTML5 permits usage of HTML and XHTML markup styles, so it is really up to you what you use. For readability and maximum compatibility, we tend to use a hybrid approach. Specifics are follows:

  • DO use lowercase for all element and attribute names, as it looks neater and means you can write markup out faster.
  • DON'T include trailing slashes for empty elements (e.g. <hr />), as they are unnecessary and slow things down. They can also break old browsers if you are not careful (although from what we can recall, this hasn't been a problem since Netscape 4).
  • DO put all attribute values in quotes. It is tempting to omit quotes since HTML5 allows this, but markup is easier to read if you do include them, and it can cause problems sometimes if you don't. For example, if you have a class attribute with two values in it such as class="important header", this can be misconstrued if the quotes were ommitted.
  • DON'T worry about writing out attributes in full, if the value is the same as the name. For example, required="required" is not really necessary; just required is perfectly understandable and works fine.

Add the viewport meta tag

Especially if you are creating an app-style experience, you will probably want to optimize your layout for viewing on different viewport sizes (and other differences in media features) using media queries. To make mobile browsers interpret media queries properly, you will need to include the viewport <meta> tag in your HTML <head>. You should include at least the following in your document, which can be modified later on as the need arises:

<meta name="viewport" content="width=device-width">

See Using the viewport meta tag to control layout on mobile browsers for further details.


Below are some CSS guidelines to make your code understandable and maintainable. In terms of efficient CSS code, you should read Writing efficient CSS.

Use expanded syntax

There are a variety of CSS writing styles you can use, but for development we prefer the expanded style, with the selector/opening brace, close brace, and each declaration on a separate line. This maximizes readability (and, again, promotes consistency on MDN):

p {
  color: white;
  background-color: black;
  padding: 10px;

Use "mobile first" media queries

When including different sets of styles for different target viewport sizes using media queries inside the same stylesheet, it is good idea to make the default styling before any media queries have been applied to the document the narrow screen/mobile styling, and then override this for wider viewports inside successive media queries.

/*Default CSS layout for narrow screens*/

@media (min-width: 480px) {
  /*CSS for medium width screens*/

@media (min-width: 800px) {
  /*CSS for wide screens*/

@media (min-width: 1100px) {
  /*CSS for really wide screens*/

This has many advantages, outlined in our Mobile First article.

We appreciate that this is not ideal for every situation. A number of people have issues with Mobile First media queries because older desktop browsers such as Internet Explorer 6-8 do not support media queries, therefore these would be served the mobile view, which would be no good. To mitigate this problem, we would also recommend conditionally applying a media query polyfill such as respond.js to your app, inside a conditional comment:

<!--[if le IE 9]>
  <script src="scripts/respond.js"></script>

Use flexible/relative units

For maximum flexibility over the widest possible range of devices, it is a good idea to size containers, padding, etc. using relative units like ems and rems, or percentages and viewport units if you want them to vary depending on viewport width. You can read some more about this in our Responsive design building blocks article.

Think carefully before using resets

For maximum control over CSS across platforms, a lot of people use CSS resets to remove every style, before then building things back up themselves. This certainly has its merits, but CSS resets can often be overkill, resulting in lots of extra time spent reimplementing things that weren't completely broken in the first place, like default margins, list styles, etc.

A more reasoned approach that we'd like to recommend you at least take a look at is normalize.css by Nicolas Gallagher, which aims to just make things more consistent across browsers, fix some default annoyances that we always get rid of (the margins on <html> and <body>, for example) and get rid of a few bugs.

Plan your CSS — avoid overriding

Before diving in and writing huge chunks of CSS, plan your styles carefully. What general styles are going to be needed, what different layouts do you need to create, what specific overrides need to be created, and are they reusable? Above all, you need to try to avoid too much overriding. If you keep finding yourself writing styles and then cancelling them again a few rulesets down, you probably need to rethink your strategy.


This current crop of JavaScript guidelines is taken from our Mozilla Coding Style page, which is dedicated more towards creating code specifically for Mozilla projects such as the Firefox browser. The two will probably diverge in the future.

  • Make sure you are aware of the JavaScript Tips.
  • Do not compare x == true or x == false. Use (x) or (!x) instead. x == true, in fact, is different from if (x)! Compare objects to null, numbers to 0 or strings to "" if there is chance for confusion.
  • Make sure that your code doesn't generate any strict JavaScript warnings, such as:
    • Duplicate variable declaration
    • Mixing return; with return value;
    • Undeclared variables or members. If you are unsure if an array value exists, compare the index to the array's length. If you are unsure if an object member exists, use "name" in aObject, or if you are expecting a particular type you may use typeof( == "function" (or whichever type you are expecting).
  • Use [value1, value2] to create a JavaScript array in preference to using new Array(value1, value2) which can be confusing, as new Array(length) will actually create a physically empty array with the given logical length, while [value] will always create a 1-element array. You cannot actually guarantee to be able to preallocate memory for an array.
  • Use { member: value, ... } to create a JavaScript object; a useful advantage over new Object() is the ability to create initial properties and use extended JavaScript syntax to define getters and setters.
  • If having defined a constructor you need to assign default properties, it is preferred that you assign an object literal to the prototype property.
  • Use regular expressions, but use them wisely. For instance, to check that aString is not completely whitespace use /\S/.test(aString); only use if you need to know the position of the result, or aString.match() if you need to collect matching substrings (delimited by parentheses in the regular expression). Regular expressions are less useful if the match is unknown in advance, or to extract substrings in known positions in the string. For instance, aString.slice(-1) returns the last letter in aString, or the empty string if aString is empty.

Shell prompts

A shell is a program that waits for you to type in a command and then press the return key. To indicate which commands you should type, MDN documentation lists them in a code block, similar to code examples. Such a block looks like this:

# This may take a while... 
hg clone firefox 
cd firefox

There are a some conventions when writing a shell code block:

  • Do not include a "$" or ">" at the beginning of a shell instruction. It confuses more than it helps and it is not useful when copying the instructions.
  • Comments start with "#".
  • Choose the "Bash" syntax highlighter.

Document Tags and Contributors

Last updated by: wbamberg,