SoFunction
Updated on 2025-03-01

N ways to write anonymous functions in js

Anonymous functions have no actual name or pointer, how to execute them?
In fact, you can see the meaning of the brackets. The parentheses have a return value, that is, the return value of the function or expression in the parentheses. Therefore, the function return value in the parentheses is equal to the return value of the parentheses. It is not difficult to understand (function(){})() can execute a function without a name...
Regarding the writing of anonymous functions, it is very divergent.
The most common usage:
Copy the codeThe code is as follows:

(function() {
alert('water');
})();

Of course, parameters can also be included:
Copy the codeThe code is as follows:

(function(o) {
alert(o);
})('water');

Want to use chained calls with anonymous functions? Very simple:
Copy the codeThe code is as follows:

(function(o) {
alert(o);
return ;
})('water')('down');

You know all common anonymous functions, let’s take a look at the uncommon ones:
Copy the codeThe code is as follows:

~(function(){
alert('water');
})();//The writing is a bit cool~

Copy the codeThe code is as follows:

void function(){
alert('water');
}();//It is said that the most efficient ~

Copy the codeThe code is as follows:

+function(){
alert('water');
}();

Copy the codeThe code is as follows:

-function(){
alert('water');
}();

Copy the codeThe code is as follows:

~function(){
alert('water');
}();

Copy the codeThe code is as follows:

!function(){
alert('water');
}();

Copy the codeThe code is as follows:

(function(){
alert('water');
}());//A little bit of forced execution~

So many writing methods are sold at a low price~ Haha, in fact, some people consider the efficiency of writing methods. If possible, give me a data. I feel that these writing methods are efficient, but they should be very small (maybe wrong), and I will choose one of them casually~