devnotes.

The Assert Module

assert is a built-in module for one specific job: checking that something is true, and loudly throwing an error if it isn't. Think of it as a tripwire you plant inside your own code — if an assumption you're relying on turns out false, you want to know immediately, not three functions later when the bug has already caused confusing downstream damage.

The basic shape

const assert = require('assert');

assert(value, message);

If value is truthy, nothing happens — execution just continues. If it's falsy, assert throws an AssertionError, optionally carrying your custom message.

function withdraw(balance, amount) {
  assert(amount > 0, 'Withdrawal amount must be positive');
  assert(amount <= balance, 'Insufficient funds');
  return balance - amount;
}

console.log(withdraw(500, 100)); // 400
withdraw(500, -10); // throws: AssertionError [ERR_ASSERTION]: Withdrawal amount must be positive

More specific comparison methods

Beyond the basic truthy check, assert offers sharper tools for comparing values:

assert.strictEqual(2 + 2, 4);                    // passes silently
assert.strictEqual(2 + 2, 5);                    // throws, values don't match

assert.deepStrictEqual({ a: 1 }, { a: 1 });       // passes — compares contents, not identity

assert.throws(() => {
  JSON.parse('not valid json');
}, SyntaxError);                                   // passes — confirms the function does throw

strictEqual is generally preferred over the looser equal, since it uses === comparison rather than allowing type coercion — assert.equal(1, '1') would pass, which is rarely what you actually want to verify.

Where this is genuinely used

In practice, assert shows up most often in testing code (it's the foundation several test runners build on) and in internal sanity checks — places where a value should always satisfy some condition given correct earlier logic, and if it doesn't, something has already gone wrong upstream and you'd rather fail loudly right there than silently produce a wrong result further down the line.

A word on catching assertion failures

Since assert throws, wrap it in a try/catch if you want to handle the failure gracefully instead of crashing the whole process:

try {
  assert.strictEqual(typeof userId, 'number', 'userId must be a number');
} catch (error) {
  console.error('Validation failed:', error.message);
}
The Assert Module | DevNotes