The assert
method in Node.js checks whether a given expression is true.
To use the assert
method, you will need to install the assert module using the command prompt, as shown below:
npm install assert
After the installation is complete, you will need to import the assert
module into the program, as shown below:
const assert = require('assert');
The prototype of the assert
method is shown below:
assert(value[, message])
Note: The
assert
method is an alias of the assert.ok() method.
The assert
method takes the following parameters:
value
: A required parameter that represents the expression to be evaluated.
message
: An optional parameter that holds the error message in case of an AssertionError. If this parameter is left empty, a default message is assigned.
If the provided expression evaluates to or false
, then the assert
function returns an assertion error and the program terminates; otherwise, execution continues as normal.
The code below shows how the assert
method works in Node.js:
const assert = require('assert');// evaluating first expressiontry{assert(10 > 5, "An assertion error was encountered.")console.log("No error.")}catch(error){console.log(error.message)}// evaluating second expressiontry{assert(10 > 50, "An assertion error was encountered.")console.log("No error.")}catch(error){console.log(error.message)}// evaluating third expressiontry{assert(10 - 10, "The expression evaluates to 0.")console.log("No error.")}catch(error){console.log(error.message)}
The code above uses different expressions to show the behavior of the assert
method.
In the first expression in line , 10 > 5
evaluates to true
, so the assert
method does not throw any errors. Therefore, only the try
branch of the try-catch
block executes.
In the second expression in line , 10 > 50
, evaluates to false
, so an error is thrown, which triggers the catch
branch of the try-catch
block. The code outputs the message associated with the error, i.e., the string provided as the message
parameter to the assert
method in line .
Similarly, in the third expression in line , 10-10
, evaluates to , so an error is thrown, which triggers the catch
branch of the try-catch
block. The code outputs the message associated with the error.
Free Resources