Manual:Coding conventions/JavaScript

This page describes the coding conventions used within files of the MediaWiki codebase written in JavaScript. See also the general conventions that apply to all program languages, including JavaScript.

Closures
Always wrap your code in a closure. This avoids leakage of variables from or to another modules. Use the following closure ("Immediately-Invoked Function Expression" ):

When writing a jQuery plugin that doesn't use any MediaWiki variables and want to execute it at the document ready event, you may also use the following format, which removes the need for a separate closure as well as aliasing jQuery to :

Whitespace

 * See also the general conventions.

For optimum readability, put one space on both sides of operators, for example.

Feel free to use blank lines to separate logically related blocks from each other.

Keywords that are followed by  should be separated by one space. This helps distinguish between keywords and function invocations (, ,  ,  , etc.).

Don't use operators as if they are functions (such as,  ,  , ..). Best practices for readability still apply and if necessary using parentheses is fine, but don't forget to apply the above to avoid confusion.

Globals
The only globals should be  and   (and perhaps  or  if needed). Other globals should never be referenced directly.

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.

Aside from references to globals, usage of the  and   globals should be avoided. Instead alias them by using the function argument list of your file's closure. That way they are safe from bad code that re-defines globals (e.g. overwriting jQuery with an old version, that unregisters plugins and lacks new features not in the old version). This is also faster for performance as it safes property and scope chain lookups.

Example code
Instead of endlessly describing all conventions, below are a few sample codes that demonstrate the following:
 * the order in which code should generally be structured
 * the use and placement of  and   statements (all var statements at the top of the function scope)
 * Use literal arrays and objects
 * Use strict comparison to undefined instead of executing a typeof operation and comparing a string to "undefined".
 * No Yoda conditional

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 object constructors. Due to the nature of JavaScript a function is not declared as an object constructor, instead it is declared like any other and used as an object constructor with the  operator. Since no error checking exists, always use UpperCamelCase for naming constructors so that the required  operator is easily recognized by the reader.

Names with acronyms in them should treat the acronym as a normal word and only uppercase the first letter. For example,  is wrong and   is correct.

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

If you're creating elements based on a variable, you can do it either of these ways:

Always use the latter syntax if the input is not in direct control because putting it inside can do a lot of unexpected things.

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

For example:

and will also work. Though we recommend not using because it looks like invalid HTML.

Pitfalls

 * JavaScript does not have block scope. Declare your variables at the top of every function.
 * Bracket notation on a string doesn't work in older versions of IE such as IE6. Use the String prototype   instead.
 * Be sure to check the [//developer.mozilla.org/ MDN Docs] before using a prototype. For example, the [//developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter filter] Array prototype isn't supported in any version of Internet Explorer before 9. See also Compatibility.
 * Never make an assumption or imply its scope. A variable should be created as either  or  . Undeclared variables are assumed to be global - the opposite of PHP.
 * When throwing exceptions, use  rather than  . You can throw a string directly in JavaScript, but some debuggers won't pick up a stack trace or the location of the error without using the   constructor.
 * Use to cover for edge cases and cross-browser differences (instead of   or  )
 * 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.
 * Beware of trailing commas in object literals as they fail in Internet Explorer.
 * Similarly, when using an array literal, don't include any extra commas. In older versions of IE,  will be interpreted as   instead of the expected.
 * Make sure you're using or  appropriately.  Read more at http://javascript.info/tutorial/attributes-and-custom-properties
 * Always quote attribute selector values:  instead of  . Avoid bugs like jqbug 8229.
 * Don't use . It's the same number of characters as   and the property lookup is faster than a function call plus the property lookup (source of .size).

Environment
There is a few things that MediaWiki specifically (or inherently due to use of jQuery), does not support:
 * jQuery doesn't support working in an environment that has manipulates 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 no longer an issue since it is made read-only (as it should be), but in older browsers this can cause issues.

Comments
Make sure though that you use the JavaScript terminology (such as  instead of  ).

In older versions of MediaWiki, JavaScript code was often very poorly commented to keep it small. Since MediaWiki 1.17 and higher code is automatically optimized by ResourceLoader's minifiers and the like. Please be generous with comments in your code, as they help future readers of the code (possibly yourself).

Generally use (single or multi-line). Save for documentation blocks and for commenting out code.

Documentation comments
We don't (yet?) automatically build HTML files from javascript documentation comments (e.g. with Doxygen or JDDoc). Some advanced editors like NetBeans can make use of JSDoc-style annotations to aid in autocomplete and code navigation.

Whatever the case, here's the format we are using now:
 * Use  for the opening block, not ,   or some other variation.
 * Start with a short description about the object (object, array, function, regex, date, jQuery, mw.Title, whatever it may be).
 * Use any of these annotations as appropriate:
 * (indented example on the next line(s))
 * (if appropriate and/or overridden, documents the  context)
 * (if appropriate and/or overridden, documents the  context)
 * (if appropriate and/or overridden, documents the  context)

jQuery

 * See also jQuery

As of MediaWiki 1.17 jQuery is loaded by default and available everywhere. familiarize yourself with its API and don't be afraid to use jQuery for DOM manipulation, Event binding, AJAX requests and Animations. These are usually much easier to work with than classic low-level DOM and DHTML interfaces, and much more consistent across browsers.

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 with great distance between point X and the point of definition. A common problem is when referring to them in a conditional statement. returns null if no element matched the ID, therefore (since null casts to boolean false) it can be used as-is in an if statement. jQuery objects on the other hand (as any object in JavaScript) cast to boolean true no matter what (in a similar scenario one would use  instead).

Performance and best practices
JSHint

Validate with JSHint. Recommended JSHint settings: Assume:
 * [_] About unsafe line breaks
 * [x] Browser

JSLint

If you use JSLint:
 * [x] Assume a browser
 * [x] Tolerate ++ and --
 * [x] Tolerate messy white space ( "messy", as in, not using Crockford's conventions. MediaWiki's conventions match his reasoning, just slightly different implementation )
 * Globals: jQuery, mediaWiki

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.

Dot notation

Use dot-notation whenever possible to access object members.

Literals and native constructors

Use array and object literal notation, do not use  or. Do not use,   or. (Usage of  and   as conversion functions is encouraged but don't use them as constructors due to equality problems).