What is “assert” in JavaScript?

后端 未结 14 701
-上瘾入骨i
-上瘾入骨i 2020-12-04 05:03

What does assert mean in JavaScript?

I’ve seen something like:

assert(function1() && function2() && function3(), \"some          


        
14条回答
  •  粉色の甜心
    2020-12-04 05:22

    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.

提交回复
热议问题