DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Iterating over arrays and objects in JavaScript

Iterating over arrays and objects in JavaScript

Axel Rauschmayer user avatar by
Axel Rauschmayer
·
Apr. 21, 11 · Interview
Like (0)
Save
Tweet
Share
9.51K Views

Join the DZone community and get the full member experience.

Join For Free

This post explains three methods for extracting information from arrays and objects:

  1. for loops
  2. Array methods (courtesy of ECMAScript 5 [1])
  3. Returning property keys in arrays
It concludes with best practices that combine the above mentioned approaches.

1. for loops

All for loops can be used with the following statements.
  • break [label]: exit from a loop.
  • continue [label]: stop the current loop iteration, immediately continue with the next one.
  • label: A label is an identifier followed by a colon. In front of a loop, a label allows you to break or continue that loop even from a loop nested inside of it. In front of a block, you can break out of that block. In both cases the name of the label becomes an argument of break or continue. Example for breaking out of a block:
        function findEvenNumber(arr) {
    loop: { // label
    for(var i=0; i<arr.length; i++) {
    if ((arr[i] % 2) === 0) {
    console.log("Found: "+arr[i]);
    break loop;
    }
    }
    console.log("No even number found.");
    }
    console.log("DONE");
    }

1.1. for

Syntax:
    for ([start]; [condition]; [final-expression])
statement
Rules:
  • Traditional way of iterating over arrays.
  • Can use var, but scope is always the complete surrounding function.
Example:
    var arr = [ "a", "b", "c" ];
for(var i=0; i<0; i++) {
console.log(arr[i]);
}

1.2. for...in

Syntax
    for (variable in object)
statement
Rules:
  • Iterate over property keys, including inherited ones.
  • Don’t use for arrays. It iterates over both array indices and property keys. There will thus be problems as soon as someone adds a property to an array.
  • Can use var, but scope is always the complete surrounding function.
  • Properties can be deleted during iteration.
Pitfall: Iterates over both array indices and property keys.
    > var arr = [ "a", "b", "c" ];
> arr.foo = true;
> for(var key in arr) { console.log(key); }
0
1
2
foo
Pitfall: Iterates over inherited properties.
    function Person(name) {
this.name = name;
}
Person.prototype = {
describe: function() {
return "Name: "+this.name;
}
};
var person = new Person("Jane");
for(var key in person) {
console.log(key);
}
Output:
    name
describe
Skip inherited properties: via hasOwnProperty().
    for(var key in person) {
if (person.hasOwnProperty(key)) {
console.log(key);
}
}

1.3. for each...in

Non-standard (Firefox only), iterates over the values of an object. Don’t use it.

2. Array methods for iteration

2.1. Iterate

Iterate over the elements in an array. The methods don’t have a result, but you can produce one in the callback as a side effect. They all have the following signature:
    function(callback, [thisValue])
Parameters:
  • The callback has the following signature (sometimes it returns no value, sometimes a boolean).
        function([element], [index], [collection])
  • The thisValue argument allows you to specify an object that is to be accessed via this in callback.
Iteration methods:
  • Array.prototype.forEach() is similar to for...in, but only iterates over an object’s own properties.
  • Array.prototype.every(): returns true if the callback returns true for every element.
  • Array.prototype.some(): returns true if the callback returns true for at least one element.
Example:
    var arr = [ "apple", "pear", "orange" ];
    arr.forEach(function(elem) {
        console.log(elem);
    });
Pitfall: forEach() does not support break. Use every() instead:
    function breakAtEmptyString(arr) {
        arr.every(function(elem) {
            if (elem.length === 0) {
                return false; // break
            }
            console.log(elem);
            return true; // don’t forget!
        });
    }
every() returns false if a break happened and true, otherwise. This allows you to react to the iteration finishing successfully (something that is slightly tricky with for loops). Caveat: You need to return a “true” value to keep going. If you want to avoid that, you can use some() and return true to break:
    function breakAtEmptyString(arr) {
        arr.every(function(elem) {
            if (elem.length === 0) {
                return true; // break
            }
            console.log(elem);
            // implicit: return undefined (interpreted as false)
        });
    }

2.2. Transform

Transformation methods take an input array and produce an output array, while the callback controls how the output is produced. The callback has the same signature as for iteration:
    function([element], [index], [collection])
Methods:
  • Array.prototype.map(callback, [thisValue]): Each output array element is the result of applying callback to an input element.
  • Array.prototype.filter(callback, [thisValue]): The output array contains only those input elements for which callback returns true.

2.3. Reduce

For reducing, the callback has a different signature:
    function(previousElement, currentElement, currentIndex, collection)
Methods:
  • Array.prototype.reduce(callback, [initialValue]): Compute a value by applying callback to pairs (previousElement, currentElement) of array elements.
  • Array.prototype.reduceRight(callback, [initialValue]): Same as reduce(), but from right to left.
Example:
    // Sum of all array elements:
    [17, 5, 4, 28].reduce(function(prev, cur) {
        return prev + cur;
    });

3. Listing property keys

  • Object.keys(obj): Lists all enumerable own property keys of an object. Example:
        > Object.keys({ first: "John", last: "Doe" })
        [ 'first', 'last' ]
    
  • Object.getOwnPropertyNames(): Lists all own property keys of an object, including non-enumerable ones.
        > Object.getOwnPropertyNames(Number.prototype)
        [ 'toExponential'
        , 'toString'
        , 'toLocaleString'
        , 'toPrecision'
        , 'valueOf'
        , 'toJSON'
        , 'constructor'
        , 'toFixed'
        ]
        > Object.keys(Number.prototype)
        []
    
    Comment: The main reason that prototype methods are not enumerable is to hide them from iteration mechanisms that include inherited properties.

4. Best practices

Iterating over arrays

Options:
  • Simple for loop.
  • One of the iteration methods.
  • Never use for...in or foreach...in.

Iterating over objects

Options:
  • Combine for...in with hasOwnProperty(), in the manner described above.
  • Combine Object.keys() or Object.getOwnPropertyNames() with forEach() array iteration.
        var obj = { first: "John", last: "Doe" };
        // Visit non-inherited enumerable keys
        Object.keys(obj).forEach(function(key) {
            console.log(key);
        });
    
Other tasks:
  • Iterate over the property (key,value) pairs of an object: Iterate over the keys, use each key to retrieve the corresponding value. Other languages make this simpler, but not JavaScript.

 

From http://www.2ality.com/2011/04/iterating-over-arrays-and-objects-in.html

Object (computer science) Property (programming) Data structure JavaScript

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • mTLS Everywere
  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling
  • OpenVPN With Radius and Multi-Factor Authentication
  • Microservices 101: Transactional Outbox and Inbox

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: