What is “assert” in JavaScript?
There is no standard assert
in JavaScript itself. Perhaps you're using some library that provides one; for instance, if you're using Node.js, perhaps you're using the assertion module. (Browsers and other environments that offer a console implementing the Console API provide console.assert
.)
The usual meaning of an assert
function is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.
Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string (without having a type checking layer like TypeScript or Flow). So you might do:
assert(typeof argumentName === "string");
...where assert
would throw an error if the condition were false.
A very simple version would look like this:
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
Better yet, make use of the Error
object, which has the advantage of collecting a stack trace and such:
function assert(condition, message) {
if (!condition) {
throw new Error(message || "Assertion failed");
}
}
If using a modern browser or nodejs, you can use console.assert(expression, object)
.
For more information:
- Chrome API Reference
- Firefox Web Console
- Firebug Console API
- IE Console API
- Opera Dragonfly
- Nodejs Console API
The other answers are good: there isn't an assert function built into ECMAScript5 (e.g. JavaScript that works basically everywhere) but some browsers give it to you or have add-ons that provide that functionality. While it's probably best to use a well-established / popular / maintained library for this, for academic purposes a "poor man's assert" function might look something like this:
const assert = function(condition, message) {
if (!condition)
throw Error('Assert failed: ' + (message || ''));
};
assert(1 === 1); // Executes without problem
assert(false, 'Expected true');
// Yields 'Error: Assert failed: Expected true' in console