Manual:Coding conventions/JavaScript

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

Linting
We use ESLint as our code quality tool. The settings for MediaWiki core can be found in. Many text editors or IDEs have plugins to provide live linting while you type (see "Integrations" on ESLint.org).

The following shows an example ESLint config file using the wikimedia config:

See .eslintrc.json in MediaWiki core and VisualEditor for examples. MediaWiki extensions must always have their own  file.

Install ESlint with: This will install ESLint globally. Then in any directory belonging to a project with an  file, and local npm dependencies installed, run it like this anywhere within the project

Whitespace
These and other aspects of our style guide are enforced with ESLint.
 * Indentation with tabs.
 * No trailing whitespace.
 * Use blank lines to 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 an argument list.
 * There should be one space on the insides of parentheses (such as in if statements, function calls, and arguments lists).
 * 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. This gives the contained code its own scope.

This pattern is known as an immediately-invoked function expression (or "iffy" ).

Declarations
Variables must be declared before use and should be the first statement of the function body. Each assignment must be on its own line. Declarations that don't assign a value can be listed together on the first line.

When you have multiple lines for value assignments and non-assigned variables, the extra lines should be indented another level.

Functions should be declared before use. In the function body, function declarations should go below the var statement.

Line length
Lines should wrap at no more than 80–100 characters. If a statement does not fit on a single line, split the statement over multiple lines. The continuation of a statement should be indented one extra level.

Function calls and objects should either be on a single line or split over multiple lines with one line for each segment. Avoid closing a function call or object at a different indentation than its opening.

Comments
Comments should be on their own line and go over the code they describe. Comments separate themselves from the opening syntax with a single space and start with a capital letter. Periods should only be used when making full sentences.

Use line comments ( inside code. Save block comments for documentation blocks and for commenting out code.

In older versions of MediaWiki, JavaScript code was often very poorly commented to keep the file size down. Nowadays modules are automatically minified by ResourceLoader.

Equality

 * Use strict equality operators ( and  ) instead of (loose) equality (  and  ). The latter does type coercion.
 * No Yoda conditionals. (yodaconditional.jpg)


 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:
 * Global variables:

Quotes
Use single quotes instead of double quotes for string literals. Remember there are no "magic quotes" in JavaScript i.e.  and   work everywhere.

Globals
In addition to the browser's native APIs, the only interfaces safe to use as global variables are  and , or (with local aliases) their longer names   and.

Avoid creating additional global variables. Code functionality exposed via a public identifier, should be added as functions and properties of an object within, e.g..

Configuration variables exposed by MediaWiki must be accessed via. For backward compatibility with legacy user scripts and gadgets, many -prefixed configuration keys are also exposed in the global scope. These are deprecated. (See

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



To avoid confusion with raw elements and other variables, prefix variables

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

Storage
Keys in localStorage and/or sessionStorage should be accessed via

Keys
Keys should start with  and use camel case and/or hyphens. Do not use underscores or other separators. Examples of real Beware that contrary to cookies via mw.cookie, there is no wiki prefix or cookie prefix added by default. If values must vary by wiki, you must manually include as part of the key.

Values
Values must be strings. Beware that attempting to store other value types will silently cast to a string (e.g.  would become  ).

Space is limited. Use short and concise values over object structures where possible. A few example:
 * For boolean state (true/false, expanded/collapsed) use "1" or "0".
 * For values that are always numbers, store them as-is and cast with  on the way out (avoid  ).
 * For values that are always strings, store them as-is.
 * For lists of software-defined values, consider comma-separate or pipe-separated if possible.
 * For lists of values that may be user-generated or more complex structures, use JSON.

Eviction strategy
Remember that Local storage does not have any eviction strategy by default. Therefore the following should be avoided: For example, if feature needs to store state about a variable entity (e.g. current page), it might make sense to use a single key for this and to limit the stored information only to the last few iterations (LRU), despite it having to parse and serialise a slightly larger amount of data on each time. It's discouraged to store these in separate keys as it would grow uncontrolled. Even with a tracking key, this would be subject to leaks because HTML5 web storage is shared between multiple open browser windows without locking mechanism (race conditions to update the tracking key).
 * Avoid using user-generated input as part of a key name.
 * Avoid keys containing identifiers for user-generated entities (e.g. user names, category names, page ids, or other user-provided or system-provided variables).
 * In general avoid approaches that involve creating a potentially large number of keys.

When removing use of a local storage key, or when changing the key name that is used, be sure to provide an eviction strategy for cleaning up old values. Typically for a more scalable system in the future.

Personal information
Avoid storing any personal information in the default storage (localStorage) as it remains when a user logs out or closes their browser. Use sessionStorage instead.

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 automatical
 * 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.
 * String methods,  , and   have similar signatures. Prefer  . (Example commit.) If need to extract a string of a certain length from a positive non-zero offset, only then should you use.
 * doesn't support negative  in IE8 and below.
 * doesn't support negative indices. And its start/end parameters are silently swapped if start is larger than end.
 * String methods,  , and   have similar signatures. Prefer  . (Example commit.) If need to extract a string of a certain length from a positive non-zero offset, only then should you use.
 * doesn't support negative  in IE8 and below.
 * doesn't support negative indices. And its start/end parameters are silently swapped if start is larger than end.

Documentation
Use to build documentation (see https://doc.wikimedia.org). The documentation comment structure is broadly similar to the but details differ to accommodate for JavaScript-specific language constructs (such as object inheritance, emitting events and arbitrary augmentation of an constructor's prototype).

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


 * Generate documentation:


 * Set up configuration for new projects: Create a JSDuck configuration file (at ). 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, indent

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


 * @abstract
 * @private
 * @static
 * @class Name (name is optional, engine will guess name from context)
 * @singleton
 * @extends ClassName
 * @mixins ClassName
 * @constructor
 * @inheritable
 * @member
 * @method name (name is optional, guessed)
 * @property name (name is optional, guessed)
 * @inheritdoc
 * @deprecated
 * @param {Type} name Optional text.
 * @return {Type} Optional text.
 * @chainable
 * @throws {Type}
 * @cfg {Type} [name="default value"] (used when a configuration object is passed to the class constructor, use one for each property and don't inclu









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  or   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 EC


 * te to jQuery
 * , Douglas Crockford