This post will explain the assertion in JavaScript.
What is assert in JavaScript?
An assert function typically throws an error if the provided expression is not true. In JavaScript, for assertion checking, you can use Console API as it provides a “console.assert()” method. If the assertion is false, the console.assert() method prints the specified message; otherwise, “undefined” is displayed on the console if the condition is true.
How to Use assert in JavaScript?
The provided syntax can be used for invoking the console.assert() method:
It takes two parameters, “assertion” which is the expression that is evaluated whether it is true or false, and “msg” is the error message that will print if the condition is false.
Example 1
We will create two variables, “a” and “b”, and assign values “20” and “23”, respectively:
var b = 23;
Then, call the console.assert() method, which will check whether the difference between variables “a” and “b” is “3”:
The output displays an error message which indicates that the difference between variables “a” and “b” is not “3”, which means the condition is false:
In the other case, we will check the assertion that the sum of the variables “a” and “b” is “43”. As a result, the console.assert() method will do nothing; just print out “undefined” on the console:
Output
Example 2
Instead of printing a message, you can also print anything like an array, list of objects, and so on, Now, we will use the same variables created in the above example, and define an array of programming languages, that will print if the assertion condition is false:
Here, we will call the “console.assert()” method by passing an assertion and an array instead of error message as an argument:
The output displayed the lament of the created array because the assertion condition is false:
We have covered all the details about the assertion in JavaScript.
Conclusion
The assert function throws an error if the specified passed argument is not true. There is no standard assert in JavaScript. However, you can use the “console.assert()” method of the Console API in JavaScript. It is utilized for testing and debugging operations. In this post, we explained the assertion and console.assert() method in JavaScript.