As the name suggests, anonymous functions are functions that have no name. They are different from the other JavaScript functions because they do not need traditional function definition like other functions do, instead they are created inline as part of an element.
Anonymous functions are nonreusable, short-lived, and generally used as arguments to other functions. They are also used as callbacks in asynchronous programming.
Since anonymous functions lack names, they are not reusable; however, they can be made reusable by assigning them to a variable. Their outputs are saved in the variables to which they are assigned.
Here's a basic example of an anonymous function in JavaScript used inside the map function:
const nums = [2,5,3,7,9];const squares = nums.map((num) => {return num*num});console.log(squares);
We have used an array function map
, it takes every element from the nums
array and provides it as an argument to the callback function, which is created inside map
since it takes a callback function as an argument.
(num) => {return num*num}
is an example of an anonymous function created without any name and used inside another function. It is returning square of each element in the nums
array, which is stored in the squares
variable.
Anonymous functions are nameless functions and are temporary in nature. They do not require the conventional definition structure. Typically are not designed for long-term use; however, their usability can be enhanced by assigning them to variables.
Free Resources