When are anonymous functions useful in JavaScript

A named function can be called using its name and reused, while an anonymous function needs to be stored in a variable or property in order to be accessed more than once. Also, in stacks/traces, named functions help with debugging by showing the function name.

// Named function
function calculateArea(width, height) {
  return width * height;
}

// Anonymous function
const areaCalculator = function (width, height) {
  return width * height;
};

// Arrow function
const areaCalculator = (width, height) => width * height;

const area = areaCalculator(5, 3); // area will be 15

Both traditional anonymous functions and arrow functions in JavaScript allow you to define functions without explicitly naming them. However, they have some key differences in syntax, behavior, and use cases.

Feature Traditional Anonymous Function Arrow Function
Syntax function (args) { // body } (args) => expr or (args) => { body }
Return values Explicit return required Implicit return from expr for single-line, explicit return for multi-line
this binding Own this binding Inherits this from surrounding context
Use cases Explicit control over this, multi-line function bodies Concise, one-line functions, predictable this behavior
Arguments object Available Not available
Constructor functions Can be used as constructors Cannot be used as constructors

Arrow functions are not always interchangeable with traditional anonymous functions. You should be aware of these differences and use them appropriately. Both behave similarly when used as simple expressions that do not depend on the this, arguments, or new.target keywords, and do not need to be called as constructors or methods.

Anonymous functions are commonly used in IIFEs (Immediately Invoked Function Expressions), callbacks, closures, event handlers etc. They can avoid cluttering the namespace with transient function names that are only used once.

Assigning to a variable

You can assign an anonymous function to a variable in JavaScript by using the function keyword without a function name, followed by the function body. You can then call the function by using the variable name.

var square = function(x) {
  return x * x;
};

// Using arrow function
// var square = (x) => x * x;

console.log(square(5)); // 25

Passing as an argument

There is no difference between passing an anonymous function as an argument and passing a callback function as an argument in JavaScript. A callback function is just a name for a function that is passed to another function and executed when the other function finishes its task. A callback function can be either named or anonymous, depending on how you define it.

function greet(callback) {
  var name = "Bob";
  callback(name);
}

greet(function(name) {
  console.log("Hi, " + name);
}); // Hi, Bob

// Using arrow function
// function greet(callback) {
//   var name = "Charlie";
//   callback(name);
// }

// greet(name => console.log("Hey, " + name)); // Hey, Charlie

You can use an anonymous function as an event handler in JavaScript by passing it as an argument to the addEventListener method of the element. For example:

// Get a reference to the button element
var btn = document.querySelector(".btn");

// Add a click event listener with an anonymous function
btn.addEventListener("click", function(event) {
  // Log the event object to the console
  console.log(event);
});

Immediately invoked function expressions (IIFEs)

This is a JavaScript design pattern that declares an anonymous function and immediately executes it. It is often used to create a lexical scope for variables and avoid polluting the global namespace.

(function() {
  console.log("Hello, World!");
})();

// Using arrow function
// (() => {
//   console.log("Hello, World!");
// })();

This creates and invokes an anonymous function that prints “Hello, World!” to the console. The function is wrapped in parentheses to indicate that it is a function expression, not a function declaration. The second pair of parentheses is used to call the function immediately.