What is an anonymous function in JavaScript?
There is actually no such thing as an “anonymous function” in JavaScript. The syntax you’re referring to is called a Function Expression. Function Expressions are created at the code execution stage, a basic Function Expression looks like this: 1 function () {}; But more usefully like… 1 2 3 var foo = function() { return true; }; And can have a name… 1 2 3 4 5 6 7 var foo = function foo() { return true; }; console.log( foo.name ); // > “foo” And can be Immediately Invoked… 1 2 3 4 5 6 7 8 9 (function foo() { return true; })(); // But this won’t create a Function Declaration, and won’t be available as foo(); foo(); // > “ReferenceError: foo is not defined” You might recognize this… 1 2 3 setTimeout( function() { // I am a Function Expression that will execute after 1 second }, 1000 ); This will help you understand the real world usage of Function Expression: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // This function accepts a number and a Function Expression