[javascript] What is “assert” in JavaScript?

What does assert mean in JavaScript?

I’ve seen something like:

assert(function1() && function2() && function3(), "some text");

And would like to know what the method assert() does.

This question is related to javascript assert

The answer is


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");
    }
}

check this:http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-quick-and-easy-javascript-testing-with-assert/

it is for testing JavaScript. Amazingly, at barely five or six lines, this code provides a great level of power and control over your code, when testing.

The assert function accepts two parameters:

outcome: A boolean, which references whether your test passed or failed

description: A short description of your test.

The assert function then simply creates a list item, applies a class of either “pass” or “fail,” dependent upon whether your test returned true or false, and then appends the description to the list item. Finally, that block of coded is added to the page. It’s crazy simple, but works perfectly.


Java has a assert statement, the JVM disables assertion validation by default. They must be explicitly enabled using command line argument -enableassertions (or its shorthand -ea),

while JavaScript supports console.assert(), it's just a logging method and won't interrupt current procedure if assertion failed.

To bring things together and satisfy various needs, here is a tiny js assertion lib.

_x000D_
_x000D_
globalThis.assert = (()=> {
  class AssertionError extends Error {
    constructor(message) {
      super(message);
      this.name = 'AssertionError';
    }
  }
  let config = {
    async: true,
    silent: false
  };
  function assert(condition, message = undefined) {
    if (!condition) {
      if (config.silent) {
        //NOOP
      } else if (config.async) {
        console.assert(condition, message || 'assert');
      } else {
        throw new AssertionError(message || 'assertion failed');
      }
    }
  }
  assert.config = config;
  return assert;
})();


/* global assert */
Object.assign(assert.config, {
  // silent: true, // to disable assertion validation
  async: false, // to validate assertion synchronously (will interrupt if assertion failed, like Java's)
});

let items = [
  {id: 1},
  {id: 2},
  {id: 3}
];
function deleteItem(item) {
  let index = items.findIndex((e)=> e.id === item.id);
  assert(index > -1, `index should be >=0, the item(id=${item.id}) to be deleted doesn't exist, or was already deleted`);
  items.splice(index, 1);
}

console.log('begin');
deleteItem({id: 1});
deleteItem({id: 1});
console.log('end');
_x000D_
_x000D_
_x000D_


In addition to other options like console.assert or rolling your own, you can use invariant. It has a couple of unique features:

  • It supports formatted error messages (using a %s specifier).
  • In production environments (as determined by the Node.js or Webpack environment), the error message is optional, allowing for (slightly) smaller .js.

As mentioned by T.J., There is no assert in JavaScript. However, there is a node module named assert, which is used mostly for testing. so, you might see code like:

const assert = require('assert');
assert(5 > 7);

assert() is not a native javascript function. It is a custom function someone made. You will have to look for it on your page or in your files and post it for anybody to help determine what it's doing.


Assertion throws error message if first attribute is false, and the second attribute is the message to be thrown.

console.assert(condition,message);

There are many comments saying assertion does not exist in JavaScript but console.assert() is the assert function in JavaScript The idea of assertion is to find why/where the bug occurs.

console.assert(document.getElementById("title"), "You have no element with ID 'title'");
console.assert(document.getElementById("image"), "You have no element with ID 'image'");

Here depending on the message you can find what the bug is. These error messages will be displayed to console in red color as if we called console.error();

You can use assertions to test your functions eg:

console.assert(myAddFunction(5,8)===(5+8),"Failed on 5 and 8");

Note the condition can be anything like != < > etc

This is commonly used to test if the newly created function works as expected by providing some test cases and is not meant for production.

To see more functions in console execute console.log(console);


If the assertion is false, the message is displayed. Specifically, if the first argument is false, the second argument (the string message) will be be logged in the developer tools console. If the first argument is true, basically nothing happens. A simple example – I’m using Google Developer Tools:

var isTrue = true;
var isFalse = false;
console.assert(isTrue, 'Equals true so will NOT log to the console.');
console.assert(isFalse, 'Equals false so WILL log to the console.');

It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):

http://chaijs.com/guide/styles/#assert


Here is a really simple implementation of an assert function. It takes a value and a description of what you are testing.

 function assert(value, description) {
        var result = value ? "pass" : "fail";
        console.log(result + ' - ' +  description); 
    };

If the value evaluates to true it passes.

assert (1===1, 'testing if 1=1');  

If it returns false it fails.

assert (1===2, 'testing if 1=1');

If you use webpack, you can just use the node.js assertion library. Although they claim that it's "not intended to be a general purpose assertion library", it seems to be more than OK for ad hoc assertions, and it seems no competitor exists in the Node space anyway (Chai is designed for unit testing).

const assert = require('assert');
...
assert(jqXHR.status == 201, "create response should be 201");

You need to use webpack or browserify to be able to use this, so obviously this is only useful if those are already in your workflow.


If using a modern browser or nodejs, you can use console.assert(expression, object).

For more information:


Previous answers can be improved in terms of performances and compatibility.

Check once if the Error object exists, if not declare it :

if (typeof Error === "undefined") {
    Error = function(message) {
        this.message = message;
    };
    Error.prototype.message = "";
}

Then, each assertion will check the condition, and always throw an Error object

function assert(condition, message) {
    if (!condition) throw new Error(message || "Assertion failed");
}

Keep in mind that the console will not display the real error line number, but the line of the assert function, which is not useful for debugging.


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

Word or function "assert" is mostly used in testing parts of application.

Assert functions are a short way of instructing the program to check the condition (also called "assertion") and if the condition is not True, it will throw error.

So let's see how it would look like in "normal code"

if (typeof "string" === "array") { throw Error('Error: "string" !== "array"'); }

With assert you can simply write:

assert(typeof "string" === "array")

In Javascript, there's no native assert function, so you have to use one from some library.

For simple introduction, you can check this article:

http://fredkschott.com/post/2014/05/nodejs-testing-essentials/

I hope it helps.