JavaScript  

Anonymous vs Arrow Functions

Introduction

JavaScript gives you many ways to define and use functions. Two powerful but often confusing types are anonymous functions and arrow functions.

In this article, we’ll explore what they are, when to use them, and how they differ.

What Is an Anonymous Function?

An anonymous function is a function without a name. You typically use it when a function is needed only once or doesn’t need to be reused by name.

Let’s compare a named function vs an anonymous function.

Named Function

Here, the function has a name: greet. You can call it anywhere in your code by that name.

function greet(name) {
    return `Hello, ${name} from named function.`;
}
console.log(greet('Alex')); // Hello, Alex from named function.

Anonymous Function

Here, the function has no name.

function () {
  console.log("I'm anonymous!");
}

How to Use Anonymous Functions?

Step 1. Assigned to a Variable (common for reuse).

The following function is created inline and assigned to the variable greetAnonymous. Same logic as before, but the function itself doesn’t have a name and can’t be called directly without the variable.

const greetAnonymous = function(name) {
    return `Hello, ${name} from Anonymous function.`;
};
console.log(greetAnonymous('Alex')); // Hello, Alex from Anonymous function.

However, you're not strictly married to a variable name here! Anonymous functions can be used anywhere.

Here are two other common ways anonymous functions are used.

Step 2. Passed as an Argument (like in callbacks).

setTimeout(function () {
  console.log("This runs after 5 seconds");
}, 5000);

An anonymous function can be passed as an argument to another function to be executed later, often used for callbacks.

Here setTimeout() function schedules an anonymous function to run once after a 5-second delay.

Step 3. Immediately Invoked (IIFE).

(function () {
  console.log("This runs immediately");
})();

An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it's defined, without needing to be called later.

Step 4. With Array Methods.

You can pass anonymous functions to other array methods, such as .map(), .filter(), and .reduce() for more complex operations.

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function (num) {
  return num * 2;
});
console.log(doubled); // [2, 4, 6, 8, 10]
const evenNumbers = numbers.filter(function (num) {
  return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4]
const sum = numbers.reduce(function (acc, num) {
  return acc + num;
}, 0);
console.log(sum); // 15

What Is an Arrow Function?

An arrow function is a shorter way to write functions. It’s anonymous by nature.

// One parameter
const double = n => n * 2;
console.log(double(5)); // Output: 10

// Multiple parameters
const add = (a, b) => a + b;
console.log(add(3, 4)); // Output: 7

// No parameters
const sayHi = () => "Hi";
console.log(sayHi()); // Output: "Hi"

// Block body (explicit return)
const multiply = (a, b) => {
  const result = a * b;
  return result;
};
console.log(multiply(2, 3)); // Output: 6

Since arrow functions are anonymous in nature, that means we should be able to rewrite everything above using arrow functions.

// 1. Arrow function assigned to a variable (anonymous function)
const greetArrow = name => `Hello, ${name} from Arrow function.`;
console.log(greetArrow('Alex')); // Output: Hello, Alex from Arrow function.

// 2. Arrow function used as a callback in setTimeout (anonymous function passed directly)
setTimeout(() => {
  console.log("This runs after 5 seconds");
}, 5000);

// 3. Immediately Invoked Arrow Function Expression (IIFE)
(() => {
  console.log("This runs immediately");
})();

// 4. Arrow function used with `map` to double the numbers (anonymous function)
const numbers = [1, 2, 3, 4, 5];

// Doubled numbers using map with an arrow function
const doubledArrow = numbers.map(num => num * 2);
console.log(doubledArrow); // [2, 4, 6, 8, 10]

// 5. Arrow function used with `filter` to get even numbers (anonymous function)
const evenArrow = numbers.filter(num => num % 2 === 0);
console.log(evenArrow); // [2, 4]

// 6. Arrow function used with `reduce` to calculate the sum (anonymous function)
const sumArrow = numbers.reduce((acc, num) => acc + num, 0);
console.log(sumArrow); // 15

Real-Life Example: Shopping Cart

You’re building a shopping cart app that.

  • Filters affordable items
  • Calculates total price
  • Applies discounts
const items = [
  { name: "Mouse", price: 25 },
  { name: "Laptop", price: 999 },
  { name: "Keyboard", price: 50 },
  { name: "Monitor", price: 200 }
];
// Filter affordable items using an anonymous function
const affordable = items.filter(function(item) {
  return item.price < 100;
});
console.log("Affordable items:", affordable);
// Calculate total price using an arrow function
const total = items.reduce((sum, item) => sum + item.price, 0);
console.log("Total price:", total);
// Apply a discount using an arrow function
const applyDiscount = (price, discount) => price - (price * (discount / 100));
// Apply a 10% discount to the total price
const discountedTotal = applyDiscount(total, 10);
console.log("Total after discount:", discountedTotal);

Bonus Examples

1. Anonymous in Event Listeners

document.getElementById("btn").addEventListener("click", function() {
  alert("Clicked!");
});

2. Arrow inside Object Method

const user = {
  name: "Sam",
  greet: () => {
    console.log("Hi, " + this.name); // 'this' won't be 'user'
  }
};

Summary

  • Anonymous functions are unnamed functions used in callbacks, assignments, or temporary logic.
  • Arrow functions are concise, useful in short expressions.
  • Both can be exported, passed around.