What is “assert” in JavaScript?

frrlod picture frrlod · Mar 9, 2013 · Viewed 213k times · Source

What does assert mean in JavaScript?

I’ve seen something like:

assert(function1() && function2() && function3(), "some text");

And would like to know what the method assert() does.

Answer

T.J. Crowder picture T.J. Crowder · Mar 9, 2013

There is no assert in JavaScript (yet; there's talk of adding one, but it's at an early stage). Perhaps you're using some library that provides one. The usual meaning is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.

Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string. So you might do:

assert(typeof argumentName === "string");

...where assert would throw an error if the condition were false.

A very simple version would look like this:

function assert(condition, message) {
    if (!condition) {
        throw message || "Assertion failed";
    }
}

Better yet, make use of the Error object if the JavaScript engine supports it (really old ones might not), which has the advantage of collecting a stack trace and such:

function assert(condition, message) {
    if (!condition) {
        message = message || "Assertion failed";
        if (typeof Error !== "undefined") {
            throw new Error(message);
        }
        throw message; // Fallback
    }
}

Even IE8 has Error (although it doesn't have the stack property, but modern engines [including modern IE] do).