JS: console.assert

By Xah Lee. Date: .

Console.assert

console.assert(expression)

prints nothing if expression eval to true by Boolean Constructor . Else, print “Assertion failed”.

// prints nothing, because all eval to true by boolean constructor

console.assert(true);

console.assert(3 === 3);

console.assert(21);

console.assert(Infinity);

console.assert(1/0);

Assert fail example

console.assert(false)
// Assertion failed
console.assert(3 === 4)
// Assertion failed
console.assert(null)
// Assertion failed

🛑 warning: if the expression in assert may not be the boolean literal value true but still pass the test. For example, console.assert(3). Better is console.assert(3 === true)

// this passes the test. but is not what we want.
console.assert(3)

// better
console.assert(3 === true)
// Assertion failed

we use console.assert often in this tutorial to verify JavaScript behavior.