Skip to content
Related Articles

Related Articles

Improve Article

Node.js console.assert() Method

  • Last Updated : 26 Jun, 2020

The console.assert() method is an inbuilt application programming interface of the console module which is used to assert value passed to it as a parameter, i.e. it checks whether the value is true or not and print an error message, if provided and failed to assert the value.

Syntax:

console.assert(value, messages)

Parameters: This method has two parameters as mentioned above and described below:

  • value: This parameter specifies the value to be asserted.
  • messages: It specifies the messages to be used as error messages. Any parameters passed along with value will be considered as message.

Return Value: This method doesn’t return anything if the value is true. If failed to assert the value then Assertion failed is logged followed by an error message, if provided in all subsequent parameters after value in util.format(). The output is used as an error message.

Below examples illustrate the use of console.assert() method in Node.js:



Example 1:




// Node.js program to demonstrate the   
// console.assert() Method
  
// Accessing console module
const console = require('console');
  
// Calling console.assert() method
console.assert(true, "error message 1");
console.assert(false, "error message 2");

Output:

Assertion failed: error message 2

Example 2:




// Node.js program to demonstrate the   
// console.assert() Method
  
// Accessing console module
const console = require('console');
  
// Calling console.assert()
var a = 10, b = 5;
  
console.assert(1 == 1, "error at 1==1");
console.assert(1 != 1, "error at 1==1");
console.assert(3 & 9, "error at 3&9");
console.assert(1 & 6, "error at 1&6");
console.assert(0 && 9, "error at 0&&9");
console.assert(1 && 8, "error at 1&&9");
console.assert(a % b == 1, "error at a%b==1");
console.assert(a > b, "error at a>b");
console.assert(b > a, "error at b>a");

Output:

Assertion failed: error at 1==1
Assertion failed: error at 1&6
Assertion failed: error at 0&&9
Assertion failed: error at a%b==1
Assertion failed: error at b>a

Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/console.html#console_console_assert_value_message




My Personal Notes arrow_drop_up
Recommended Articles
Page :