JavaScript: Anonymous Function Example

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');


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() {

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}`);


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


My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of 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 from a starting stage. As well as demo example.

Leave a Reply

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