Passing functions around
You can, for example, do something like this:
function say(word) {
console.log(word);
}
function execute(someFunction, value) {
someFunction(value);
}
execute(say, “Hello”);
Read this carefully! We pass the function say as the first parameter to the execute function. Not the return value of say, but say itself!
Thus, say becomes the local variable someFunction within execute, and execute can call the function in this variable by issuing someFunction() (adding brackets).
Of course, because say takes one parameter, execute can pass such a parameter when calling someFunction.
We can, as we just did, pass a function as a parameter to another function by its name. But we don’t have to take this indirection of first defining, then passing it – we can define and pass a function as a parameter to another function in-place:
function execute(someFunction, value) {
someFunction(value);
}
execute(function(word){ console.log(word) }, “Hello”);
We define the function we want to pass to execute right there at the place where execute expects its first parameter.
This way, we don’t even need to give the function a name, which is why this is called an anonymous function.
This is a first glimpse at what I like to call “advanced” JavaScript, but let’s take it step by step. For now, let’s just accept that in JavaScript, we can pass a function as a parameter when calling another function. We can do this by assigning our function to a variable, which we then pass, or by defining the function to pass in-place.