0

I am examining a minified script and see this pattern function (n) { .. }(jQuery) all over the place and it's used in chain like so: function (n) {..}(jQuery), !function (n) {..}(jQuery), !function (n) {..}(jQuery).

Pls note that it's not (function($) {})(jQuery); and I couldn't find any answer to my question.

Anyone has an idea? Thanks!

Gang Fang
  • 787
  • 7
  • 14
  • 3
    possible duplicate https://stackoverflow.com/questions/29256718/what-jquery-means-in-the-end-of-function – daremachine Jan 01 '20 at 23:35
  • @daremachine - what I am asking is different, there is no parentheses around `function (n) { .. }`. – Gang Fang Jan 01 '20 at 23:45
  • I dont see different. (jQuery) at the end is passed like n because its compiled. $ is more readable than n. – daremachine Jan 01 '20 at 23:46
  • Without enclosing parentheses (to make an IIFE), I don't believe this is valid syntax. Can you please give a link to the code you saw this in? – Robin Zigmond Jan 01 '20 at 23:48
  • 1
    `function (n) { .. }` is a [function expression](https://medium.com/@mandeep1012/function-declarations-vs-function-expressions-b43646042052) which lets you map a function to a variable. `function (n) { .. }(x)` immediately invokes the function. – max Jan 01 '20 at 23:48
  • 2
    That is, for the first one. With the initial `!` it's perfectly valid as an IIFE. The key is to have some token before the `function` keyword to make it a function expression, rather than a function declaration. – Robin Zigmond Jan 01 '20 at 23:50
  • 2
    @max that's true, but JS will parse any statement beginning with the word `function` as a function declaration, not an expression - anything coming after the closing `}` on the same line is invalid syntax. That's exactly why IIFE's always have enclosing parentheses, or sometimes a leading `!` - they're both "tricks" to make the engine parse it as an expression. – Robin Zigmond Jan 01 '20 at 23:54
  • @RobinZigmond - here is a part of the script https://codesandbox.io/s/pensive-keller-wbtm5?fontsize=14&hidenavigation=1&theme=dark. Please ignore the start and end of that. Thank you! – Gang Fang Jan 02 '20 at 00:15
  • 2
    `!function(n){}` and `(function(n){})` have the same effect so they can be considered equivalent for all intents and purposes. Hence the answers given on the linked question (and its duplicates) should answer yours. Particularly relevant: https://stackoverflow.com/a/23925102/218196 – Felix Kling Jan 02 '20 at 00:18
  • @FelixKling - didn't know they're equivalent. Thank you. – Gang Fang Jan 02 '20 at 00:21

1 Answers1

2

It's a function expression that's immediately called, which is more commonly known as an Immediately Invoked Function Expression.

The brackets are of course because this wouldn't work:

function(){}();

As that's invalid JavaScript. Following this, prepending the IIFE with the ! character allows missing out the prefix ( and suffix ), and is of course done by a minifer in most cases.