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 as our code quality tool. The settings for MediaWiki core can be found in. Please use an editor that supports inline linting (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.

The  file is organised alphabetically and sectioned as follows:

Projects can add additional enforcing or relaxing options in the local section. The following common options are used in all projects:

To avoid confusion between an enforcing and a relaxing option, group them by category (see http://jshint.com/docs/options/ for an overview). For example  is a relaxing option to allow functions in a loop, whereas   is a restriction to disallow undefined variables.

Look at the JSHint configuration for MediaWiki core or that of VisualEditor for 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, thus causing inability to merge new changes until it's 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.
 * When a function has parameters, there should be a space on the inside side of both parentheses, for both function definitions and function calls.
 * 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.

In terms of parentheses, both enclosing either the entire expression or just the function expression works (see Ben Alman's blog post). For consistency use the above format (enclosing the entire expression).

Declarations
Variables must be declared before use. JavaScript will hoist them at run-time if you don't. Specifying them this way makes code easier to read by reflecting what happens at run-time. It helps prevents common mistakes such as implied globals.

Functions should be declared before use. Local functions should follow the  statement.

Indentation
Indent blocks from their containing blocks with one tab. Often, editors display this as the same width as 4 spaces, but the display configuration is up to the developer.

Line length
Lines should wrap at no more than 80–100 characters. If a statement does not fit on a line, split the statement over multiple lines. If possible, place the line break after an operator (e.g. a comma or logical operator). The next line should be indented an extra level.

Function calls and objects should either be on a single line or split over multiple lines with 1 line for each segment. Avoid mixing the number of segments per line or ending a call or object in the middle of an indentation level.

Comments
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. Nowadays 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 favour 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, lots of -prefixed variables are exposed in the global scope (if  is enabled, see ). Don't rely on these and 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 are constructors used with the  operator. Those names must start with an uppercase 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 our only defence.

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 and other variables, prefix variables storing an instance of jQuery with a dollar sign ( e.g. ). This matters because the DOM (e.g.  ) returns null if no elements were found, therefore (since null casts to boolean false) one would test the plain variable like. jQuery objects on the other hand (like any array or object in JavaScript) cast to boolean true. If you confuse a jQuery object with the return value of a DOM method, a condition could fail badly. In such case 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

 * Be careful to preserve compatibility with left-to-right and right-to-left languages (i.e.  or  ), especially when styling text containers. Putting those declarations in CSS file will allow them to be automagically  flipped for RTL-languages by ResourceLoader.
 * Use and  appropriately. Read more:
 * jQuery#attr, jQuery API
 * Attributes and custom properties, javascript.info
 * Consistently 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
Use JSDuck to build documentation (see https://doc.wikimedia.org/). The documentation comment structure is broadly similar to the doxygen format we use in PHP but details differ to accommodate for javascript-specific language constructs (such as object inheritance, emitting events and arbitrary augmentation of an constructor's prototype).


 * Installation: Standard RubyGems install: See the installation guide for more information.


 * Generate documentation:


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

Documentation comments

 * Text in free-form blocks (e.g. description of methods, parameters, return values etc.) should be sentence case.
 * End sentences in a full stop.
 * Continue sentences belonging to an annotation on the next line, indented with one additional space.
 * Value types should be separated by a pipe character. Use only types that are listed in the Types section or the identifier of a different class as specified in your project (e.g. ).

Tags
We use the following annotations. They should be used in the order as they are described here, for consistency. See JSDuck/Tags for more documentation about how these work.


 * @abstract
 * @private
 * @class Name (name is optional, engine will guess name from context)
 * @singleton
 * @extends ClassName
 * @mixins ClassName
 * @constructor
 * @static
 * @method name (name is optional, guessed)
 * @property name (name is optional, guessed)
 * @inheritable
 * @param {Type} name Optional text.
 * @returns {Type} Optional text.
 * @chainable
 * @throws {Type}

Types
Special values:
 * undefined
 * null
 * this

Primitive types:
 * boolean
 * number
 * string

Built-in classes:
 * Array
 * Date
 * Function
 * RegExp
 * Object

Browser classes:
 * HTMLElement

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.