What does the exclamation mark do before the function?

后端 未结 9 1891
误落风尘
误落风尘 2020-11-21 04:47
!function () {}();
9条回答
  •  逝去的感伤
    2020-11-21 04:49

    It returns whether the statement can evaluate to false. eg:

    !false      // true
    !true       // false
    !isValid()  // is not valid
    

    You can use it twice to coerce a value to boolean:

    !!1    // true
    !!0    // false
    

    So, to more directly answer your question:

    var myVar = !function(){ return false; }();  // myVar contains true
    

    Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):

    function () { return false; }();  // syntax error
    

提交回复
热议问题