By Sebastian Otto


2010-09-20 21:21:51 8 Comments

!function () {}();

10 comments

@dmi3y 2013-10-01 18:10:29

There is a good point for using ! for function invocation marked on airbnb JavaScript guide

Generally idea for using this technique on separate files (aka modules) which later get concatenated. The caveat here is that files supposed to be concatenated by tools which put the new file at the new line (which is anyway common behavior for most of concat tools). In that case, using ! will help to avoid error in if previously concatenated module missed trailing semicolon, and yet that will give the flexibility to put them in any order with no worry.

!function abc(){}();
!function bca(){}();

Will work the same as

!function abc(){}();
(function bca(){})();

but saves one character and arbitrary looks better.

And by the way any of +,-,~,void operators have the same effect, in terms of invoking the function, for sure if you have to use something to return from that function they would act differently.

abcval = !function abc(){return true;}() // abcval equals false
bcaval = +function bca(){return true;}() // bcaval equals 1
zyxval = -function zyx(){return true;}() // zyxval equals -1
xyzval = ~function xyz(){return true;}() // your guess?

but if you using IIFE patterns for one file one module code separation and using concat tool for optimization (which makes one line one file job), then construction

!function abc(/*no returns*/) {}()
+function bca() {/*no returns*/}()

Will do safe code execution, same as a very first code sample.

This one will throw error cause JavaScript ASI will not be able to do its work.

!function abc(/*no returns*/) {}()
(function bca() {/*no returns*/})()

One note regarding unary operators, they would do similar work, but only in case, they used not in the first module. So they are not so safe if you do not have total control over the concatenation order.

This works:

!function abc(/*no returns*/) {}()
^function bca() {/*no returns*/}()

This not:

^function abc(/*no returns*/) {}()
!function bca() {/*no returns*/}()

@Carnix 2013-10-02 20:28:46

Actually, those other symbols do not have the same effect. Yes, they allow you to call a function as described, but they are not identical. Consider: var foo = !function(bar){ console.debug(bar); }("bat"); No matter what which of your symbols you put in front, you get "bat" in your console. Now, add console.debug("foo:",foo); -- you get very different results based on what symbol you use. ! forces a return value which isn't always desirable. I prefer the ({})() syntax for clarity and accuracy.

@oozzal 2013-05-06 14:49:07

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

@Ben 2020-01-23 19:27:42

This is incorrect. ! changes the way the runtime parses the function. It makes the runtime treat the function as a function expression (and not a declaration). It does this to enable the developer to immediately invoke the function using the () syntax. ! will also apply itself (ie negation) to the result of invoking the function expression.

@Zibri 2018-06-23 06:24:32

Let's save a few other bytes!

(() => {})()

example:

(() => {return "yeah"})()

@Martial 2019-01-08 15:21:45

(() => 'yeah')();

@Zibri 2019-01-09 14:22:25

yep. even better.

@Varatharaj 2017-09-05 10:05:04

Its just to save a byte of data when we do javascript minification.

consider the below anonymous function

function (){}

To make the above as self invoking function we will generally change the above code as

(function (){}())

Now we added two extra characters (,) apart from adding () at the end of the function which necessary to call the function. In the process of minification we generally focus to reduce the file size. So we can also write the above function as

!function (){}()

Still both are self invoking functions and we save a byte as well. Instead of 2 characters (,) we just used one character !

@For the Name 2018-11-05 15:13:02

This is helpful because often you'll see this in minified js

@antzshrek 2018-01-13 15:55:47

! will negate (opposite) whatever you're expecting as a result, i.e if you have

var boy = true;
undefined
boy
true
!boy
false

when you call boy, your result will be true, but the moment you add the ! when calling boy, i.e !boy, your result will be false. Which in other words you mean NotBoy, but this time it's basically a boolean result, either true or false.

That's the same thing that happens to the !function () {}(); expression, running only function () {}(); will flag you an error, but add ! right in front of your function () {}(); expression, makes it the opposite of the function () {}(); which should return you true. Example can be seen below:

function () {}();
SyntaxError: function statement requires a name
!function () {}();
true

