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 .jshintrc. 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)

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.
 * There should be no space between the function name and left parenthesis of the argument list. This gives visual distinction between keywords and function invocations.
 * 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).

The  statement should be the first statement in the function body.

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
There is a long history of browser compatibility, performance and other research left out here. The result is below is the status quo of how types should be checked.


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

Quotes
Single quotes are preferred over double quotes for literal strings.

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 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 symbol. This makes it easy to recognize and manipulate them even if origin of a variable is less obvious. The DOM API (e.g. ) returns null if no element matched the ID, therefore (since null casts to boolean false) it is used plain in an if statement. jQuery objects on the other hand (as any object in JavaScript) cast to boolean true. If a jQuery object is confused for the return value of a DOM method, a conditional could fail badly. In the exampe scenario one would use  instead.

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

and also work. Though avoid using because it is invalid HTML (it works due to tolerance within jQuery, it would fail in strict parsers).

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).

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 because it makes code harder to follow and it is unstable due to mixing of jQuery methods with element attributes (e.g. a plugin called "title" might convert an element into a heading, which means the title attribute can 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. 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.


 * Usage: JSDuck Tags are used inside block comments.


 * 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,.

Types
When documenting types, use a lowercase type of primitive value, the value itself, or the name of the constructor if an object is expected. JavaScript implements the below primitive values. Anything else is an object and should be described by its constructor (e.g.,  ,  ,  ,  ,  ,  , ..):
 * e.g. if a function always returns false
 * e.g. if a function always returns true
 * function returns either 'foo' or 'baa'
 * e.g. if a function always returns true
 * function returns either 'foo' or 'baa'

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 is 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.