Cityscape
Girl

JavaScript

Named vs. Anonymous Functions

Easy
25 min

What Is a Named Function?

A named function is a function that has its own identifier. You define it separately and can refer to it by name whenever needed. For example:

function isEven(num) {
  return num % 2 === 0;
}

let numbers = [3, 7, 8, 11];
let firstEven = numbers.find(isEven);
console.log(firstEven);  // prints 8

Here, the function isEven is defined once and then passed as an argument to the find() method. This is clear and helps organize your code if you use the same function in multiple places.

What Is an Anonymous Function?

An anonymous function is defined without a name. Instead of writing a separate function declaration, you write the function directly where you need it. This is common when you only need the function once. For example:

let numbers = [3, 7, 8, 11];
let firstEven = numbers.find(function(num) {
  return num % 2 === 0;
});
console.log(firstEven);  // prints 8

In this example, the function is written directly inside the find() method call. Because it doesn’t need a name (since you won't call it elsewhere), it is called an anonymous function.

Advantages of Each Approach

Named Functions

  • Clear and reusable when you need the same logic in multiple places.
  • Easier to debug, as they have an identifier.

Anonymous Functions

  • More concise, especially when the function is used only once.
  • Keeps related code together, making it easier to read in many cases.

Exercises

Use a Named Function for Finding an Element

  • Create an array named numbers with the values [1, 3, 5, 6, 7] using let.
  • Write a named function called isEven that takes a number and returns true if it is even.
  • Use numbers.find() with isEven to find the first even number and store it into a variable called firstEven.
  • Print the result using console.log.

Use an Anonymous Function Inline

  • Using the same array numbers from the previous exercise, use an anonymous function (written inline) with numbers.find() to find the first even number and store it into a variable named firstEven.
  • Print the value of firstEven using console.log.

hakatemia pro

Ready to become an ethical hacker?
Start today.

As a member of Hakatemia you get unlimited access to Hakatemia modules, exercises and tools, and you get access to the Hakatemia Discord channel where you can ask for help from both instructors and other Hakatemia members.