Skip to Content
JavaScript: The Good Parts
book

JavaScript: The Good Parts

by Douglas Crockford
May 2008
Intermediate to advanced
172 pages
4h 54m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Good Parts

Methods

JavaScript provides a set of methods for acting on arrays. The methods are functions stored in Array.prototype. In Chapter 3, we saw that Object.prototype can be augmented. Array.prototype can be augmented as well.

For example, suppose we want to add an array method that will allow us to do computation on an array:

Array.method('reduce', function (f, value) {
    var i;
    for (i = 0; i < this.length; i += 1) {
        value = f(this[i], value);
    }
    return value;
});

By adding a function to Array.prototype, every array inherits the method. In this case, we defined a reduce method that takes a function and a starting value. For each element of the array, it calls the function with an element and the value, and computes a new value. When it is finished, it returns the value. If we pass in a function that adds two numbers, it computes the sum. If we pass in a function that multiplies two numbers, it computes the product:

// Create an array of numbers.

var data = [4, 8, 15, 16, 23, 42];

// Define two simple functions. One will add two
// numbers. The other will multiply two numbers.

var add = function (a, b) {
    return a + b;
};

var mult = function (a, b) {
    return a * b;
};

// Invoke the data's reduce method, passing in the
// add function.

var sum = data.reduce(add, 0);    // sum is 108

// Invoke the reduce method again, this time passing
// in the multiply function.

var product = data.reduce(mult, 1);
    // product is 7418880

Because an array is really an object, we can add methods directly to an individual ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern JavaScript for the Impatient

Modern JavaScript for the Impatient

Cay S. Horstmann
Head First JavaScript Programming

Head First JavaScript Programming

Eric T. Freeman, Elisabeth Robson
Learn JavaScript

Learn JavaScript

Shaun Wassell

Publisher Resources

ISBN: 9780596517748Supplemental ContentCatalog PageErrata