What does the exclamation mark do before the function?

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

    Exclamation mark makes any function always return a boolean.
    The final value is the negation of the value returned by the function.

    !function bool() { return false; }() // true
    !function bool() { return true; }() // false
    

    Omitting ! in the above examples would be a SyntaxError.

    function bool() { return true; }() // SyntaxError
    

    However, a better way to achieve this would be:

    (function bool() { return true; })() // true
    

提交回复
热议问题