Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?
Let's say we have an array of associative arrays:
var myArray = [{'key': 'value'}, {'key': 'value1'}];
So we can iterate:
for (var i = 0; i < myArray.length; i++)
And:
for (var i in myArray)
I don't see a big difference. Are there any performance issues?
The difference between them is: for-in provides access to the object keys , whereas the for-of operator provides access to the values of those keys. Iterating over an object or array is a pretty routine task with JavaScript, in fact, it's hard to imagine a day when you don't' need to perform this action.
for...of Vs for...inThe for...in loop is used to iterate through the keys of an object. The for...of loop cannot be used to iterate over an object. You can use for...in to iterate over an iterable such arrays and strings but you should avoid using for...in for iterables. The for...of loop was introduced in ES6.
A JS Array is an object, so yes, it's associative too, but that's not what it's for. If you want to iterate over an object's keys, use for (var key in object) . If you want to iterate over an array's elements, however, use for(var i = 0; i < array. length; i += 1) .
for..in is a method for iterating over "enumerable" properties of an object. It therefore applies to all objects (not only Object() s) that have these properties. An enumerable property is defined as a property of an object that has an Enumerable value of true.
Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in
statement.
If you use for in
to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.
Everything but the properties can be filtered out with .hasOwnProperty
. This code sample does what you probably wanted originally:
for (var name in obj) { if (Object.prototype.hasOwnProperty.call(obj, name)) { // DO STUFF } }
The choice should be based on the which idiom is best understood.
An array is iterated using:
for (var i = 0; i < a.length; i++) //do stuff with a[i]
An object being used as an associative array is iterated using:
for (var key in o) //do stuff with o[key]
Unless you have earth shattering reasons, stick to the established pattern of usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With