JavaScript Console assert() Tutorial

In this section, we will learn what the console assert() method is and how to use it in JavaScript.

JavaScript Console assert() Method:

The `assert()` method is a way of sending a message to browsers console but base on the result of an expression!

Basically, this method takes two arguments. The first one is the expression which, at the end, will result in either true or false. If the result is true, then no message will be sent to the console. Otherwise, if the result was false, a message (which is the second argument of this method) will be sent to the console.

Console assert() Method Syntax:

console.assert(expression, message)

Console assert() Method Parameter:

The method takes two arguments:

  • The first argument is the expression that returns either `true` or `false` value.
  • The second argument is the message that we want to be sent to the browser console only if the result of the expression is false.

Console assert() Method Return Value:

There’s no return value for this method.

Example: using Console assert() method in JavaScript

const name = prompt("What is your name?");

console.assert(name, "Why didn't you set your name?!");

Output:

Assertion failed: Why didn't you set your name?!

Here, when the prompt dialog box appears, if we hit the cancel button, the value of the `name` identifier becomes null (which will be coerced into the value `false` in the expression of the `assert` method).

For this reason, the expression of the `assertion()` method resulted false and so the message is sent to the browser console.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies