Skip to content

Instantly share code, notes, and snippets.

@asyncanup
Last active May 11, 2022 01:03
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save asyncanup/c52c1e4da9163fbc4590 to your computer and use it in GitHub Desktop.
Save asyncanup/c52c1e4da9163fbc4590 to your computer and use it in GitHub Desktop.
Simple JavaScript assert

Why you need assertions

It's better to fail with your own error than undefined is not a function.

A simple assertion solution would let your application fail early and fail at the right point in runtime execution. Allowing you to handle it better.

How you write assertions

For a recent barebones app, I wrote assertions as part of code like this:

function startApplication(url, callback) {
  assert('string' === typeof url, 'URL needs to be a string!');
  
  if (callback) assert('function' === typeof callback);
  // Application code
}

If I had needed a slightly more meaty assertion library, I would have used Shouldbe with Underscore. But this was just fine for the little app.

Show me the code!

(Or, how you implement simple assertion)

Just throw this simple assert into your application and use it generously:

function assert(condition, message) {
    if (!condition) {
        throw new Error(message || 'Assertion failed');
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment