Node.js Reference ยท Globals and Console
Node.js console.assert() method
Reference for console.assert() in Node.js: it prints an Assertion failed message to stderr only when the condition is falsy and never throws or stops the program.
console.assert(value, ...messages) checks value. If it is truthy, nothing happens. If it is falsy, Node writes Assertion failed (followed by your message, if any) to standard error.
It does not throw and it does not stop the program, which makes it different from assert.ok() in the node:assert module. Think of it as a conditional log line for sanity checks while debugging.
console.assert(items.length > 0, 'no items for order %d', orderId);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
console.assert(value: any, ...message: any[]): void
| Name | Description |
|---|---|
value |
Condition to test. Any falsy value (false, 0, '', null, undefined, NaN, 0n) counts as a failure. |
...message |
Optional values formatted like console.log(). If the first is a string it may use %s-style specifiers. |
Returns: undefined.
Output format: Assertion failed alone, or Assertion failed: your message. If the first message item is not a string, Node prints Assertion failed followed by all items, joined with spaces.
Usage notes
- Never throws. Do not use it to validate input or enforce invariants; code after it still runs with bad data. Use
node:assertor explicitthrowfor that. - Writes to stderr, so redirecting stdout does not hide the failures.
- Message arguments are evaluated even when the check passes, because JavaScript evaluates arguments before the call. Avoid expensive expressions in the message of hot code.
- Handy for temporary debugging inside loops where only the unexpected case should produce output.
- Browsers differ: their
console.assertshows a red error line with a stack trace; Node prints only the text. - No stack trace is printed. Add
console.trace()if you need to know where the failed check was. - Tests:
node:testandnode:assertgive structured failures;console.assertfailures do not fail a test.