In a previous article, we've introduced JavaScript functions and how to use them. We've seen that a function has a name and parameters.

function sayHello(name) {
  return "Hello " + name;
}
console.log(sayHello("Paul")); // "Hello Paul"

Declaring an anonymous function

So, what is an anonymous JavaScript function? Just as the name implies, it is a function without a name. The simplest example is assigning a function to a variable:

let sayHello = function(name) {
  return "Hello " + name;
}

Whilst the function doesn't have a name, because we've assigned it to a variable, we can use still call it when required:

console.log(sayHello("Paul")); // "Hello Paul"

Functions as parameters

A very common usecase for anonymous functions are as arguments for JavaScript functions, for example `setTimeout`:

setTimeout(function sayHello() {
  console.log("Hello World");
}, 1000);

`setTimeout` takes 2 arguments: a function to execute, and an interval in miliseconds after which the function is executed. In the example above, we've passed a function named `sayHello`, but, even though we've given it a name, the function won't be available to use:

sayHello(); // ReferenceError: sayHello is not defined 

Next Steps