JavaScript Anonymous Functions


JavaScript, we can pass a function as a parameter when calling another function. This post is about anonymous functions, which will be discussed and illustrated after we discuss passing a function to another function.

In the code below we have two functions: sayToConsoleLog and myFunction. Here we pass the function sayToConsoleLog as the first parameter to the myFunction function. Not the return value of sayToConsoleLog, but sayToConsoleLog itself! The function sayToConsoleLog becomes the local variable someFunction within myFucntion, and myFucntion can call the function in this variable by issuing someFunction() (adding brackets).

// send to console log whatever is in the parameter word
function sayToConsoleLog(word) {
    console.log(word);
}
function myFunction(someFunction, value) {
    someFunction(value);
}
myFunction(sayToConsoleLog, "Hello from function1.js");
// We pass the function sayToConsoleLog as the first parameter
// to the myFunction function.

Anonymous Functions

Here below is an example from the book The Node Beginner Book written by Manuel Kiessling . 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 myFunction(someFunction, value) {
    someFunction(value);
}
myFunction(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.

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.

Node

We can test our code using Node.js. Here is a post called Node.js Hello World that explains how to do that.

Function passing makes an HTTP server work

Here is some code to make an HTTP server. It is again from the book: The Node Beginner Book. Below we pass to the createServer function an anonymous function.

var http = require("http");
http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

Below is the same code but refactored. It is easier to see what’s going on.

var http = require("http");
function onRequest(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}
http.createServer(onRequest).listen(8888);
Series Navigation<< JavaScript Functions IntroductionJavaScript Functions Part 1 >>

Leave a comment

Your email address will not be published. Required fields are marked *