Introduction to JavaScript anonymous functions
Introduction to JavaScript anonymous functions
An anonymous function is a function without a name. An anonymous function is often not accessible after its initial creation.
The following shows an anonymous function that displays a message:
let show = function () {
console.log('Anonymous function');
};
show();
In this example, the anonymous function has no name between the function keyword and parentheses ().
Because we need to call the anonymous function later, we assign the function to the show variable.
Using anonymous functions as arguments of other functions
We often use anonymous functions as arguments of other functions. For example:
setTimeout(function () {
console.log('Execute later after 1 second')
}, 1000);
In this example, we pass an anonymous function into the setTimeout() function. The setTimeout() function executes this anonymous function one second later.
Note that functions are the first-class citizens in JavaScript, so you can pass a function to another as an argument.
Immediately invoked function execution
If you want to create a function and execute it immediately after declaration, you can use the anonymous function like this:
(function() {
console.log('IIFE');
})();
How it works.
First, the following defines a function expression:
(function () {
console.log('Immediately invoked function execution'); })
Second, the trailing parentheses () allow you to call the function:
(function () {
console.log('Immediately invoked function execution'); })();
and sometimes, you may want to pass arguments into it, like this:
let person = {
firstName: 'John',
lastName: 'Doe'
};
(function () {
console.log(`${person.firstName} ${person.lastName}`);
})(person);
