JavaScript coding guidelines

General

  • Using global variables (e.g. global = 1) should be avoided as much as possible.

Naming conventions

  • All names must be written in English.
  • Variables must be written in lowercase characters separated by underscores.

Good example:

var hostid = 12345,
    item_applications = [];

Bad example:

var Hostid = 12345,
    itemApplications = [];
  • Prefix variable names with $ only when they contain jQuery objects.

Good example:

var $widget_header = $('.widget_header', $widget),
    host_count = 5;

Bad example:

var widget = $('.widget_container'),
    $hosts = [$('#host1'), $('#host2')];
  • Function names (except constructors) must use lower camel case.

Good example:

function create() {
    // some logic here
}

function getName() {
    // some logic here
}

Bad example:

function Create() {
    // some logic here
}

function get_name() {
    // some logic here
}

Variables

Variable declaration

  • Each variable must be declared on a separate line.

  • Multiple variables must be separated by a comma.

Good example:

var itemids = [],
    item_applications = [];

Bad example:

var itemids = [];
var item_applications = [];

Bad example:

var itemids = hostids = [];

var left = null, top = null, right = null, bottom = null;

var itemIds = [],
    itemApplications = [];

Objects

  • Do not use quotes when creating object entities.

Good example:

var person = {firstname: 'Mario', lastname: 'Smith'};

person.firstname = 'Mr.';

Bad example:

var person = {"firstname": 'Mario', "lastname": 'Smith'};

Assignments

  • Avoid multiple left-hand assignments on a single line.

Good example:

curr_lbl.style.background = background;
curr_lbl.style.color = background;

Bad example:

curr_lbl.style.background = curr_lbl.style.color = background;
  • Wrap complex statements assigned to a variable in parentheses.

Good example:

var disable = (return_code === '-1' && service_enabled);

Bad example:

var disable = return_code === '-1' && service_enabled;

Conditional statements

  • The opening brace is written on the same line as the conditional statement.

  • The closing brace is always written on its own line.

Good example:

if (list.length > 100) {
    // some logic here
}

Bad example:

if (list.length > 100)
{
    // some logic here
}

If/Else/Else if

  • "If" statements must always use curly braces {}.

Good example:

if (list.length > 100) {
    // some logic here
}

if (list.length > 100) {
    // some logic here
} else {
    // some logic here
}

if (list.length > 100) {
    // some logic here
} else if (list.length == 1) {
    // some logic here
} else {
    // some logic here
}

Bad example:

if (list.length > 100) // some logic here

if (list.length > 100) {
    // some logic here
} else {
    // some logic here
}
  • Use "else" or "else if" when possible, avoiding separate "if" statements.

Good example:

if (a == b) {
    d = e;
}
else if (a == c) {
    d = f;
}
else {
    d = g;
}

Bad example:

if (a == b) {
    d = e;
}
if (a == c) {
    d = f;
}
if (a != b && a != c) {
    d = g;
}

Switch

  • If we fall through, the comment should be present, confirming that it's intentional.

Example:

switch (condition) {
    case 1:
        // some logic here
        // falls through
    case 2:
        // some logic here
break;

    case 3:
        // some logic here
break;

    default:
        // some logic here
break;
}

Try/Catch

Example:

try {
    // some logic here
} catch (exception if condition) {
    // some logic here
} finally {
    // some logic here
}

Loops

For

Example:

for (var i = 0; i < list.length; i++) {
    // some logic here
}

While

Example:

while (list.length > 0) {
    // some logic here
}

Do/While

Example:

do {
    // some logic here
} while (list.length > 0);

forEach() iterator

Example:

['<some_array>'].forEach(function (field) {
    // some logic here 
});

Formatting

  • Limit lines to 200 characters.

Strings

  • Use single quotes for strings when possible.

  • Add spaces around + in string concatenations.

Good example:

const x = 'string';

Bad example:

const x = "string";

Blank spaces

  • Use a single space after commas in argument lists.

Good example:

function updateUserProfile(idx, value_int, idx2) {
    // some logic here
}

Bad example:

function updateUserProfile(idx,value_int,idx2) {
    // some logic here
}
  • Use spaces around binary operators, but do not add spaces between unary operators (like -, ++, --) and their operands.

  • Use a space between a keyword and the following parenthesis.

Good example:

if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
    n = (n > 0 || -1) * Math.floor(Math.abs(n));
}

Bad example:

if(n!==0&&n!==(1/0)&&n!==-(1/0)){
    n=(n>0||-1)*Math.floor(Math.abs(n));
}
  • Use a space after a colon before a keyword.

