JavaScript: Anonymous Function Example

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.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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