The community is working on translating this tutorial into Spanish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".
Anonymous Functions
So far in this tutorial, we have only created functions with a name. And you may think: Of course they have a name, otherwise we wouldn't know how to call them. And you're absolutely right - if you need to be able to manually call the function later on, it has to have a name.
However, there are many ways to use functions in JavaScript and some of them works great with a so-called anonymous function. The most common use case is probably when you need to pass in the function as a parameter to another function, often referred to as a callback function.
Using an anonymous function
In JavaScript for the webbrowser, we find at least two functions which allows you to pass in a callback function (more on those in the next article). They are called setTimeout() and setInterval(), and are frequently used by web developers. We will go into details about them later in this tutorial, but for now, they are here to demonstrate how an anonymous function can be used.
But first, let's see how it would look if we declared a named function and then passed that function to the setTimeout() function:
function SaySomething()
{
alert("Hello, world!");
}
setTimeout(SaySomething, 1000);
This is quite simple: We declare a function, called SaySomething(), and then we call the setTimeout() function, passing in two arguments: The name of the function that should be called, and the delay, in milliseconds, before it should happen. In this case, I have specified a delay of 1 second (1000 milliseconds), so when 1 second has passed, the SaySomething() function is called.
This works just fine, but very often, you won't need to call this function from anywhere else, so there's really no need for it to clutter up your code space. We can instead use an anonymous function, created on-the-fly and only for this specific call to setTimeout(). Here's how it looks:
setTimeout(function() { alert("Hello, world!"); }, 1000);
Notice that it looks like a regular function, but there's no name. This is a perfect example of where an anonymous function makes sense.
Function expressions
In JavaScript, functions are first-class citizens and not some kind of magical construct, as seen in other programming languages. This also means that you can assign a function to a variable, even an anonymous function, like this:
let func = function()
{
alert("Hello, world!");
};
func();
Notice how I declare a variable, called func, and then immediately I assign an anonymous function to it. This will now allow me to call this function simply by adding a set of parentheses to the variable name, as I do in the last line of the example.
As a little curiosity, the fact that you have now stored the function in a variable actually allows you to get the code of the function. If you run the below example, you will see this in action:
let func = function()
{
alert("Hello, world!");
};
alert(func);
Notice that I have now left out the parentheses when accessing the func variable in the last line, because we are using it as a value instead of a function.
Arrow functions
The arrow function expression syntax was introduced in the ES6 specification in 2015, so it is supported by all modern browsers today. It's really just a syntactic shortcut that you can use, for instance, when you need to use an anonymous function. Here's how it looks:
let func = () => alert("Hello, world!");
func();
As you can see, the name comes from the arrow-like operator =>. This syntax is now even shorter than it was before, but of course in this case, it's also an extremely simple function. Arrow functions can take parameters too, and by default, they will return the result of the statement, like this:
let add100 = n => n + 100;
alert(add100(42));
Notice that I have now omitted the parentheses, but added a parameter called n. You will also notice that I don't have to use the return keyword - if at all possible, JavaScript will simply return the result of the statement. In this example, the input (n) is returned, after 100 has been added to it.
On the other hand, if you have multiple parameters, you may NOT omit the parentheses, and if your function contains more than a single statement, you will have to use the return keyword as well. Here's an example:
let sum = (n1, n2) =>
{
if((isNaN(n1)) || (isNaN(n1)))
alert("Both parameters must be numbers!");
return n1 + n2;
};
alert(sum(40, 2));
Arrow functions are especially handy when used as callback functions. Here's a rewritten version of a previous example in this article, where we use an arrow function:
setTimeout(() => alert("Hello, world!"), 1000);
So you save a few keystrokes, compared to when you use the function-keyword version, but whether you prefer this shorter version or not is probably a matter of taste.
Please notice that arrow functions does NOT support the this keyword and should therefore not be used for object/class methods.
Summary
Anonymous functions can be quite handy when you don't need to reference them later on, for instance when you need to supply a callback function. They can be used with the function keyword, like a regular function, or in the shorter version with the arrow function syntax, depending on your personal preference.