9

I was taking a look through the bootstrap JS source and I came across something that I haven't seen before:

+function ($) { "use strict";
//...
}(window.jQuery);

What's the deal with the + in front of the function declaration? Is it to mitigate some potential minification problems or something?

I believe that placing a + before an expression type converts the result of the expression to a number, but I don't see what the relevance of that would be here.

Thanks for anybody who can shed some light on this for me.

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100

1 Answers1

9

That is so that the function declaration is a function expression, so that it can be executed immediately.

Usually that is done by putting parentheses around it:

(function ($) { "use strict";
//...
}(window.jQuery));

or:

(function ($) { "use strict";
//...
})(window.jQuery);
Mike Causer
  • 8,196
  • 2
  • 43
  • 63
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Interesting, so the + basically "evaluates" the code that follows it which turns it into an expression? Also, I assume there is no difference between using the + before the function declaration or putting parentheses around it (the function declaration)? – Adam Jenkins Sep 22 '13 at 21:06
  • @Adam:Yes, in both cases it's just to keep the syntax from being a regular function definition, and in both cases the result of the entire expression (i.e. the return value from the function) is ignored. – Guffa Sep 22 '13 at 21:16