Utility functions in JavaScript

We often have JavaScript functions which are used in several pages of our project. Best approach is to store all these functions in a shared JavaScript file, included when necessary.

The usual approach I adopt (and suggest) is to create an utility class like the following one:

function Util () {}

Util.read = function (sel) {
    return jQuery(sel).val();
};

Util.write = function (sel, val) {
    jQuery(sel).val(val);
};

We start to define an empty Class (named Util) by a constructor and then we add to it our functions.
These are “static” like functions which are always available, without the need to create an instance of the class Util (with the new operator).

I save the above code in a util.js file (file name = class name).

How to use the utility functions ?

    // read the value of the element with id myinput
    var val = Util.read('#myinput');

JSLint users: don’t forget to add Util in the globals list ( /*globals Util */ )

Final comment: these approach should be used only for utility methods which do not save internal state
or use global variables. The constructor function should be empty; the functions defined as above (and not via class prototype) cannot access to any
class field.

Checking JavaScript in NetBeans

NetBeans 7.3 has introduced an improved JavaScript support, including a wider support for JavaScript code checks. It is also possible to install a JSLint plugin for stronger code checking.

Let’s start with NetBeans native capabilities. In the Tools -> Options -> Editor -> Hints we can find all NetBeans code quality checks, divided by language.

The following picture shows the JavaScript checks:

2013-05-22_fig1

In the following picture we see how the NetBeans JavaScript hints work:

2013-05-22_fig2

This is nice feature to have so we can fix the errors while we are coding. Unfortunately the NetBeans JavaScript checks are limited (in number) and we should use an external plugin to enforce our code checking rules to our js files.

JSLint is the reference JavaScript quality checker. A good JSLint plugin for NetBeans is available here.

To install it in NetBeans, juts follow this simple procedure:

1. Download the plugin on the PC

2. Open the Plugin window in NetBeans (Tools -> Plugins) and click on the “Downloaded” tab.

3. Click on “Add Plugins” and select the downloaded file.

2013-05-22_fig3

4. Press “Install” to start JSLint plugin installation.

After installation, we can go back to our file and check it now with JSLint. Open the context menu (right mouse click) and select “JSLint”. In the Action Items window, we find all errors detected by JSLint on our file.

2013-05-22_fig4

As we can see in the picture, JSLint is more restrictive than NetBeans, showing more errors (3 in our small example). For the complete and reference list of JSLint checks please refer to the JSLint author page.

If the Action Items list contains errors on other files in the project and in particular on libraries files (like jQuery and Bootstrap js files) we can easily filter out them. We can create an Action Item Filter as shown in the following images:

2013-05-22_fig5

2013-05-22_fig6

JSLint plugin configuration can be found in Tools -> Options -> Miscellaneous -> JSLint (tab). The options set on this page are valid for all JavaScript files in the project. In the next picture, the configuration I usually use in my projects:

2013-05-22_fig7

Basically I limit line length to 80 characters and defineĀ window as global variable.

File specific settings can be defined as follows:

/*jslint sloppy:true */
/*global window */
function myFunc(txt) {
window.alert(txt)
}

The /*jslint contains JSLint configuration parameters while /*global defines implicit global variables (defined outside the current file). Important: there should be no space between the asterisk and the words jslint and global so take care that NetBeans formatting will not try to format Javascript comments.

How to define variables in Javascript

As in every language, also in Javascript there are several different ways to define variables and everybody is free to select the preferred approach. Nevertheless we should consider the following:

  • Javascript has some unusual rules on variables scoping
  • Code quality checkers like JSLint and JSHint prefer some specific solutions
  • Using a “standard” solution makes our code cleaner and more readable

The approach I use is quite standard and it can be summarized in few rules.

The basic rule is that all variables should be defined before their use. Javascript does not force us to define the variables before usage; if not defined, Javascript will create them on the fly.

Unfortunately this behavior let us to make errors like this:

activeList = true;
if (activList) {
alert("The list is active");
}

Inside the if the variable name is wrong; in the example Javascript will create a new variable with false as default value so the alert will never be invoked.

If possible, variables should be defined inside functions.

Global variables (defined in the same .js file but outside any function) should be used only if there are no alternatives. These kind of variables should be defined at the begon of the file and with a relevant comment.

External variables (defined in other .js files) should not be used (even if this is not always possible).

The var instruction should be the first in the function body

Example:

var gl = 1;  // global var
function myFunc () {
    var lc1 = 0,
        lc2 = 15,
        i;
    for (i = gl; i < 10; i += 1) {
        lc1 = lc1 + i;
    }
    ....
}

Notes:

  • gl is a global variable. It is defined and commented at the the begin of the file.
  • lc1, lc2 and i are all local variables, defined inside the myFunc function.
  • I have used only one var statement for all the local variables. This is also the preferred JSLint solution. It is also acceptable to use one var instruction for each variable. Here what it is important is to be coherent and to use the same solution among all project files.
  • For a similar reason I have defined the loop variable (i) together with the others. Alternative could be to define it inside the loop instruction (for (var i = gl; ….) but we should not forget that index variables have the same scope of the other function variables and they are not limited to the loop scope (like, for example, in Java)