techStackGuru

Anonymous function javascript


An anonymous function is one that has no name. Anonymous functions can be sent as a parameter to other functions.


Lets see how to define anonymous function

(function () {
    //body
 }); 

Example

let display = function() {
    console.log('This is anonymous function');
};

display();
} 
Output
This is anonymous function

The anonymous function in the preceding example has no name between the function keyword and the parentheses.

Anonymous functions as arguments

setTimeout(function() {
    alert('anonymous function');
}, 5000); 

This will execute anonymous function every 5 seconds.

Invoked the function and executed it immediately

(function() {
    console.log('Function executed immediately');
})();

Execution with parameters

let print = {
    message: 'hello',
};

(function () {
    console.log(print.message);
})(print);  //hello 

Arrow Functions example

const print = function () {
    console.log('This is Anonymous function example');
};

print();     //This is Anonymous function example

Example

const Multiply = function (a, b) {return a * b};
const result = Multiply(2, 5);
console.log(result)  //10

ReferenceError

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.

Advantages of Anonymous function

  • A great benefit of anonymous functions is that they can be used to generate IIFE (Immediately Invoked Function Expression)
  • It is possible to pass anonymous functions as arguments to other functions.
  • Difference between Anonymous and Named functions in JavaScript

    In its simplest form, a "anonymous function" is a function with no name.

    Example of anonymous function

    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.

    Example of named function

    function print() {
       console.log ("Named function example");
    };
    
    print();
    Anonymous functionNamed 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.