Good example:

init: function(time) {
    this.delay = time;
    this.delayLeft = this.delay;
    this.start();
}

Bad example:

init:function(time) {
    this.delay = time;
    this.delayLeft = this.delay;
    this.start();
}

Blank lines

  • Use a blank line after variable declarations, around statements, and before return.

Good example:

var footerButton = GetData(e.target),
    form = footerButton.closest('form'),
    confirmText = footerButton.attr('confirm');

if (confirmText && !confirm(confirmText)) {
    Event.stop(e);

    return false;
}

Bad example:

var footerButton = GetData(e.target),
    form = footerButton.closest('form'),
    confirmText = footerButton.attr('confirm');
if (confirmText && !confirm(confirmText)) {
    Event.stop(e);
    return false;
}

Comments

  • Use only // double slashes for comments.

Example:

// simple comment
  • Start block comments with a capital letter.

Example:

//
// New block comment.
//
  • Use full words in comments (e.g., parameter instead of param).

  • Write multiline comments using block syntax and keep within the maximum line length.

  • Omit comments if the code is self-explanatory.

Comparison

  • Use == equal or != not equal operators when comparing numeric values to zero.

Good example:

if (itemid != 0) {}

Bad example:

if (itemid) {}
  • Use typeof to check if a variable is undefined.

Good example:

if (typeof variable !== 'undefined') {}

Bad example:

if (variable !== undefined) {}

General structure

  • Decouple logic from the main function by placing it in a separate object.

  • Keep the main function simple and avoid unnecessary complexity.

  • Exception: simple functions may remain self-contained.

Good example:

var SinteticData = {
    params: {
        min: 0,
        // some params
    },

    setParams: function (params) {
        // some magic here
    },

    getSin: function (min, max, shift, period) {
        // some magic here
    },

    getValue: function () {
        // some magic with call getSin()
    }
}

try {
    SinteticData.setParams(JSON.parse(value));

    return SinteticData.getValue();
} catch (error) {
    error += (String(error).endsWith('.')) ? '' : '.';

    Zabbix.log(3, '[ DEMO ] ERROR: ' + error);

    return JSON.stringify({ 'error': error });
}

Bad example:

var SinteticData = {
    params: {
        min: 0,
        // some params
    },

    setParams: function (params) {
        // some magic here
    },

    getSin: function (min, max, shift, period) {
        // some magic here
    }
}

try {
    SinteticData.setParams(JSON.parse(value));

    var tmp_data = SinteticData.getSin(SinteticData.params),
        tmp_data2 = [],
        tmp_out = '';

    for (var i = 0; i < tmp_data.length; i++) {
        // some magic with update tmp_data2
    }

    for (var j = 0; j < tmp_data.length; j++) {
        // some magic with update tmp_out
    }

    return tmp_out;
} catch (error) {
    error += (String(error).endsWith('.')) ? '' : '.';

    Zabbix.log(3, '[ DEMO ] ERROR: ' + error);

    return JSON.stringify({ 'error': error });
}
  • Treat all external data structures (objects, arrays, input parameters) as unreliable and validate them before use.

For example, check the input parameters:

...
    setParams: function (params) {
       ['min', 'max', 'shift', 'mutation_t', 'mutation_v', 'mutation_r', 'period'].forEach(function (field) {
           if (typeof params === 'object' && typeof params[field] !== 'undefined' && params[field] !== '') {
               SinteticData.params[field] = parseFloat(params[field]);
           }
       });
   }
...
  • Avoid directly accessing object properties by key or array element by index; use dedicated methods instead.

Good example:

var data = some_object.getField('property');

Bad example:

var data = some_object['property'];
  • Always catch exceptions and provide complete information about their cause.

Good example:

try {
    credentials = JSON.parse(credentials);
} catch (error) {
    throw 'Failed to parse response received from instance metadata. Check debug log for more information.';
}

Bad example:

credentials = JSON.parse(credentials);
  • Avoid copying blocks of code; consider using file inclusion instead.

Example:

params:
    include:
    - ./scripts/oci_validate_zbx_params.js
    - ./scripts/oci.js
    - ./scripts/compute/oci_compute_health_metrics_POST.js
  • For HTTP requests, provide proxy support.

Example:

if (typeof AWS.params.proxy !== 'undefined' && AWS.params.proxy !== '') {
    request.setProxy(AWS.params.proxy);
}
  • For logging, use tags to identify the process.

Good example:

Zabbix.log(3, '[ AWS Billing ] ERROR: ' + error);

Bad example:

Zabbix.log(3, error);