JS: Exclamation sign before function. !function
What does !function mean?
This:
!function(param){body}(args)
It is equivalent to this for the function's side-effect:
(function(param){body})(args)
It means, define a function expression, and evaluate it right there.
The exclamation is the boolean “not” operator. [see JS: Boolean Operators]
The exclamation forces what follows into a expression.
People do this hack to save one character worth of source code file size.
!function ff(x) { console.log("hi", x); }(3); // is equivalent to the following, but for the function's side-effect only (function ff(x) { console.log("hi", x); })(3); // s------------------------------ // their return values are different console.log( !function ff(x) { console.log("hi", x); }(3), ); // hi 3 // true console.log((function ff(x) { console.log("hi", x); })(3)); // hi 3 // undefined
who promoted !function style in JavaScript
who is the first to promote !function style in javascript
ai answer
Ben Alman (in his 2010 blog post on IIFEs) is the person most associated with promoting the
!function(){}()style.Quick Context
The pattern
!function(){ /* code */ }()(or similar with~,+,-,void, etc.) is a compact way to write an Immediately Invoked Function Expression (IIFE). It forces thefunctionkeyword to be parsed as a function expression (instead of a declaration) so it can be executed right away, while saving a byte or two compared to the more common(function(){})()form. This was especially useful for minification in the pre-ES6 era.Why Ben Alman?
- In November 2010, he published the influential post "Immediately-Invoked Function Expression (IIFE)", where he:
- Coined/popularized the term IIFE (replacing the older "self-executing anonymous function").
- Explicitly listed and explained the unary operator variants, including:
!function(){ /* code */ }(); ~function(){ /* code */ }(); +function(){ /* code */ }(); // etc. - Noted they save bytes when you don't care about the return value.
- This post became the canonical reference for the technique. Many developers and articles still point back to it.
Earlier History
- The general IIFE pattern
(function(){})()existed before 2010 (used in libraries like jQuery, and discussed on comp.lang.javascript and Stack Overflow as early as 2008–2009).- The unary
!trick appeared in minified code (e.g., Sizzle, Twitter widgets) for size optimization, but Ben Alman was the one who clearly documented, explained, and promoted it as a deliberate style.In short: Others used it, but Ben Alman was the first major promoter who gave it visibility and a clear explanation in the broader JavaScript community. His post is still the go-to reference.
Ben Alman on JavaScript Immediately-Invoked Function Expression
- Immediately-Invoked Function Expression (IIFE)
- By Ben Alman
- https://benalman.com/news/2010/11/immediately-invoked-function-expression/
Note, Ben Alman is the creator of grunt.js , js task runner. Among other things.