spudly.shuoink.com

the best way to predict the future is to implement it

Entries Comments


assert for javascript

1 July, 2008 (20:26) | JavaScript

I was looking through a C++ book the other day and realized that javascript doesn’t have any functionality (that I know of at least) to perform assertions.

An assertion allows you to check in your script for things that should never happen, and throw an error if the thing that wasn’t supposed to happen happened. In other words, they throw an exception under certain conditions.

Anyway, I’ve written a very simple javascript function to allow you to use assertions in your code. Here it is:

function assert( test ) {
   if ( test === false ) {
      throw new Error( "Assert failed" );
   }
   return test;
}

It’s really simple, but really quite useful, especially if you’ve got some complex code and you want to make sure it worked properly before continuing.

Here’s a simple example:

var age = calculateAgeBasedOnSomeCrazyRandomAlgorithm();
assert( age > 0 ); // age can never be negative!

At this point, if age is less than or equal to 0, a JavaScript error will be thrown, and the current operation will stop executing.

« String.interpolate()

 Date.add(), Date.subtract(), & Date.truncate() »

Write a comment