JavaScript basics (6): (immediately execute function)

JavaScript basics (6): (immediately execute function)

Lay a good foundation, check for omissions and fill vacancies

Foundation is the top priority

Execute function immediately

To execute a function immediately is to declare a function to be called immediately

This type of function is not declared, and is released immediately after one execution, suitable for initialization

var num = (funciton(a,b){
    var d = a + b
    return d
}(1,2))
 

Why use a pair of parentheses in the outermost layer to hold the function?

The first understanding

In order to be compatible with js syntax, syntax errors will be reported without parentheses

Therefore, the immediate execution function can be written in many ways, as long as it can pass the js syntax check.

The second understanding

Only expressions can be executed symbolically, function declarations cannot be executed immediately

Expressions that can be executed symbolically will automatically give up the function name

So the immediate execution function can be said to be an anonymous function

(function(){alrt(' ')} ()) // 
(function(){alrt(' ')}) () //
!function(){alrt(' ')}() // 
+function(){alrt(' ')}()
-function(){alrt(' ')}()
~function(){alrt(' ')}()
void function(){alrt(' ')}()
new function(){alrt(' ')}()