JavaScript Anonymous Functions
JavaScript Anonymous Functions
Donate Now
(https://www.javascripttutorial.net/donation/)
(function () {
//...
});
Note that if you don’t place the anonymous function inside the () , you’ll get a syntax error. The ()
makes the anonymous function an expression that returns a function object.
An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it
to a variable.
For example, the following shows an anonymous function that displays a message:
https://www.javascripttutorial.net/javascript-anonymous-functions/ 1/4
29/07/2022, 08:06 JavaScript Anonymous Functions
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 anonymous
function to the show variable.
In practice, you often pass anonymous functions as arguments to other functions. For example:
setTimeout(function() {
}, 1000);
If you want to create a function and execute it immediately after the declaration, you can declare an
anonymous function like this:
https://www.javascripttutorial.net/javascript-anonymous-functions/ 2/4
29/07/2022, 08:06 JavaScript Anonymous Functions
(function() {
console.log('IIFE');
})();
How it works.
(function () {
})
(function () {
})();
and sometimes, you may want to pass arguments into it, like this:
let person = {
firstName: 'John',
lastName: 'Doe'
};
(function () {
})(person);
Arrow functions
https://www.javascripttutorial.net/javascript-anonymous-functions/ 3/4
29/07/2022, 08:06 JavaScript Anonymous Functions
console.log('Anonymous function');
};
return a + b;
};
Summary
https://www.javascripttutorial.net/javascript-anonymous-functions/ 4/4