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

Enumeration

The for in statement can loop over all of the property names in an object. The enumeration will include all of the properties—including functions and prototype properties that you might not be interested in—so it is necessary to filter out the values you don't want. The most common filters are the hasOwnProperty method and using typeof to exclude functions:

var name;
for (name in another_stooge) {
    if (typeof another_stooge[name] !== 'function') {
        document.writeln(name + ': ' + another_stooge[name]);
    }
}

There is no guarantee on the order of the names, so be prepared for the names to appear in any order. If you want to assure that the properties appear in a particular order, it is best to avoid the for in statement entirely and instead make an array containing the names of the properties in the correct order:

var i;
var properties = [
    'first-name',
    'middle-name',
    'last-name',
    'profession'
];
for (i = 0; i < properties.length; i += 1) {
    document.writeln(properties[i] + ': ' +
            another_stooge[properties[i]]);
    }

By using for instead of for in, we were able to get the properties we wanted without worrying about what might be dredged up from the prototype chain, and we got them in the correct order.

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