Secrets of the JavaScript Ninja

From Code Self Study Wiki
Jump to: navigation, search

Chapter 1

Testing

// Syntax:
assert(condition, message);
 
// Example:
assert(x == 200, "Error: x is not 200");

Performance Analysis

start = new Date().getTime();
for (var n = 0; n < maxCount; n++) {
    // measure this
}
elapsed = new Date().getTime() -start;
assert(true, "Measured time: " + elapsed);

Chapter 2

Debugging

To debug in all browsers:

function log() {
    try {
        console.log.apply(console, arguments);
    }
    catch(e) {
        try {
            opera.postError.apply(opera, arguments);
        }
    }
    catch(e) {
        alert(Array.prototype.join.call(arguments, " "));
    }
}
// Some code
log(x); // see the function above

You can set breakpoints in Firebug or the Chrome developer tools. It stops right before the marked line (at least in Firebug).

Testing

Guidelines for tests:

  • Repeatability
  • Simplicity
  • Independence (break into small units)

Types of tests:

  • Deconstructive -- remove things from the current point
  • Constructive -- start at a point where there are no bugs and add things until the bug appears again
When performing unit testing, a test group will likely represent a collection of assertions as they relate to a single method in our API or application. If you were doing behavior-driven development, the group would collect assertions by task. Either way, the implementation is effectively the same.

He uses methods on anonymous functions:

(function() {
    var something1, something2, something3;
    this.test = function test(arg1, fn) {
        // some code
        fn();
    };
})();