Lesson 13

Functions

Functions may seem simple in JavaScript, but beneath this simplicity lies enormous power. Gaining an understanding of this power is one of the keys to mastering the JavaScript language.

In Lesson 11, you created simple functions and invoked them from the console. For instance:

function isPositive(num) {
    return num >= 0;
}

In JavaScript, functions are objects so it is possible to assign them to variables:

f1 = function isPositive(num) {
    return num >= 0;
}

If you ask JavaScript the type of f1, it will respond as follows:

> typeof f1
"function"

This is another example of JavaScript being slightly disingenuous. Functions are not a distinct data-type; they are objects and therefore support all the features you will learn about in the next lesson, such as the ability to invoke methods on them.

Once you have assigned a function to a variable, you can invoke it via its variable name by appending brackets and parameters:

> f1(9)
true

In fact, you can use this variable wherever you can use any other variable in JavaScript; for instance, you can pass it as a parameter to another function.

Consider an example where you want to write a function that counts how many positive numbers are in an array. With the power of functions, you can do this by writing a generic algorithm as follows:

function countForArray(array, condition) {
    var result = 0;
    for (var i = 0; i < array.length; i++) {
        var element = array[i];
        if (condition(element)) {
            result++;
        }
    }
    return result;
}

This ...

Get HTML5, JavaScript, and jQuery 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.