@SoEzPz 2015-07-31 16:36:23

! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.

Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.

Instead, use the closing parenthesis and the BANG (!) if needed.

// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true

Other Operators that work...

+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1

Combined Operators...

+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1

@Neil 2011-04-13 20:02:29

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.

@gilly3 2011-07-28 16:58:06

+1. This really is the best answer here, and sadly, hardly upvoted. Obviously, ! returns boolean, we all know that, but the great point you make is that it also converts the function declaration statement to a function expression so that the function can be immediately invoked without wrapping it in parentheses. Not obvious, and clearly the intent of the coder.

@Tom Auger 2011-09-28 18:34:35

+1 This is the only answer that actually addresses WHY you would want to do this, and why one sees it used more than the negation of the return result would seem to warrant. The unary operator ! (also ~, - and +) disambiguates from a function declaration, and allows the parens at the end () to invoke the function in-place. This is often done to create a local scope / namespace for variables when writing modular code.

@Andrew Savinykh 2012-05-29 21:00:57

Why do you need to wrap a block of code into a function to execute it? Why instead of (function(){alert('bla');)})(); one can't simply write alert('bla');?

@Neil 2012-05-29 23:58:09

@zespri As Tom says, "This is often done to create a local scope / namespace for variables when writing modular code."

@Jure Triglav 2012-11-13 20:31:41

Another benefit is that ! causes a semi-colon insertion, so it's impossible for this version to be wrongly concatenated with a file that doesn't end with a ;. If you have the () form, it would consider it a function call of whatever was defined in the previous file. Tip of the hat to a co-worker of mine.

@George Mauer 2013-07-30 22:09:22

One more benefit - since there is literally no reason to do !function or }() other than an iife it makes it easy to scrape them out of code if need be. Not a major thing, but I've used that fact a few times.

@Carnix 2013-10-02 20:32:12

One downside is that ! forces a return value. Sometimes this matters, sometimes it does not - but if you happen to need to test the return value from the function and "undefined" is a valid possibility, you best not use the ! convention and instead use ({})() since it can return undefined. Consider: var foo = !function(bar){}("bat");console.log("foo:",foo);//=>true Verses: var foo = (function(bar){})("bat");console.log("foo:",foo);//=>undefin‌​ed

@Neil 2013-10-08 10:49:27

@Carnix var foo = breaks the statement/expression ambiguity and you can simply write var foo = function(bar){}("baz"); etc.

@Pablo Ezequiel Leone 2014-05-29 17:00:47

this is ugly to see... The long way round is not too long to choose the exclamation mark. This way could save to the developer a fraction of a second, and hours to understand to others.

@cookie monster 2014-08-30 18:30:00

@PabloEzequielLeoneSignetti: It has nothing to do with the length of the code irrespective of the spurious claim made in this answer. It's about using an operator that is not overridden for multiple purposes that can be interpreted different ways depending on its surrounding code. The ! is a prefix unary operator, and will only ever be interpreted as that. I doubt it would take any competent developer "hours to understand" this.

@cookie monster 2014-08-30 18:31:28

The "more readable" version is no more readable nor simpler to understand for someone who has never seen it before, which is why there are so many questions on SO asking what (function(){})() means.

@user1106925 2014-12-31 19:00:56

function foo() {} is not a statement. It's a declaration. Though some implementations incorrectly allow it to be used as a statement in some cases. The !function foo() {}; is an expression statement.

@totten 2015-07-30 14:27:56

jslint says, the proper way to do it is (function (){}());

@Dmitry S. 2015-10-04 10:31:18

This is usually done by minification/uglification scripts, where every single byte counts.

@Alex Fotios 2016-12-16 20:52:37

The precedence rule you mention is unrelated or rather symptomatic to why this works the way it does. Better answer is the one by @Michael Burr right below

@user1336321 2017-12-24 17:13:08

this is not part of 101 though

@Sebastian Gaweda 2019-05-02 13:38:04

IIFE stands for Immediately Invoked Function Expression in case anyone is wondering

@kamal 2016-03-06 09:56:36

