What does the exclamation mark do before the function?

后端 未结 9 2144
误落风尘
误落风尘 2020-11-21 04:47
!function () {}();
9条回答
  •  没有蜡笔的小新
    2020-11-21 05:07

    JavaScript syntax 101. Here is a function declaration:

    function foo() {}
    

    Note that there's no semicolon: this is just a function declaration. You would need an invocation, foo(), to actually run the function.

    Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

    The ! alone doesn't invoke the function, of course, but we can now put () at the end: !function foo() {}() which has higher precedence than ! and instantly calls the function.

    So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:

    (function(){})();
    

    Lastly, ! makes the expression return true. This is because by default all IIFE return undefined, which leaves us with !undefined which is true. Not particularly useful.

提交回复
热议问题