简体   繁体   中英

Why does a ! before a function not return boolean opposite value?

I was reading through this SO question . I sort of understand what's going on, but I'm confused why

!function foo() {
  console.log(true) ;
}()

doesn't return false .

!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:

"will also return the boolean opposite" makes me think that false should be returned. Why isn't it. alert(!true); //false

Without a return statement the function returns undefined . When you apply ! to undefined you get true .

Try

console.log(!function() { return true; }());

Note that the idiomatic use of ! before an IIFE is just that — an idiom. The fact that the ! operator has an effect on the return value almost always doesn't matter, because the return value is being completely ignored by the calling environment. Thus

+function() {
  // whatever
}();

is effectively exactly the same, even though the + unary operator is different from the ! unary operator.

Functions that have either an empty return statement or a non-existent one return the value undefined upon their invocation. Applying ! to "falsy" values such as 0, null, undefined return true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM