A self-calling unnamed function is convenient because it does not have a name and you can write many such functions in one file and there will be no conflicts with names.
Syntax without parameters
( function(){} )();
or
( function(){}() );
Syntax with parameters
( function (param1, param2, ...){} )(meaning1, meaning2, ...);
Html
<html>
<body>
<script>
// Self-calling unnamed function with no parameters
( function(){ alert('Hello1'); } )();
// Self-calling unnamed function with no parameters
( function(){ alert('Hello2'); }() );
// Self-calling unnamed function with one parameter
( function(text) {alert(text);} )("Hello3");
</script>
</body>
</html>
In order not to write a new function with a name, but to call a self-calling unnamed function and not be a conflict with the names of other functions. [konec_stroki]That is, usually a self-calling unnamed function is some independent function of its own that does something.
Self-calling unnamed function used in advertising
Yandex
If you want your website to make money then you
Yandex offers to embed ads on your page.
Yandex for each site gives its own piece of advertising code. Here's an example of such ad code:
JavaScript
<!-- Yandex.RTB R-A-234410-1 -->
<div id="yandex_rtb_R-A-234410-1"></div>
<script type="text/javascript">
(function(w, d, n, s, t) {
w[n] = w[n] || [];
w[n].push(function() {
Ya.Context.AdvManager.render({
blockId: "R-A-234410-1",
renderTo: "yandex_rtb_R-A-234410-1",
horizontalAlign: false,
async: true
});
});
t = d.getElementsByTagName("script")[0];
s = d.createElement("script");
s.type = "text/javascript";
s.src = "//an.yandex.ru/system/context.js";
s.async = true;
t.parentNode.insertBefore(s, t);
})(this, this.document, "yandexContextAsyncCallbacks");
</script>
(function(w, d, n, s, t) ... this is the self-calling unnamed function.
That is, your page can have a lot of your functions. [konec_stroki] Calling a self-calling unnamed function will not call any of your functions (there will be no name conflict).