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.
Zotero.FooBar
within the Zotero XPCOM object, ZoteroFooBar
without)Zotero.Date.sqlToDate()
, var foo = true;
)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(); }
For an explanation of the difference between public, privileged and private methods and members, please see Douglas Crockford's Private Members in JavaScript.
prototype
outside the constructor) should be used rather than privileged methods (defined using this
within) for memory and performance reasons: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 () { ... }, ... };
var _initialized = false;
, Zotero.Item.prototype._loadItemData = function() {…}
)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';
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; };
getID()
, generateHTML()
ZOTERO_CONFIG
array in zotero.js and capitalizedZotero.debug(message, level)
function. level
is optional and defaults to 3. Error messages (i.e. things that should never happen and that can't be handled gracefully) should be thrown rather than passed to debug()
.throw new Error()
instead of throwing a string (which doesn't generate a stack trace)