Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this JavaScript snippet mean? [duplicate]

I have not met this type of grammar before. What does it mean? To what technique is it related?

(function(fun) { 

})(myFunkyAlert);
like image 969
Shaobo Wang Avatar asked Aug 07 '26 14:08

Shaobo Wang


2 Answers

This is an anonymous function that will run as soon as it is declared. Its parameter is myFunkyAlert and inside the function it will be referenced as the fun variable.

The reason we usually write a function like that is to avoid conflicts, due to scoping.

Example:

var myFunkyAlert = "The funky alert";

(function(fun) { 
   alert(fun);
})(myFunkyAlert);

This will result in an alert with the message "The funky alert".

like image 179
Ibu Avatar answered Aug 10 '26 13:08

Ibu


You're defining an anonymous function and then calling it with myFunkyAlert as an argument.

like image 39
Noufal Ibrahim Avatar answered Aug 10 '26 13:08

Noufal Ibrahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!