Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript for...in vs for

Tags:

javascript

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?

like image 746
andrii Avatar asked Oct 28 '08 10:10

andrii


People also ask

When to use for in VS for of VS for JavaScript?

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.

What is for in and for of loop?

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.

Should I use for in JS?

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) .

What is for in used for?

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.


2 Answers

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     } } 
like image 28
Benno Richters Avatar answered Sep 19 '22 19:09

Benno Richters


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.

like image 191
AnthonyWJones Avatar answered Sep 19 '22 19:09

AnthonyWJones