Quick Javascript Development Tips

Recently I have written lots of Javascript and jQuery code working on a live betting system that is build by consuming two APIs (Search and POS API) and has pretty complex functionality. So, time has come to open the Javascript tag on my blog with two quick tips about developing Javascript code.

The first tip is about benchmarking and second about debugging Javascript code using the console functionality. Did I mentioned that I use Firefox and Firebug for web development?

Benchmarking Javascript code using Firebug is really easy, You just drop console.time at the beginning and console.timeEnd at the end of the code snippet, and then you get result about how that code is performing:

console.time('BEFORE');
var ar = [];
for (i = 0; i < 10000; i++) {
  ar.push("text");
}
ar.join("");
console.timeEnd('BEFORE');

console.time('AFTER');
var str = "";
for (i = 0; i < 10000; i++) {
  str += "text"
}
console.timeEnd('AFTER');

The results are:

BEFORE: 16ms
AFTER: 13ms

Second tip is about cross-browser Javascript debugging by logging debug messages. I get this tip from Secrets of the JavaScript Ninja book, but improved it a little bit by encapsulating it in a module using the Javascript module pattern and adding some JS Lint code quality check.

/*global console */
/*global opera */


"use strict";


/**
 * Logger functionality
 * @constructor
 */

var LOGGER = (
  function () {

    /**
     * Writes log messages
     * 
     */
    function log() {
        try {
          console.log.apply(console, arguments);
        } catch (e) {
          try {
            opera.postError.apply(opera, arguments);
          } 
          catch (e2) {
          alert( Array.prototype.join.call( arguments, " " ) );
          }
        }
    }


    /**
     * Public interface
     * 
     */
    return {
      log: log
    };
  }()
);

Then we can use this module and log some messages:

LOGGER.log("message 1")
LOGGER.log("message 2")

If you like more fancy way of logging messages you may want to check the Blackbird library.

Next on Javascript I will be writing on some Javascript tools for: code quality check, documenting code, code compression, etc.