console.assert()

The console.assert() method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

Note: This feature is available in Web Workers

Syntax

console.assert(assertion, obj1 [, obj2, ..., objN]);
console.assert(assertion, msg [, subst1, ..., substN]); // C-like message formatting

Parameters

assertion

Any boolean expression. If the assertion is false, the message is written to the console.

obj1 ... objN

A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output.

msg

A JavaScript string containing zero or more substitution strings.

subst1 ... substN

JavaScript objects with which to replace substitution strings within msg. This parameter gives you additional control over the format of the output.

Examples

The following code example demonstrates the use of a JavaScript object following the assertion:

const errorMsg = 'the # is not even';
for (let number = 2; number <= 5; number += 1) {
    console.log('the # is ' + number);
    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
    // or, using ES2015 object property shorthand:
    // console.assert(number % 2 === 0, {number, errorMsg});
}
// output:
// the # is 2
// the # is 3
// Assertion failed: {number: 3, errorMsg: "the # is not even"}
// the # is 4
// the # is 5
// Assertion failed: {number: 5, errorMsg: "the # is not even"}

See Outputting text to the console in the documentation of console for further details.

Specifications

Specification
Console Standard
# assert

Browser compatibility

BCD tables only load in the browser