What does the exclamation mark do before the function?

后端 未结 9 1915
误落风尘
误落风尘 2020-11-21 04:47
!function () {}();
9条回答
  •  旧时难觅i
    2020-11-21 05:07

    The function:

    function () {}
    

    returns nothing (or undefined).

    Sometimes we want to call a function right as we create it. You might be tempted to try this:

    function () {}()
    

    but it results in a SyntaxError.

    Using the ! operator before the function causes it to be treated as an expression, so we can call it:

    !function () {}()
    

    This will also return the boolean opposite of the return value of the function, in this case true, because !undefined is true. If you want the actual return value to be the result of the call, then try doing it this way:

    (function () {})()
    

提交回复
热议问题