An anonymous function is one that has no name. Anonymous functions can be sent as a parameter to other functions.
(function () {
//body
});
let display = function() {
console.log('This is anonymous function');
};
display();
}
This is anonymous function
The anonymous function in the preceding example has no name between the function keyword and the parentheses.
setTimeout(function() {
alert('anonymous function');
}, 5000);
This will execute anonymous function every 5 seconds.
(function() {
console.log('Function executed immediately');
})();
let print = {
message: 'hello',
};
(function () {
console.log(print.message);
})(print); //hello
const print = function () {
console.log('This is Anonymous function example');
};
print(); //This is Anonymous function example
const Multiply = function (a, b) {return a * b};
const result = Multiply(2, 5);
console.log(result) //10
const res = function abc() {};
console.log(abc); // ReferenceError: abc is not defined
It is only possible to use the function name within the body of the function. If you use it outside of the function body, you will get an error.
In its simplest form, a "anonymous function" is a function with no name.
const print = function () {
console.log("Anonymous function example");
};
print();
When it comes to named functions, they refer to functions whose names follow the function keyword, which can be used as callbacks for the function.
function print() {
console.log ("Named function example");
};
print();
Anonymous function | Named function |
---|---|
Anonymous functions can only be called after they have been declared. | Name functions can be invoked before declarations. |
A function that is anonymous will never be hoisted. | A function that is named are hoisted. |