HTML DOM console.assert() Method


The HTML DOM console.assert() method is used to write a message to the console only if the first expression supplied to it is false. These messages are intended for user to see. The expression as well as the displaying message are sent as first and second parameters to the console.assert() method respectively.

Syntax

Following is the syntax for console.assert() method −

console.assert(assertion,msg);

Here, assertion is any expression that returns boolean true or false. The msg is a JavaScript string or an object. The assertion should be false to display the msg on console.

Example

Let us see an example for the console.assert() method −

<!DOCTYPE html>
<html>
<body>
<h1>console.assert example</h1>
<p>To view the message press F12 on the keyboard and go to the console tab.</p>
<script>
console.assert(document.getElementById("Sample"), "You have no element with ID 'Sample'
in this document");
</script>
</body>
</html>

Output

This will produce the following output −

In the console tab in developer tools you will see the following −

In the above example −

We have used the console.assert() method andthe getElementById() method to get the element that has id “Sample” associated with it. Since there is no element in our HTML document, it will return false.

The second parameter takes the message that it will display only if the first parameter returns false. The message in our case is “You have no element with ID ‘Sample’ in this document”, which is displayed in the console” −

console.assert(document.getElementById("Sample"), "You have no element with ID 'Sample' in this document");
raja
Published on 07-Aug-2019 17:56:18
Advertisements