What is “assert” in JavaScript?

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

What does assert mean in JavaScript?

I’ve seen something like:

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


        
14条回答
  •  旧时难觅i
    2020-12-04 05:27

    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
    

提交回复
热议问题