Reputation: 2307
I came across this piece of code in a project I am working on:
var dataSources = **an array of objects**
var _iteratorNormalCompletion = true;
for (var _iterator = dataSources[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var dataSource = _step.value;
....
}
Firstly, I have never come across anything like this before (didn't even know what to search for to find any reference material). What is the technical term for it and how does it work? Where does _step.value
get assigned? What are the differences between this and a for loop
?
Secondly, are there any standout benefits of using this style of for
over a standard for loop
, as to me it just seems an over-complicated way of achieving the same output:
var dataSources = **an array of objects**
for (var i = 0; i < dataSources.length; ++i) {
var dataSource = dataSources[i];
....
}
Upvotes: 0
Views: 36
Reputation: 29936
Your example seems to be a precompiled version of a for..of loop. This code is not meant to be written by hand, instead you could write this:
var dataSources = **an array of objects**;
for (let dataSource of dataSources) {
....
}
And compile it to get the form you showed us.
As you can see this syntax is even shorter than a regular for loop, and has the benefits of being able to iterate over any iterable collection. See the iteration protocol.
Upvotes: 2