JavaScript coding guidelines

From MozillaZine Knowledge Base

(Difference between revisions)
Revision as of 23:52, 7 November 2004
Asqueella (Talk | contribs)
(add a link to js vars)
<-- Previous diff
Revision as of 23:27, 14 November 2004
Asqueella (Talk | contribs)
(oops. remove extra '()')
Next diff -->
Line 62: Line 62:
}, },
- doSomething(): function(aParam) {+ doSomething: function(aParam) {
alert(aParam); alert(aParam);
} }

Revision as of 23:27, 14 November 2004


Javascript coding guidelines

Here is a list of conventions (discuss). Some people disagree, but some think it's a good idea to follow them.

Naming Convensions

There are six basic rules.

  1. Every variable object name's 1st char should be a lower case. var myName = "Torisugari";
  2. Every constant object name should be upper cases. const MY_NAME = "Torisugari";
  3. Every constructor name's 1st char should be an upper case.
          function Mozillazine(){
            this.description="A Cool Site";
          var gMyFav = new Mozillazine();
  4. By prefix g the author means that is a global object, and unique in the window. Exception: A global function doesn't have to start with g.
  5. By prefix a the author means that is an argument.
  6. By prefix _ the author means that is a private member.

Bad examples, though gramatically correct (see next section for a good example):

var bar=0; /*bar should be gBar*/
function foo(){
  var gFoobar = 0; /* gFoobar is not a global value */
  return gFoobar;

function foo(bar){  /* bar should be aBar */
  var aFoobar="foo" + bar; /* aFoobar is not an argument */
  return aFoobar;

var gFoo={

var foobar=gFoo._bar; /* _bar is a public member ? */
/* In other words, you can write only "this._bar" */

Avoiding name collisions

In order to avoid name collisions, use an unique prefix (for example, name of the extension) for identifiers in overlays (this also applies to XUL ids in overlays).

To avoid prefixing each identifier, you can put them inside an object with unique name:

var ExtensionName = {
  _privateMember: 3,
  anotherMember: "A string",

  init: function() {

  doSomething: function(aParam) {


Dev : Javascript variables