Java Script is one of the most popular & evergreen scripting languages for web & app development. This scripting language is used by millions of developers around the world. Do you “what is an anonymous function in javascript?”. many developers don’t know about it. if you have queries related to the anonymous function, then read this blog carefully.
Anonymous Function in Java Script
What is Anonymous Function in Java Script
According to Geekforgeeks, the Anonymous function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
If the interviewer asks you this question, your answer will be
- The anonymous function doesn’t have any name associated with it.
- We store this function with a variable.
- We can’t callback this function after declaration.
What is the Syntax of Anonymous Function in Java Script
// Function Body
}
How Anonymous Function in Java Script works?
Basically, if you want to execute a particular code only one time or do a self-execution then this function will be helpful to you.
- For only one time function run.
- A function does not have any name.
console.log(“hello world”);
};
Pass arguments with Anonymous Function
We can pass arguments in any function for better reusable code blocks. The anonymous function also has where you can pass arguments. see the code below 👇
*make sure you write code in between <script> </script> tag in HTML file.
var welcome = function (youtube) {
console.log(“Welcome to “, youtube);
};
welcome(“yesuus!”);
Anonymous Function with settimeout() function
If you want to execute any function or any block of code for a specific time, then you must use the setTime() function. Here you can try this with an anonymous function.
setTimeout(function () {
console.log(“Welcome to GeeksforGeeks!”);
}, 2000);
Self Execution of Anonymous Function
(function () {
console.log(“Welcome to Yesuus!”);
})();
Arrow functions with Anonymous Function
ES6 introduced a new and shorter way of declaring an anonymous function, which is known as Arrow Functions.
- You can use the Arrow function with Anonymous function.
var welcome = () =>
{
console.log(“Welcome to Yesuus!”);
}
welcome()
Follow our YouTube Video
If you have still queries on the anonymous function, watch this video. It will explain everything.