Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Node.js console.assert() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 prints 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 a 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. 

Example 1: The below example illustrates the use of a console.assert() method in Node.js

javascript




// 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: The below example illustrates the use of a console.assert() method in Node.js

javascript




// Node.js program to demonstrate the
// console.assert() Method
 
// Accessing console module
const console = require('console');
 
// Calling console.assert()
let 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&&8");
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
Last Updated : 06 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials