Chapter 5: Functions

5.4 Advanced Function Concepts

Now that we are familiar with variable scope, let us move on to other more advanced function concepts. In Javascript, we can do some pretty fanciful stuff with functions. Some of these include:

    1. storing functions in a variable,
    2. passing a function as an argument to another function, and
    3. returning a function from another function.

Let’s look at what each of these means.

5.4.1 Storing Functions in a Variable

We learned in Chapter 3.1 that we can store a value in a variable. For instance, we can write

var userName = 'Peter';

We can also store a function in a variable. Add the code below to chap5.js to try this out.

var myFunction = function (a, b, c) {
    console.log('This function adds three numbers');
    return a + b + c;
};

On the right side of the assignment operator, we define the following function using the function keyword:

function (a, b, c) {

    console.log('This function adds three numbers');
    return a + b + c;
}

Notice that this is very similar to how we defined functions in the previous section, with the only exception that the function name is missing. When we assign a function to a variable, the function name is optional. Functions without names are known as anonymous functions. We assign this function to a variable called myFunction.

To call this function, we use the variable name (myFunction). Add the following line to chap5.js:

var sum = myFunction (1, 2, 3);
console.log('The sum is ' + sum);

On the first line, we use

myFunction (1, 2, 3);

to call the function. We then assign the result to a variable called sum. Finally, we use console.log() to display the value of sum.

If you refresh template.html now, you’ll get

This function adds three numbers
The sum is 6

as the output.

5.4.2 Passing a function as an argument to another function

Besides assigning a function to a variable, we can also pass a function as an argument to another function. We came across this concept when we discussed the sort() method for arrays in Chapter 3.3.

Let’s look at more examples.

First, let’s add a function called addNumbers() to chap5.js:

function addNumbers (x, y) {
    return x + y;
}

Next, add another function called calc() to chap5.js:

function calc (a, b, func) {
    console.log('The two numbers are ' + a + ' and ' + b);
    return func(a, b);
}

This second function has three parameters, a, b and func. It does two things. First, it displays a message regarding the values of a and b. Next, it calls the function func() and returns the answer.

To call the calc() function, we need to pass in a function for the third parameter. For instance, we can pass in the addNumbers() function. Add the following lines to chap5.js and run the code:

var result = calc(1, 2, addNumbers);
console.log('The result is ' + result);

We’ll get

The two numbers are 1 and 2
The result is 3

as the output.

In this example, addNumbers() is known as a callback function. A callback function is a function that is passed into another function as an argument and is called inside that function.

We tend to use them quite frequently when we write event handlers. We’ll discuss event handling in Chapter 10.

5.4.3 Returning a Function from Another Function

Next, let’s look at how we can return a function from another function.

Consider the code below:

var input = prompt('Enter 1 or any other key');

function showMessage(userInput){
    if (userInput === '1')
        return "You entered 1";
    else
        return "You did not enter 1";
}

var result = showMessage(input);
console.log(result);

We first prompt users to enter a value and store it in a variable called input.

Next, we define a function called showMessage(). This function has one parameter (userInput) and returns a string based on the value of userInput.

After defining the function, we call the function on line 10 and pass in the variable input as the argument. We then print the result of showMessage() on the next line.

This function is a typical example of how we can return a string from a function.

Now, we’re going to modify the code a bit to demonstrate how you can return a function from a function. To do that, just change line 5 to

return function (x, y, z) { console.log('The sum is ' + (x+y+z)); };

Here, we return an anonymous function – function (x, y, z) { console.log('The sum is ' + (x+y+z)); } – instead of a string. This function adds three numbers and displays the answer on the console.

Next, change line 7 to

return function (x, y) { console.log('The difference is ' + (x-y)); };

This function subtracts two numbers and displays the answer on the console.

Refresh template.html now and enter 1 when prompted.

What do you think you’ll get as the output?

You get

ƒ (x, y, z) { console.log('The sum is ' + (x+y+z)); }

right?

This is because the showMessage() function returns a function. In this case, it returns the first function because we entered 1. This function is stored in the variable result.

If you want to execute the function, you can add the following line:

result(1, 3, 7);

Refresh template.html and enter 1 when prompted. You’ll get an additional line

The sum is 11

in your output. Now refresh template.html again and enter 2 when prompted. You’ll get

The difference is -2

Notice that here, even though we passed in three arguments (1, 3 and 7), only the first two arguments are used (1 – 3 = -2) because the second function only requires two arguments.