Open In App

What is the use of the console.assert() method in JavaScript ?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The console.assert() method in JavaScript is used for debugging purposes to check whether a given assertion is true. If the assertion is false, an error message is logged to the console along with a stack trace, helping developers identify and fix issues during development.

Syntax:

console.assert(assertion, message, ...args);

Parameter:

  • assertion: The expression or value to be tested. If it evaluates to false, the assertion fails.
  • message (optional): A message to be displayed in the console if the assertion fails.
  • args (optional): Additional arguments to be included in the error message, which can be useful for logging additional information.

Example: This example will show that it will throw error when assertion got false value.

function divide(a, b) {
console.assert(b !== 0, "Error: Cannot divide by zero");
return a / b;
}

console.log(divide(10, 2));
// Output: Assertion failed: Error: Cannot divide by zero
console.log(divide(10, 0));

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads