Assertion

by jeremyjones on March 19, 2011

  • Share
  • CevherShare
  • Share

Assertion is one of the common techniques that people use to debug JavaScript code. You use assertion to ensure that an expression evaluates to true during script execution. This means that if any expression evaluates to false there is possibly a bug in your code. There is no inbuilt assert function in JavaScript, but it is simple to write your own. This example will throw an exception of type AssertException when the expression evaluates to false:

function AssertException(message) { this.message = message; }
AssertException.prototype.toString = function () {

return 'AssertException: ' + this.message;
}
function assert(exp, message) {

if (!exp) {

throw >new AssertException(message);
}
}

Making your function throw an exception is not very useful on its own, so you need to include a relevant error message or code to help you find the assertion that has the problem. You can use catch() to check whether an exception is an assert exception in the following example:


catch (e) {
If (e instanceof AssertException) {
// Deal with you exception here
}
}

You can use this function like this:

assert(obj != null, ‘Object is null!);

When obj is equal to null, the Firefox JavaScript console will show this message:

uncaught exception: AssertException: Object is null!

Assertion is a great technique to help you locate any errors in the depths of your JavaScript code.

Leave a Comment

Previous post:

Next post: