frrlod frrlod - 5 months ago 49x
Javascript Question

JavaScript - assert?

What does

mean in javascript?

I've seen something like:

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

And would like to know what the method


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).