ryan-cook
ryan-cook

Reputation: 96

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:

EDIT: I'm not trying to test anything here. If my motivation for doing this is unclear, check out CC2 or Clean Code or the Wiki page: https://en.wikipedia.org/wiki/Assertion_(software_development)

Upvotes: 1

Views: 191

Answers (1)

rich remer
rich remer

Reputation: 3577

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");
}

Upvotes: 1

Related Questions