You're viewing the legacy docs. They are deprecated as of May 18, 2016.
These docs are for version 2.4.2 and below of the Javascript SDK. Go to our current docs, or see our Web migration guide.

Version 2.4.2Changelog

DataSnapshot.forEach()

Because of the way JavaScript object hashes work, the ordering of data in the JavaScript object returned by val() is not guaranteed to match the ordering on the server nor the ordering of child_added events. That is where forEach() comes in handy. It guarantees the children of a DataSnapshot will be iterated in their actual order, the same order as they are kept in your Firebase database.

Assume we have the following data in our Firebase database:

{
  "users": {
    "fred": {
      "first": "Fred",
      "last": "Flintstone"
    },
    "barney": {
      "first": "Barney",
      "last": "Rubble"
    }
  }
}

We can loop through our users in order with the forEach() method. The callback provided to forEach() will be called synchronously with a DataSnapshot for each child:

var ref = new Firebase("https://docs-examples.firebaseio.com/samplechat/users");
ref.once("value", function(snapshot) {
  // The callback function will get called twice, once for "fred" and once for "barney"
  snapshot.forEach(function(childSnapshot) {
    // key will be "fred" the first time and "barney" the second time
    var key = childSnapshot.key();

    // childData will be the actual contents of the child
    var childData = childSnapshot.val();
  });
});

You can cancel the enumeration at any point by having your callback function return true. For example, the following code sample will only fire the callback function one time:

var ref = new Firebase("https://docs-examples.firebaseio.com/samplechat/users");
ref.once("value", function(snapshot) {
  // The callback function will only get called once since we return true
  snapshot.forEach(function(childSnapshot) {
    var key = childSnapshot.key();
    // key === "fred"

    return true;
  });
});