Skip to content Skip to sidebar Skip to footer

How Do I Implement Assertions In JavaScript?

I'd like to use assertions to check for invalid parameters in my private methods (and others that should only be called internally). I'd prefer: A failed assertion terminates the

Solution 1:

Something like?

const assert = env === "production"
    ? () => {}
    : (test, msg) =>  {
        if (!test) throw new Error(`assertion failed: ${msg}`);
      };

// ...

function foo(param) {
    assert(typeof param === "number", "param is a Number");
}

Post a Comment for "How Do I Implement Assertions In JavaScript?"