DDO wiki:Coding conventions/JavaScript

Whitespace
These and other aspects of our style guide are enforced with JSCS.
 * Indentation with double spaces.
 * 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" ).

Files (e.g. jQuery plugins) that don't reference the mediaWiki object should omit the  and   arguments from the 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 are listed together on the same line.

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

Type checks

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

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

Globals
Only and  should be used (in addition to the browser's native APIs).

For backward compatibility, many -prefixed variables are exposed in the global scope. Don't use these and call  instead. (See Task T72470).

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

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.