What is anonymous function?

Anonymous function in JavaScript #javascript #webdevelopment #nodejs

How to define anonymous function?

function() {
// ...
}

Above function will show you error. To resolve this error you have to wrap this anonymous function into () . This function denotes as function as expression and it return function object. When you run the code you won’t get any output since this anonymous function is not getting called anywhere.

(function() {
console.log("this is anonymous function");
// ...
})

Immediately Invoked function

(function() {
console.log("this is Immediately invoked function");
// ...
})();

Here we are facing one problem, we can not call this function later on since it executes immediately. So how do we call this function later or how do we reuse anonymous function? I am going to explain you it below

Assigning anonymous function as variable?

let getName = function () {
console.log("My name is Ajay");
}

getName(); // call getName function

How to pass arguments to immediately invoked function?

// passing string as argument
(function(city) {
console.log("My current city is: " + city);
})('Mumbai');


// passing object as argument
(function() {
console.log("Person name is: " + person.name);
})(person={name: "ajay"});

Arrow function as anonymous function

// arrow function
let getAge = () => {
console.log("current age is 24");
}

getAge(); // call getAge

Passing anonymous function as argument

setTimeout(function() {
console.log("passing anonymous function as argument.");
}, 1000);

Thanks for reading this blog hope you have liked it. If yes then please clap and follow me for more blogs like this.

Did you enjoy this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!. Thanks for reading. Happy coding.