What is Assertion in JavaScript?
In JavaScript, assertions refer to expressions that verify if a specified condition holds true. They are frequently utilized during debugging and testing to confirm that particular conditions or assumptions regarding your code are accurate.
In straightforward terms, assertions enable us to define the boundaries that mark the start and end of lines, words, and various patterns, allowing us to signify the possibility of a match. This encompasses techniques such as look-ahead, look-behind, and conditional expressions.
What is the console.assert in JavaScript?
In JavaScript, the console.assert function serves the purpose of outputting a message intended for the user. These methods are utilized within the console in JavaScript.
In straightforward terms, the console.assert function in JavaScript is used to show an error message or a designated message in the console within the inspect element when a specified condition fails to hold true or when an expression evaluates to a False boolean value. This feature is advantageous since there exists an alert function to present errors within the user interface of the webpage.
In JavaScript, the method console.assert outputs a message only when the expression provided to it evaluates to false. This method accepts two arguments: the first argument represents the expression, while the second argument is the message that will be displayed.
Syntax
The syntax for the JavaScript console.assert function is as follows:
console.assert (expression, message)
Parameters
The console.assert function in JavaScript accepts two arguments, which include:
Expression
In JavaScript, the expression serves as the mandatory argument for this method. It signifies any evaluable expression. When this method is executed within a program, the moment the execution arrives at the expression parameter, the expression is evaluated first. Following this evaluation, a subsequent message is then displayed on the user console based on the outcome of that expression.
By utilizing this expression, we are restricted to outcomes that yield only Boolean values. In cases where the expression evaluates to true, no message will be printed. Conversely, if the expression evaluates to false, the message will be displayed on the console.
Message
In JavaScript, the message serves as a mandatory argument for the console.assert function. It encompasses the information that is intended to be displayed in the console.
In JavaScript, when the execution flow encounters the message parameter, this parameter operates based on the outcome of the expression parameter. If the evaluation of the expression yields true, the message will not be displayed. Conversely, if the evaluation results in false, the message will be output to the console.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The console.assert() Method</title>
<style>
h1 {
color: red;
}
h2 {
font-family: Impact;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>Example for:</h1>
<h2> The console.assert() Method</h2>
<p>To view the message in the console press the F12
key on your keyboard.</p>
<script>
console.assert(document.getElementById("MyElement"),
"There is no element with the ID 'MyElement'");
</script>
</body>
</html>
Explanation:
In the preceding illustration, we have established a straightforward H1 tag along with an H2 tag, which will assist us in presenting the assertion. Within the style tag, we have specified the font color, font family, and text alignment for the different tags.
Now, let’s examine the script segment; our initial step involved identifying the MyElement ID and verifying its existence within the DOM. If the ID is not found, we output a straightforward assertion message indicating that the specified ID is absent from the DOM. To address such scenarios where we need to confirm the completion of a specific condition, we can utilize the console.assert function.
Output:
Example 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>console.assert() method</title>
<style>
h1 {
color: rgb(129, 17, 235);
}
h2 {
font-family: Impact;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>Example for:</h1>
<h2>DOM console.assert( ) Method to display object</h2>
<p>To view the message in the console press the F12 key on
your keyboard. </p>
<script>
var MyElement = { Product: "Coca Cola", Type: "Beverage" };
console.assert(document.getElementById("MyDemo"), MyElement);
</script>
</body>
</html>
Explanation:
In the preceding example, we have established a basic h1 and h2 tag to present the assertion. Within the style tag, we have specified the font color, font family, and text alignment for the different tags.
Within the script segment, we focused on the MyDemo identifier and confirmed its existence within the Document Object Model (DOM). This check yields a Boolean outcome (either true or false) for the message parameter. Furthermore, we set up an object called MyElement, which comprises two pairs of keys and values: product and its corresponding type. Subsequently, we assessed whether the ID was present in the DOM; if it was not found, we refrained from executing any operations. Conversely, if the ID was found, we utilized the JavaScript console.assert function to display the object.
Output:
Types of Assertions in JavaScript
Boundary-type assertion
Input boundary beginning assertion
In JavaScript, the caret symbol (^) serves to indicate the start of the input. When the multiline flag is activated, it can also find a match right after a line break character. For instance, if we apply the regex /^A/, it will not match the "A" in "an A", but it will successfully match the initial "A" in "An A".
Input boundary end assertion
It precisely aligns with the conclusion of the input. When the multiline option is activated, it additionally aligns strictly right before a line break character. For instance, /t$/ distinctly fails to match the "t" in "eater," yet it unmistakably matches it in "eat."
Word boundary assertion
A word boundary refers to the location where a word character is adjacent to a non-word character, for instance, the space that separates a letter from another letter. It is crucial to understand that when a word boundary is matched, it does not become part of the match itself, indicating that its length is effectively zero.
Example
const fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"];
// Select descriptions that contains 'en' or 'ed' words endings:
const enEdSelection = fruitsWithDescription.filter((descr) =>
/(en|ed)\b/.test(descr),
);
console.log(enEdSelection); // [ 'Red apple', 'Green Avocado' ]
Non-word boundary assertion
It corresponds to a non-word boundary. This is an instance in which the characters preceding and following the boundary are of the same category: they must either both be classified as words or both as non-words. For instance, this occurs between two alphabetic characters or between two whitespace characters.
The start and finish of a string are regarded as non-word characters. Similarly, the matched non-word boundary is excluded from the overall match as well.
Other Assertions
Lookahead assertion
It aligns with x solely when x is succeeded by y. For instance, the expression /Rohit (?=Spart)/ will match Rohit exclusively if it is immediately followed by Spart. Similarly, the pattern /Rohit(?=Spart|Frost) will identify Rohit only when it is succeeded by either Spart or Frost.
Example
const regex = /First(?= test)/g;
console.log("First test".match(regex)); // [ 'First' ]
console.log("First peach".match(regex)); // null
console.log("This is a First test in a year.".match(regex)); // [ 'First' ]
console.log("This is a First peach in a month.".match(regex)); // null
Negative lookahead assertion
It successfully identifies x only in instances where x is not succeeded by y. For instance, the regex /\d+(?!\.)/ will match a numerical value only if it is not immediately followed by a decimal point. In the case of /\d+(?!\.exec('3.141')) it captures 141 but excludes 3.
Lookbehind assertion
"It identifies 'x' solely when it is preceded by 'y'. For instance, the expression /(?<=Rohit)Spart/ successfully matches 'Spart' only if it follows 'Rohit'. Similarly, the pattern /(?<= Rohit|Tom)Spart matches 'Spart' exclusively when it is preceded by either 'Rohit' or 'Tom'. Nevertheless, 'Rohit' and 'Tom' do not appear in the results of the match."
Advantages of using Assertion in JavaScript
- In JavaScript, assertion helps us to minimize the time to debug the code.
- In JavaScript, it can be reused across multiple projects if developed with the intent of keeping it in mind.
- It also helps us to improve the error detection.
- In JavaScript, assertion provides better monitoring of the design and helps in easier debugging of test failures.
- We can use assertion for both dynamic simulation as well as in formal verification of the design in JavaScript.
Conclusion
In summary, the console.assert function in JavaScript serves as a means to send messages to the user. These messages appear in the console. The console.assert method requires two parameters: the first is the expression, and the second is the message. Both parameters are essential for the console.assert function to operate correctly in JavaScript.
The assertion method in JavaScript includes an expression parameter that evaluates to a Boolean value, either true or false. Additionally, the message parameter can be a string or an object that gets displayed in the console. Several contemporary web browsers that support the console.assert method include Internet Explorer, Mozilla Firefox, Microsoft Edge, Google Chrome, Safari, and the Opera browser.