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

Like CSS declarations, in an object literal the notation should be one key per line, have no space before the colon and one space after the colon.

Use operators such as typeof like, not like a function.

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 compare to undefined instead of executing a typeof operation and comparing strings.
 * 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.

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

jQuery pitfalls

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

Comments and documentation
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 run code through ResourceLoader's minifiers and the like, please feel free to liberally comment your code to aid future maintainers.

Doxygen/jsdoc documentation is not yet built automatically from JavaScript files, but it may be at some point in the future. In the meantime, some advanced editors like NetBeans can make use of JSDoc-style annotations to aid in autocomplete and code navigation.

Here's the format we aim to follow from now on:

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, AJAX requests, and utility functions. 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 instances 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.

Performance and best practices
JSHint

Validate with JSHint. Recommended JSHint settings: Assume:
 * Tick all "Warn"-checkboxes, except these:
 * [ ] About unsafe line breaks
 * [x] Browser
 * [x] jQuery

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