In this tutorial,we will learn about Javascript anonymous functions.
Anonymous function:
- anonymous function in JavaScript is a function without a name.
- It is declared and used in a single line of code, and is often passed as an argument to another function or assigned to a variable.
Anonymous function Example JavaScript:
//Anonymous function passed as an argument to setTimeout
setTimeout(function() {
console.log("Hello World");
}, 1000);
In this example, an anonymous function is passed as an argument to the setTimeout
function, which sets a delay for the code inside the anonymous function to be executed. The anonymous function is declared inline, and its code will be executed after a delay of 1000 milliseconds.
Example2:
// Anonymous function assigned to a variable
var add = function(x, y) {
return x + y;
};
console.log(add(3, 5)); // 8
In this example, the anonymous function is assigned to a variable add
. This allows the anonymous function to be used multiple times in your code, just like any other function. The anonymous function takes two arguments x
and y
, and returns their sum. When add
is called with arguments 3
and 5
, it returns the result 8
.
Anonymous functions are useful in situations where you need a quick one-off function for a specific task, and you don’t need to give it a name for reuse elsewhere in your code. They are also commonly used in callback functions and event handlers, where a named function may not be necessary.
Thanks for Reading.