SoFunction
Updated on 2025-04-06

About the confusing analysis of javascript function objects

The function object in js is a fascinating thing, but because it is too flexible and often confusing, I will post some code below:

Most people have abbreviation like this:
Copy the codeThe code is as follows:
function test () {}


How to write the entire book "Javascript Language Essence":
Copy the codeThe code is as follows:
var test = function () {}


Functions can be run immediately and assigned values:
Copy the codeThe code is as follows:

var test = function () {} () // test === undefined
var test2 = function () {return 'sugar cake'}() // test2 === 'sugar cake'

However, the abbreviation method of the function cannot be run directly, and the following code will report an error:
Copy the codeThe code is as follows:
function test() {}() // SyntaxError: syntax error


If you use the "()" run character to wrap it normally:
Copy the codeThe code is as follows:
(function test () {})();


In fact, this function name test is meaningless anymore. If it is removed, it becomes an anonymous function. It can still automatically execute the code inside the function. Commonly used anonymous function writing methods:
Copy the codeThe code is as follows:
(function () {})();


Anonymous functions can also be written in this way, which may be a little more beautiful:
Copy the codeThe code is as follows:
(function () {}());


Seeing this, are you going crazy when you first came into contact with JS? I once saw my project in C language and petrified immediately after seeing anonymous functions...