Use for loop for array provide errror

Viewed 4523

I use the following code that works as expected, while using a ESLINT i got error

ESLint: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. (no-restricted-syntax)

This is the code

for (const subscription of resp.data.subscriptions) {
  if (subscription.url) {
    return subscription.url;
  }
}

The code is simply

  • get an array of data from other function
  • loop on each array item
  • when the first array instance have url take it and return

Is there a way to write it better to avoid the eslint issue ?

2 Answers

There is a debate about for...of usage here and its eventual restriction

for(let i = 0; i < array.length; i ++) { ... } is antiquated syntax, and while I know everyone understands what it means, we should be leaving it behind.

array.map has functional connotations and we shouldn't be producing side effects in the closure.

array.forEach is an option, but I personally don't like it for this sort of imperative work.

So I think the ForOfStatement should be removed from the restricted syntax for the above reasons - anyone with any conflicting viewpoints? Do we know what the original justification is?

for..of is more expensive than forEach, check this out

I have no opinions, you could just remove the eslint rule

You can use a .filter to solve this:

var arrObjWithURL = resp.data.subscriptions.filter(function(item) {
    return item.url;
});

if (arrObjWithURL.length > 0) {
    return arrObjWithURL[0];
}

You can also use .find:

return resp.data.subscriptions.find(function(item) {
    return item.url;
});

... or this to continue if there is no URL found:

const objWithUrl = resp.data.subscriptions.find(function(item) {
    return item.url;
});

if (objWithUrl !== undefined) {
    return objWithUrl;
}

demo on jsfiddle.net

Related