JavaScript: Anonymous Functions

JavaScript: Anonymous Functions

In this tutorial, you will learn everything about JavaScript anonymous functions.

Intro to JavaScript anonymous functions

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

See following the following example:

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

say();

In this example, the anonymous function has without a name. It has assigned to a variable.

If you want to call the anonymous function later, assign the function to the say variable.

Using anonymous functions as arguments of other functions

We often use anonymous functions as arguments of other functions.

See the following example:

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

In some cases, you have declared a function and want to execute an anonymous function immediately. You can use like this:

See the following example:

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

How it works:

First of all, 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.

Leave a Reply

Your email address will not be published. Required fields are marked *