JavaScript Anonymous Function

Anonymous function in JavaScript; In this tutorial, i am going to show you about JavaScript anonymous function with the help of examples.

JavaScript anonymous functions

As the name suggest, An anonymous function is declared without any name.

Let’s, take an first example for javaScript anonymous function; as shown below:

let say = function () {
    console.log('Hello Anonymous function');
};
say();

Note that:- in the above given example; An anonymous function has without a name.

Using anonymous functions as arguments of other functions

Use anonymous functions as arguments of other functions; as shown below:

setTimeout(function () {
    console.log('Run after 5 second')
}, 5000);

In this example, we pass an anonymous function into the  js setTimeout() function. The setTimeout() function executes this anonymous function s second later.

Immediately Invoking an Anonymous Function

Want to execute an anonymous function immediately. You can use like this:

(function() {
    console.log('Hello');
})();

How Immediately Invoking an Anonymous Function Works

To declared a function like below:

(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 an anonymous function. You can use like this:

let ps = {
    firstName: 'John',
    lastName: 'Doe'
};
(function () {
    console.log(`${ps.firstName} ${ps.lastName}`);
})(ps);

Conclusion

In this tutorial, you have learned how to define Anonymous functions without names. and also, learned how to immediately invoked an anonymous function execution.

More JavaScript Tutorials

Leave a Comment