Assertion

Last Updated on: September 15, 2022

Assertion is a technique you can 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, so you must 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 your exception here
  }
}

You can use this function like this:

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

When obj is equal to null, you can see this message in your browser console:

uncaught exception: AssertException: Object is null!

Assertion is an excellent technique to help you locate any errors lurking in the depths of your JavaScript code.


Get notified of new posts:


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *