Search code examples
javascriptiife

Why use the `+` (plus) or `!` (logical not) operator in an IIFE?


I know the typical form of an IIFE is:

(function(){/* code */})()

However, recently I found a new one:

!function(){/* code */}()
+function(){/* code */}()

which also work as IIFEs.

I think in the first ! makes the value a boolean, so the code is equivalent to true(), and in the second + makes the value a number, so the code is the same as NaN()? But true() and NaN() cannot possibly work, while the above two forms work well.

How do those two forms of IIFE work?


Solution

  • In the cases of !function() {}() and +function() {}() JavaScript will first evaluate the right handside of the given statement/IIFE and then cast the return value of the IIFE to a boolean in case of ! or to type number in case of +. If the IIFE returns a boolean ! will negate the return value.

    Example

    console.log(
      !function() {
        return "something";
      }()
    ); 
    
    /**
    !function() {
      return "something";
    }()
    
    evaluates to
    
    !"something" and not true() or false()
    
    lastly !"something" is equivalent to false
    */