assert.ok()

Throws an AssertionError when the given value is falsy, otherwise does nothing.

Signature
assert.ok(value[, message])
  • Added in Node.js v0.1.21

Parameters

ParameterTypeDescription
$valueanyThe input that is checked for being truthy.
$messageoptionalstring | Error | FunctionError message, an Error instance to throw instead, or a function called on failure. When omitted, Node generates a message from the source text of the failing call.

Errors

Throws an AssertionError with code ERR_ASSERTION when value is falsy; if message is an Error instance, that error is thrown instead.

Changelog

  • PHP v26.0.0Message may now be a printf-like format string or function.
  • PHP v10.0.0assert.ok() with no arguments now uses a predefined error message.

assert.ok() is the truthiness check the rest of the module is built on. The module object is itself this function, so assert(value) and assert.ok(value) are literally the same callable — assert === assert.ok evaluates to true.

Reach for it when the thing you are checking is genuinely a boolean condition: a regex matched, an array is non-empty, a flag is set. For anything with two comparable sides, use assert.strictEqual() instead — a failing ok() can only report false, while a failing strictEqual() prints both values and a diff.

The generated message

With no message, Node reads the source file and reconstructs the failing expression, producing something like The expression evaluated to a falsy value: assert.ok(rows.length). That only works when the source is readable; from a REPL, from node -e, or after minification you get a bare fallback. Supplying your own message is the reliable option.

It is not a type guard

The thrown object carries actual (your value), expected: true and operator: '=='. Note that operator says ==, but no comparison happens — the value is simply coerced to boolean.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Guard a function entry point so a bad argument fails loudly instead of producing NaN downstream
  • Assert that a parsed config contains a required section before the server boots
  • Confirm a regex matched at all before reading capture groups

Frequently asked questions

What is the difference between assert() and assert.ok()?

There is none — assert is assert.ok, the same function object, so assert === assert.ok is true. assert.ok() was added in v0.1.21 and the callable alias in v0.5.9; pick whichever reads better and stay consistent.

Why does assert.ok() print my source code in the error message?

When you omit the message argument, Node reads the file the call came from and rebuilds the failing expression to produce a message like "The expression evaluated to a falsy value: assert.ok(user.id)". Pass your own message to get a stable, readable failure instead.

Should I use assert.ok() or assert.strictEqual() in tests?

Use strictEqual() whenever you have two values to compare, because its failure output shows both sides and a diff. Reserve ok() for conditions that are already boolean, such as a regex test or a length check.

More examples

Use it as a precondition guard

The first call returns the pool object. The second fails the third assertion, and because each check carries its own message the error names the exact rule that was broken rather than reporting a generic falsy value.

Example · javascript
const assert = require('node:assert');

function createPool(options) {
  assert.ok(options, 'createPool requires an options object');
  assert.ok(Number.isInteger(options.max), 'options.max must be an integer');
  assert.ok(options.max > 0, 'options.max must be greater than 0');
  return { max: options.max, inUse: 0 };
}

console.log(createPool({ max: 8 }));
// { max: 8, inUse: 0 }

try {
  createPool({ max: 0 });
} catch (err) {
  console.log(err.message);
  // options.max must be greater than 0
}

Throw a typed error instead of an AssertionError

When message is an Error instance, that instance is thrown verbatim — the output shows a TypeError with no ERR_ASSERTION code. This lets library code keep its own error taxonomy while still using assert for the check itself.

Example · javascript
const assert = require('node:assert');

function readHeader(headers, name) {
  assert.ok(
    name in headers,
    new TypeError(`missing required header: ${name}`),
  );
  return headers[name];
}

try {
  readHeader({ accept: '*/*' }, 'authorization');
} catch (err) {
  console.log(err.constructor.name); // TypeError
  console.log(err.code);             // undefined
  console.log(err.message);          // missing required header: authorization
}

Inside the built-in test runner

Each ok() carries a message describing the rule, so a regression prints the broken rule instead of "the expression evaluated to a falsy value". Requiring node:assert/strict is the usual habit: in strict mode equal() and deepEqual() become their strict counterparts, while ok() is unchanged.

Example · javascript
const test = require('node:test');
const assert = require('node:assert/strict');

function slugify(input) {
  return input.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}

test('slugify produces a url-safe string', () => {
  const slug = slugify('Hello, Node 22!');
  assert.ok(slug.length > 0, 'slug must not be empty');
  assert.ok(/^[a-z0-9-]+$/.test(slug), `slug had illegal characters: ${slug}`);
  assert.ok(!slug.startsWith('-'), 'slug must not start with a hyphen');
});

// $ node --test
// ✓ slugify produces a url-safe string (1.2ms)

Discussion

  • Be the first to comment on this lesson.