-1

What is the difference between these two self invoking functions? The function does not work if the ! (not) symbol is added.

Please clarify if any one has clear understanding.

// first
(function( $ ) {
   // ...
})( jQuery );


// second
!function($){
    alert("test1");
}(jQuery), function(){
   alert("test2");
}(jQuery);
PCA
  • 1,677
  • 6
  • 28
  • 45
  • `function () {} function () {}`, remove `,` between functions bodies. – Justinas May 15 '15 at 10:12
  • What do you mean by "the function does not work"? What about it doesn't work? – James Donnelly May 15 '15 at 10:14
  • When I read "self invoking functions" I was kind of expecting recursive functions... – Chris Wesseling May 15 '15 at 10:14
  • It seems like syntax mistake in the 2nd code: it contains self invoking function **and** anonymous function definition separated by comma – hindmost May 15 '15 at 10:14
  • Can you please check this plugin jquery input mask - here this type of function is used. https://github.com/RobinHerbots/jquery.inputmask/blob/3.x/dist/jquery.inputmask.bundle.js – PCA May 15 '15 at 10:16
  • http://stackoverflow.com/questions/14129774/what-is-this-javascript-syntax-function – PCA May 15 '15 at 10:27

1 Answers1

-3
  1. !function () {} means negative function (similar to if (!someVar) {}), to make sure what result is before making it negative, function must be executed. So ! can be replaced with +.

  2. You have something wrong with //second, because you create two anonymous functions and between there is ,. I think you are getting syntax error in this place, so next function does not work (and is not executed, because no one is calling this function)

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • [the comma, makes a sequence of *expressions*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). So the second form works perfectly.. until you remove the `!` and turn the *expressions* that are there into (incomplete) *statements* – Chris Wesseling May 15 '15 at 11:17