brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: console.assert() only logs when your condition is false

Web-Development
~/tips/tip-console-assert-log-only-on-failure

console.assert(items.length > 0, 'cart is empty', items)

Prints an error to the console only when the checked condition fails.

Log lines like console.log('ok') fill the console with noise when everything is fine. An assertion stays quiet until something is wrong.

console.assert(items.length > 0, 'cart is empty', items)

console.assert(expression, object) logs an error only when the expression evaluates to false. The Chrome docs example checks x < y and passes an object with the values and a reason. When the expression is true, nothing is printed.

In a loop that runs a thousand times, that’s the difference between a readable console and a wall of text. A neighbour worth knowing is console.count(label), which logs how many times it was called with the same label from the same line.

Caveat: a failed assertion doesn’t stop the script. Execution carries on after the message, so don’t rely on it as a guard.

Both are in the Chrome console API reference with the others, such as console.group() for nesting related lines. An assertion for the unexpected and a counter for how often something runs cover most quick debugging.

Node follows the same idea. On Node 22.23.5, console.assert(false, 'cart is empty', { n: 0 }) prints Assertion failed: cart is empty { n: 0 } to stderr, and a line after it still runs. Passing a true condition prints nothing at all.

The Chrome page documents only the expression, object form, so how extra arguments get formatted is something I’d check in your own console before depending on it.

Further reading: Console API reference

More Web-Development tips ab -n 200 -c 10 https://example.com/ document.designMode = "on" function save(item) { Save draft spellcheck="false" All Web-Development tips (67) All topics

Link