Events and anonymous functions

An anonymous function is a function that is not given a name. In JavaScript, the header is simply function() without the use of a name.

Why would you want to create a function without a name? Having a name is useful when you are going to use the function repeatedly. If a function is only going to be used once, however, a name isn't really necessary.

We used the following function in the previous example:

window.onload = startFunction;

function startFunction() {
    document.getElementById('replacehere').textContent='Replacement text.';
}

Equivalently, we could have used an anonymous function:

window.onload = function() {
    document.getElementById('replacehere').textContent='Replacement text.';
}

Anonymous functions have many uses, including for event listeners, which we will consider next.