Javascript
JavaScript Fundamentals -- Functions in JavaScript

Anonymous Functions

PRO

Anonymous functions in JavaScript are very similar to named functions, but they don't have a name identifier. Here's an example of an anonymous function:

function() {
  // do something
}

Now, you would never write a function exactly like that, because then you could never call it. Here's how you would create an anonymous function in a way that you could call it later on:

const sayHi = function() {
  // do something
}

sayHi(); 

This time, we stored that function in the sayHi variable. Then we can invoke the function as shown above as well. Invoking (or calling) the function like this looks just like if we had invoked a named function.

For the most part, you'll use anonymous functions as callback functions in your JavaScript work. An example of that looks like this:

const pizzas = ['Cheese', 'Pepperoni'];
pizzas.forEach(function(pizza) {
  console.log(pizza);
});

The .forEach method on the array loops over each item in the array. You need to provide a callback function there, and an anonymous function is perfect for this.

You can learn more about anonymous functions in this blog post.