coding_style_js.rst (5130B)
1 ======================= 2 JavaScript Coding style 3 ======================= 4 5 Coding style 6 ~~~~~~~~~~~~ 7 8 `prettier <https://prettier.io/>`_ is the tool used to reformat the JavaScript code. 9 10 11 Methods and functions 12 ~~~~~~~~~~~~~~~~~~~~~ 13 14 In JavaScript, functions should use camelCase, but should not capitalize 15 the first letter. Methods should not use the named function expression 16 syntax, because our tools understand method names: 17 18 .. code-block:: cpp 19 20 doSomething: function (aFoo, aBar) { 21 ... 22 } 23 24 In-line functions should have spaces around braces, except before commas 25 or semicolons: 26 27 .. code-block:: cpp 28 29 function valueObject(aValue) { return { value: aValue }; } 30 31 32 JavaScript objects 33 ~~~~~~~~~~~~~~~~~~ 34 35 .. code-block:: cpp 36 37 var foo = { prop1: "value1" }; 38 39 var bar = { 40 prop1: "value1", 41 prop2: "value2" 42 }; 43 44 Constructors for objects should be capitalized and use Pascal Case: 45 46 .. code-block:: cpp 47 48 function ObjectConstructor() { 49 this.foo = "bar"; 50 } 51 52 53 Operators 54 ~~~~~~~~~ 55 56 In JavaScript, overlong expressions not joined by ``&&`` and 57 ``||`` should break so the operator starts on the second line and 58 starting in the same column as the beginning of the expression in the 59 first line. This applies to ``?:``, binary arithmetic operators 60 including ``+``, and member-of operators. Rationale: an operator at the 61 front of the continuation line makes for faster visual scanning, as 62 there is no need to read to the end of line. Also there exists a 63 context-sensitive keyword hazard in JavaScript; see {{bug(442099, "bug", 64 19)}}, which can be avoided by putting . at the start of a continuation 65 line, in long member expression. 66 67 In JavaScript, ``==`` is preferred to ``===``. 68 69 Unary keyword operators, such as ``typeof``, should have their operand 70 parenthesized; e.g. ``typeof("foo") == "string"``. 71 72 Literals 73 ~~~~~~~~ 74 75 Double-quoted strings (e.g. ``"foo"``) are preferred to single-quoted 76 strings (e.g. ``'foo'``), in JavaScript, except to avoid escaping 77 embedded double quotes, or when assigning inline event handlers. 78 79 80 Prefixes 81 ~~~~~~~~ 82 83 - k=constant (e.g. ``kNC_child``). Not all code uses this style; some 84 uses ``ALL_CAPS`` for constants. 85 - g=global (e.g. ``gPrefService``) 86 - a=argument (e.g. ``aCount``) 87 88 - JavaScript Specific Prefixes 89 90 - \_=member (variable or function) (e.g. ``_length`` or 91 ``_setType(aType)``) 92 - k=enumeration value (e.g. ``const kDisplayModeNormal = 0``) 93 - on=event handler (e.g. ``function onLoad()``) 94 - Convenience constants for interface names should be prefixed with 95 ``nsI``: 96 97 .. code-block:: javascript 98 99 const nsISupports = Components.interfaces.nsISupports; 100 const nsIWBN = Components.interfaces.nsIWebBrowserNavigation; 101 102 103 104 Other advice 105 ~~~~~~~~~~~~ 106 107 - Do not compare ``x == true`` or ``x == false``. Use ``(x)`` or 108 ``(!x)`` instead. ``x == true``, is certainly different from if 109 ``(x)``! Compare objects to ``null``, numbers to ``0`` or strings to 110 ``""``, if there is chance for confusion. 111 - Make sure that your code doesn't generate any strict JavaScript 112 warnings, such as: 113 114 - Duplicate variable declaration. 115 - Mixing ``return;`` with ``return value;`` 116 - Undeclared variables or members. If you are unsure if an array 117 value exists, compare the index to the array's length. If you are 118 unsure if an object member exists, use ``"name"`` in ``aObject``, 119 or if you are expecting a particular type you may use 120 ``typeof(aObject.name) == "function"`` (or whichever type you are 121 expecting). 122 123 - Use ``['value1, value2']`` to create a JavaScript array in preference 124 to using 125 ``new {{JSxRef("Array", "Array", "Syntax", 1)}}(value1, value2)`` 126 which can be confusing, as ``new Array(length)`` will actually create 127 a physically empty array with the given logical length, while 128 ``[value]`` will always create a 1-element array. You cannot actually 129 guarantee to be able to preallocate memory for an array. 130 - Use ``{ member: value, ... }`` to create a JavaScript object; a 131 useful advantage over ``new {{JSxRef("Object", "Object", "", 1)}}()`` 132 is the ability to create initial properties and use extended 133 JavaScript syntax, to define getters and setters. 134 - If having defined a constructor you need to assign default 135 properties, it is preferred to assign an object literal to the 136 prototype property. 137 - Use regular expressions, but use wisely. For instance, to check that 138 ``aString`` is not completely whitespace use 139 ``/\S/.{{JSxRef("RegExp.test", "test(aString)", "", 1)}}``. Only use 140 {{JSxRef("String.search", "aString.search()")}} if you need to know 141 the position of the result, or {{JSxRef("String.match", 142 "aString.match()")}} if you need to collect matching substrings 143 (delimited by parentheses in the regular expression). Regular 144 expressions are less useful if the match is unknown in advance, or to 145 extract substrings in known positions in the string. For instance, 146 {{JSxRef("String.slice", "aString.slice(-1)")}} returns the last 147 letter in ``aString``, or the empty string if ``aString`` is empty.