Reputation: 5907
Now we have a for... of loop in JS. Can it be used for iteration over arrays instead of for (let i = 0, len = array.length; i < len; i++) {...}
seamlessly or are there any caveats that make using it for arrays a bad practice?
Upvotes: 1
Views: 120
Reputation: 288530
Yes, it's OK.
Well, unless you specified a custom value for Symbol.iterator
, but still want the loop to be from 0 to length.
var arr = [1,2,3,4];
arr[Symbol.iterator] = function*() {
yield "custom";
yield "iterator";
};
console.log('Old for loop:');
for (let i = 0; i < arr.length; i++) console.log(' ', arr[i]);
console.log('New for-of loop:');
for (let item of arr) console.log(' ', item);
Upvotes: 2
Reputation: 30330
Yes, for... of
is fine for Arrays because they are iterable.
You can verify that in your browser's console by checking that Array instances have a Symbol.iterator
method:
[][Symbol.iterator]
> values() { [native code] }
... and, tautologically, by the fact that you can iterate them with for... of
!
Upvotes: 1
Reputation: 92579
In my opinion the main purpose of for-of loops is to iterate arrays. The fact that iterating arrays using for-in loops is considered a bad practice has nothing to do with it. Also, for-in loop can be used for iterating any objects, but for-of loop can be used only for iterating objects that are iterable.
Upvotes: 0