Manual:Coding conventions/JavaScript

This page describes the coding conventions for JavaScript files of the MediaWiki codebase. See also the general conventions.

Linting
We use JSHint for code quality through static analysis. The settings for MediaWiki core can be found in. Please use an editor that supports inline linting in your editor (see platform support for JSHint).

You are recommended to have nodejs (with npm). Install node-jshint from the command line for automatic linting. node-jshint automatically discovers the closest .jshintrc file and uses it. Or http://jshint.com/ (may produce different results due to absence of jshintrc settings)

The  file is organised alphabetically and grouped as follows:

Projects can add additional enforcing options or relaxing options. However the following common options must be used in all projects:

To avoid confusion between an enforcing option and a relaxing option projects are encouraged to group them by category (see http://jshint.com/docs/ for an overview). For example  relaxes by allowing   in addition to , whereas   is a restriction to not allow trailing whitespace.

Look at the JSHint configuration for MediaWiki core or that of VisualEditor for good examples. Your extension should have its own  file to avoid relying on whatever the closest jshintrc file is in the local installation (because if that other file changes, it would instantly invalidate your code from that point on, thus causing inability to merge new changes until it is fixed).

Whitespace

 * Blank lines separate one block of logically related code from another.
 * One space on both sides of binary operators and assignment operators.
 * Keywords followed by a " " (left parenthesis) must be separated by one space. This gives visual distinction between keywords and function invocations.
 * There should be no space between the function name and left parenthesis of the argument list.
 * Don't use operators as if they are functions (such as,  ,  ,  ,  , ..).

Closure
Avoid leakage of variables from or to other modules by wrapping files in a closure. Use the following closure (aka "Immediately-Invoked Function Expression", or iffy):

Files that don't reference MediaWiki modules (e.g. a jQuery plugin) should omit the  and   arguments from the closure. JavaScript closures are explained here.

Declarations
All variables must be declared before used. JavaScript does not require this, but doing so makes the code easier to read and prevents common mistakes (such as implied globals).

All functions should be declared before they are used. Inner functions should follow the  statement.

Indentation
Indent blocks from their containing blocks with one tab (usually represented with 4 spaces).

Line length
Lines should wrap at no more than 80-100 characters. When a statement does not fit on a single line, it may be necessary to span the statement over multiple lines. Place the line break after an operator (ideally after a comma). A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion. The next line should be indented an extra level.

Comments
Please be generous with comments in your code, as they help future readers of the code (possibly yourself).

In older versions of MediaWiki, JavaScript code was often very poorly commented to keep it small. Since MediaWiki 1.17 and higher modules are automatically minified by ResourceLoader.

Generally use (single or multi-line).

Save for documentation blocks and for commenting out code.

Equality

 * Strict equality checks should be used in favor of loose  wherever possible.
 * No Yoda conditionals

Type checks
The below is the result of a long history of browser compatibility, edge cases, performance and other research. Don't take it lightly. There is a reason behind every single detail.


 * string:
 * number:
 * boolean:
 * null:
 * object:
 * Plain Object:
 * Function:
 * Array:
 * HTMLElement:
 * undefined:
 * Local variables:
 * Properties:
 * Global variables:

Quotes
Single quotes are preferred over double quotes for string literals.

Globals
Only  and   should be used (in addition to the browser's API).

Any and all code should be written as an extension to either of these. General purpose (not MediaWiki-specific) modules that manipulate DOM elements should be written as a jQuery plugin. And MediaWiki core or extension modules should extend the global  object.

If code is made available standalone and/or provided by a third party that exposes itself as a global, then (for use in MediaWiki context) alias or instantiate it into a property of  and use it from there.

For backward compatibility, MediaWiki exposes lots of -prefixed variables in the global scope (that is, if  is enabled). These are deprecated and will be removed at some point, so don't rely on this but use  instead.

Naming
All variables and functions must use lowerCamelCase for their naming. For functions, verb phrases are preferred (so instead of ).

The only exception to this are constructor functions used with the  operator. These names must start with a capital letter. JavaScript has no dedicated syntax for classes or constructors, they are declared as any other function. As such there is no compile-time or run-time warning for instantiating a regular function or omitting the  operator on a constructor. This naming convention is the only defense we have.

Names with acronyms in them should treat the acronym as a normal word and only uppercase the first letter. For example " " as opposed to " ".

jQuery

 * See also jQuery

To avoid confusion with raw elements or other variables, we prefix variables storing an instance of jQuery with a dollar sign, e.g., to make them easy to recognize. This matters because the DOM API (e.g. ) returns null if no element matched the query, therefore (since null casts to boolean false) one would test the plain variable, in the example. jQuery objects on the other hand (like any object in JavaScript) cast to boolean true, so if you confuse a jQuery object with the return value of a DOM method, a conditional could fail badly. In the example one would use  instead.

Creating elements
To create a plain element, use the simple  syntax in the jQuery constructor:

When creating elements based on the tag name from a variable (which may contain arbitrary html):

Only use when you need to parse HTML (as opposed to creating a plain element).

Collections
Different types of collections sometimes look similar but have different behaviour and should be treated as such. This confusion is mostly caused by the fact that arrays in javascript look a lot like arrays in other languages, but are in fact just an extension of Object. We use the following conventions:

Avoid using a  loop to iterate over an array (as opposed to a plain object). A  will iterate over the keys instead of over the indices:
 * keys are strings
 * order not guaranteed
 * index can have gaps
 * might include non-numerical properties

Pitfalls

 * Bracket notation on a string doesn't work in older versions of IE. Use   instead.
 * Be careful to preserve compatibility with left-to-right and right-to-left languages (ie.  or  ), especially when styling text containers. This is another reason why such declarations should be in CSS files, so that they are automagically flipped by CSSJanus in ResourceLoader for RTL-languages.
 * Use and  appropriately. Read more at http://javascript.info/tutorial/attributes-and-custom-properties
 * Always quote attribute selector values:  instead of   (jqbug-8229).
 * As of jQuery 1.4 the jQuery constructor has a new feature that allows passing an object as second argument, like . Don't use this. It makes code harder to follow, fails on attributes (such as 'size') that are also methods, and is unstable due to this mixing of jQuery methods with element attributes.  A future jQuery method or plugin or called "title" might convert an element into a heading, which means the title attribute can also no longer be set through this method. Be explicit and call ,  ,   etc. directly.

Documentation
Wikimedia projects have begun using JSDuck to build documentation from JavaScript comments (see https://doc.wikimedia.org/). The documentation comment structure for JavaScript is broadly similar to the doxygen format we use for PHP comments but many details differ to accomodate for certain javascript specific language constructs (such as object inheritance, emitting events and arbitrary augmentation of the prototype of an existing class).


 * Installation: Requires Ruby and the Ruby  package manager) Exec: gem install jsduck See also the JSDuck readme.


 * Generate documentation: jsduck --config=path/to/jsduck-json-file


 * Set up configuration for new projects: Create a JSDuck configuration file (in  or   depending on whether you have more JSDuck files (such as ,  ,   etc.). See for example,  and.

Usage

 * Tags
 * Types

Text in free-form blocks (e.g. description of methods, parameters, return values etc.) should be sentence case. If inside a tag when such a description wraps to a newline, indent with one extra space. Separate types with a bar :

Final notes
Use CSS for styling many elements

Don't apply styling to lots of elements at once; this has poor performance. Instead use a common parent's class (or add one) and apply CSS in a .css file. Thanks to ResourceLoader, this will all be loaded in the same HTTP request, so there's no performance penalty for having a separate CSS file. Do not set CSS into inline "style" attributes, don't insert "style" elements from JS either.

Environment There are a few things that MediaWiki specifically (or inherently due to use of jQuery), does not support:
 * jQuery doesn't support environments that have manipulated the  as it's considered harmful.
 * Both MediaWiki and jQuery do not support environments that have manipulated the global  variable as it's considered harmful. As of ECMAScript5 this is no longer an issue since it is made read-only (as it should be), but in older browsers this can cause issues.