Its another way of writing IIFE (immediately-invoked function expression).

Its other way of writing -

(function( args ) {})()

same as

!function ( args ) {}();

@Tobias 2017-10-16 14:31:58

Well, it's not exactly the same; the 2nd form negates the result of the function call (and then throws it away, because there is no value assignment). I'd strictly prefer the more explicit (function (args) {...})() syntax and leave that !function form to minification and obfuscation tools.

@gilly3 2010-09-20 21:25:09

It returns whether the statement can evaluate to false. eg:

!false      // true
!true       // false
!isValid()  // is not valid

You can use it twice to coerce a value to boolean:

!!1    // true
!!0    // false

So, to more directly answer your question:

var myVar = !function(){ return false; }();  // myVar contains true

Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):

function () { return false; }();  // syntax error

@Mark Fox 2013-03-11 00:55:10

For the sake of clarity for readers who may want to use an assignment with an immediately invoked function your example code var myVar = !function(){ return false; }() could omit the ! like var myVar = function(){ return false; }() and the function will execute correctly and the return value will be untouched.

@Triynko 2015-07-26 01:07:39

To be clear, you can use it once to coerce to Boolean, because it's a logical not operator. !0 = true, and !1 = false. For JavaScript minification purposes, you'd want to replace true with !0 and false with !1. It saves 2 or 3 characters.

@Michael Burr 2010-09-20 21:28:16

The function:

function () {}

returns nothing (or undefined).

Sometimes we want to call a function right as we create it. You might be tempted to try this:

function () {}()

but it results in a SyntaxError.

Using the ! operator before the function causes it to be treated as an expression, so we can call it:

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

(function () {})()

@Andrey 2010-09-20 21:32:47

who can ever need this?

@Andrey 2010-09-20 21:36:48

this is the only answer that explains case in the question, bravo!

@Skilldrick 2011-09-30 08:28:35

Your second code sample isn't valid JavaScript. The purpose of the ! is to turn the function declaration into a function expression, that's all.

@Anmol Saraf 2012-08-20 18:07:47

@Andrey The bootstrap twitter uses this in all there javascript (jQuery) plugin files. Adding this comment just in case others might also have the same question.

@Kristian 2014-03-31 22:01:00

d3.js also uses the !function syntax

@Mike Hedman 2014-08-27 20:10:47

@Andrey - The time that I have seen this was in minimized code, where saving that one extra byte is a win.

@1252748 2014-08-30 18:49:26

"If you want the actual return value to be the result of the call, then try doing it this way: (function () {})()". Why does that work like that? Thanks, I know this is from forever ago..

@Ronnie 2016-03-08 15:18:52

@thomas That snippet of code is simply shorthand for declaring a function and then calling it. So rather than function myFunction(){}; myFunction(); you can just say (function () {})(). This works because function names are optional and putting brackets around a function declaration make that function an expression, i.e. allow it to be immediately invoked. I know your question is now from forever ago

@1252748 2016-03-08 15:24:30

@Ronnie heheh yeah this snippet is far less mystifying to me than it was in 2014, but thanks for following up!

@Ronnie 2016-03-08 15:26:10

@thomas I've just realised its not really accurate to say function names are optional. They are required for non-anonymous functions, and for anonymous functions, although they are optional, their inclusion is redundant.

@OzzyTheGiant 2017-09-06 20:55:56

I just finished a workshop at teamtreehouse.com which references this SO question. A good reason to use self-executing anonymous functions is to modularize your code, thus preventing the global namespace from being cluttered. Also, when referencing a variable, it will limit itself to searching for the variable's value to the local scope, giving you a small performance boost.

Related Questions

Sponsored Content

68 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

38 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

37 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

25 Answered Questions

[SOLVED] What is the scope of variables in JavaScript?

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

26 Answered Questions

[SOLVED] Set a default parameter value for a JavaScript function

86 Answered Questions

[SOLVED] How do JavaScript closures work?

41 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 734567 View
  • 2709 Score
  • 41 Answer
  • Tags:   javascript jquery

21 Answered Questions

[SOLVED] What is the difference between call and apply?

Sponsored Content