JavaScript console assert() Method

JavaScript console.assert() method is “used to write an error message to the console if the assertion is false. If the assertion is true, nothing happens.”

Syntax

console.assert(expression, message)

Parameters

  1. expression: It is required, and any expression.
  2. message: It is the message to write in the console.

Return value

It returns None.

Example 1: How to Use console.assert() Method

<script>
  const err_msg = "The # is not positive";
 
  for (let number = -2; number <= 2; number++) {
    console.log(`the # is ${number}`);
    console.assert(number >= 0, "%o", { number, err_msg });
  }
</script>

Output

How to Use console.assert() Method

Example 2: Writing an object to the console

let x;
let y = 2;

const obj = {firstname:"Niva", lastname:"Shah"};

console.assert(x + y == 11, obj);

Output

Writing an object to the console

JavaScript console.assert() method tests if the passed argument is a truthy or falsy value.

Browser compatibility

The console.assert() method is supported in all browsers like Internet Explorer, Mozilla Firefox, Microsoft Edge, Google Chrome browser, Safari, and Opera browser.

That’s it.

Leave a Comment