HTML DOM console.warn() Method


The HTML DOM console.warn() method is used to display a warning message in the console. In some browsers there is a small exclamation mark in console log for these warnings The console.warn() method will not interrupt your code execution. Developers can use the console.warn() method to give warnings to the user about some user action.

Syntax

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

console.warn(message)

Here, the message is a mandatory parameter of type string or object. It is displayed as a warning in the console view.

Example

Let us look at an example for the console.warn() method −

<!DOCTYPE html>
<html>
<body>
<h1>console.warn() Method</h1>
<p>Click the below button more than 4 times</p>
<button onclick="warning()" type="button">CLICK</button>
<script>
   var i=0;
   function warning(){
      i++;
      if(i>4)
      console.warn("You have clicked this button too many times");
   }
</script>
<p>Press F12 key to view the warning message in the console.</p>
</body>
</html>

Output

This will produce the following output −

On clicking the CLICK button more than 4 times and viewing the output in console tab.

In the above example −

We have created a button CLICK that will execute the warning() method upon being clicked upon by the user.

<button onclick="warning()" type="button">CLICK</button>

The warning() method increments the variable i. If the variable i gets greater than 4 the console.warn(msg) method is executed which displays the msg parameter as a warning −

var i=0;
function warning(){
   i++;
   if(i>4)
   console.warn("You have clicked this button too many times");
}

Updated on: 08-Aug-2019

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements