JavaScript Assertions are possible

Assertions are a great development-time debugging tool. They allow us to raise a red flag whenever a condition occurs that should never occur. This is, of course, an entirely different strategy than error-handling, which is a production-stage, run-time tool that helps to improve a programs robustness by gracefully "surviving" after an expected error occurs.

Assertion Example: The current object has been initialized before calling this routine

Error-handling Example: User attempted to import a CSV file with 5 rows, instead of the expected 6 rows

Assertions are a handy self-disciplinary tool for the developer, but not all development languages support them natively. Unfortunately, JavaScript falls into this category. But, the concept behind the assertion is simple, and the code behind the concept is very easy to integrate into any language. Below is very basic assertion function that can be executed as a statement. It can make use of console logging or popup dialog alerts. But, the real magic happens when the function "detects" that the script is no longer in development mode. In this case, it will rewrite itself to a very basic empty function to improve performance. Cool right!


ASSERT = function(condition, message) {
    /* the checks below will only be performed in development */

    /* during production, if an ASSERT is left in place, it will cause the ASSERT function to rewrite itself to a void, empty function to improve performance */

    /* you can assign appropriate values to local or dev parameters as makes sense by your application */

    if(local OR dev) {
        ASSERT = function(condition, message) { 
            /* do nothing */
        }
    }
    else {
        if(!condition) {
            alert(message);
            // or console.log(message);
            throw new Error(message);
        }
    }   
}

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs
  • Very rarely anything promotional


Tagged .

Updated: 2012-10-18

Phil LaNasa follow us in feedly