01.17.2022 - JavaScript/Console Assert Command

All posts

Posted On 01.17.2022

The built-in console comes with the console.assert method, which is pretty useful to write some tests in your code.

This method has the syntax of:

console.assert(assertion: bool, msg: string, obj1: any, obj2: any,...)

When the assertion expression returns false, the execution will be stopped, and the msg string will be printed out after the "Assertion failed:" message. You can format the msg just like how you format strings in languages like C++, using any obj followed after msg.

Otherwise, the execution continues.

For example:

const actual = 10;
const expected = 15;
console.assert(actual === expected, "Expected %d. Got %d", expected, actual);
console.log("All good!);

Result:

Assertion failed: Expected 15. Got 10

If we change actual = 15, the output on the screen will be:

All good!