Anonymous function in JavaScript

habtesoft
2 min readApr 3, 2023

In JavaScript, an anonymous function is a function without a name. Instead, it is defined as an expression and assigned to a variable, or passed as an argument to another function. Anonymous functions are also sometimes called “function expressions”.

Not a Medium member? Read this article here

Anonymous functions are commonly used in JavaScript for a variety of purposes, such as:

  • Creating closures
  • Defining event handlers
  • Passing functions as arguments to other functions
  • Defining callbacks for asynchronous operations
  • Creating IIFEs (Immediately Invoked Function Expressions)

Here’s an example of an anonymous function:

const myFunc = function() {
console.log('Hello world!');
}

myFunc(); // Output: "Hello world!"

In this example, we’ve defined an anonymous function and assigned it to the variable myFunc. We can then call the function using the variable name, just like we would with a named function.

Anonymous functions can also take arguments and return values, just like named functions:

const addNumbers = function(x, y) {
return x + y;
}

const result = addNumbers(5, 7);
console.log(result); // Output: 12

--

--

habtesoft
habtesoft

Written by habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat

No responses yet