The question won't be complete if we don't mention about alternative methods for looping through objects.
Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.
If you work with jQuery, you may use jQuery.each()
method. It can be used to seamlessly iterate over both objects and arrays:
$.each(obj, function(key, value) {
console.log(key, value);
});
In Underscore.js you can find method _.each()
, which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):
_.each(obj, function(value, key) {
console.log(key, value);
});
Lo-Dash provides several methods for iterating over object properties. Basic _.forEach()
(or it's alias _.each()
) is useful for looping through both objects and arrays, however (!) objects with length
property are treated like arrays, and to avoid this behavior it is suggested to use _.forIn()
and _.forOwn()
methods (these also have value
argument coming first):
_.forIn(obj, function(value, key) {
console.log(key, value);
});
_.forIn()
iterates over own and inherited enumerable properties of an object, while _.forOwn()
iterates only over own properties of an object (basically checking against hasOwnProperty
function). For simple objects and object literals any of these methods will work fine.
Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in
loop will usually be faster than any abstraction, such as jQuery.each()
, these methods are considerably easier to use, require less coding and provide better error handling.