Table of Contents

JavaScript code in Zotero should conform to the following coding and style guidelines. We encourage Zotero plugin writers to follow these guidelines as well for consistency and possible future integration of code into the Zotero codebase.

Note: Not all current code in Zotero conforms to these guidelines. While existing code generally should not be modified for the sole purpose of conforming, new code or modifications to existing code should follow these guidelines.

Basic style

Braces

Braces should conform to 1TBS variant of the K&R style:

function abc() {
    ...
}
 
if (abc == 'def') {
    ...
}

Add a space after keywords to distinguish them from function calls:

Bad:

if(foo) {

Good:

if (foo) {

Braces must always be used for multi-line conditionals, even if the enclosed block contains a single line.

Bad:

if (!_initialized)
   init();

Good:

if (!_initialized) {
   init();
}

Public/privileged/private/static methods and members

For an explanation of the difference between public, privileged and private methods and members, please see Douglas Crockford's Private Members in JavaScript.

Zotero.Item = function() {
    ...
}
 
Zotero.Item.prototype.numCreators = function () {
    ...
}
Zotero.FooBar = (function () {
    // Private members and methods
    var _foo = "bar";
 
    function foo {
        ...
    }
 
    // Public members and methods
    return {
        getFooObjects: function () {
            ...
        }
    };
}());

or

Zotero.FooBar = {
    getFooObjects: function () {
         ...
    },
    ...
};

Comments

Functions should be commented using JSDoc syntax:

/**
 * Does something or other
 *
 * @param {string} value - This is a value
 * @param {boolean} [optionalValue] - This is an optional value
 * @return {number[]} - Array of itemIDs
 */
function myFunction(value, optionalValue) {
   ...
}

For readability and neatness, add a space after the slashes in line comments, and capitalize the first word:

Bad:

//this is a comment
var foo = 'bar';

Good:

// This is a comment
var foo = 'bar';

Additional notes

Bad:

function sum(num) {
    total = 0; // total is global!
    for (i=0; i<num; i++) { // i is global!
        total += i;
    }
    return total;
}

Good:

function sum(num) {
    var total = 0;
    for (let i=0; i<num; i++) { // i is local to the for loop
        total += i;
    }
    return total;
}
var func = function (bar) {
    var foo = bar;
};