Skip to content

Using 'ForOfStatement' is not allowed (no-restricted-syntax) #1271

Closed

Description

@mrtl-srn

Hi,
Since everybody tell us to not use forEach() but use for loop instead because it is much faster (https://jsperf.com/test-if-using-forofstatement-is-not-allowed-makes-sens), I would like to know why this is not allowed by airbnb ?

Activity

  1. ljharb commented on Jan 20, 2017

    @ljharb
    Collaborator

    a) microbenchmarks (ie, jsperfs) are not accurate reflections of real-world performance
    b) performance isn't important. It's easy to make clean code fast; it's hard to make fast code clean.

  2. AKST commented on Feb 21, 2017

    @AKST

    While I get this is an opinionated linter, the readability of forEach over for of is pretty debatable. But more importantly for of is actually more polymorphic as you can add the iterator property to any data type.

    techinically you can add a forEach method to any data type, but 🤷‍♂️

    Plus It's also more consistent, as the jQuery implementation of forEach orders parameters differently (yes some people still have to interact with jQuery), that and nodeLists's implementation of forEach is not present on all browsers, where as using for of works once you start using the babel polyfill.

    for of is simply a more powerful feature.


    For people landing here via google, here's the original definition if you want to over load it.

  3. ljharb commented on Feb 21, 2017

    @ljharb
    Collaborator

    Array.prototype.forEach.call(nodeList) works in every ES5+ browser.

    Separately, jQuery iteration methods should only be used for element collections, so I'm not sure why its element ordering really applies.

    You can't yet add the iterator property to any data type, because Symbol is not polyfillable nor available in every browser we support. This guide does not allow using symbols currently.

  4. AKST commented on Feb 22, 2017

    @AKST

    Array.prototype.forEach.call(nodeList) works in every ES5+ browser.

    True, but if the original argument against for of is that it isn't readability, then this isn't a strong argument in favour of forEach.

    I'm not sure why its element ordering really applies.

    It's less the ordering of the elements and more the ordering ordering of the parameters on invocation, the function you pass to jQuery forEach each passes the index through the first argument and the actual element in the second. 

    However if the readability of Array.prototype.forEach.call isn't an issue for you, then this may be a non issue.

    There's also the fact you can't yield from a forEach for an outer function the same way you can with a for of, or you use await in an async function (unless this rule accommodates for this).

    Symbol is not polyfillable nor available in every browser we support.

    Doesn't core-js (used by bable I believe) polyfillSymbol's, as well as well known symbols like the iterator symbol?


    edit: Just so I don't waste your time, is there a link to previous discussion on what decisions led to for of being disabled? Because surely stuff like iterating in a generator or async function is something that's been considered.

  5. petertrotman commented on Feb 22, 2017

    @petertrotman

    I'd just like to chime in and say that I would also like a justification for why ForOfStatement is restricted. I would like to use for (let element of array) { ... } in places where I am producing side effects in the iteration.

    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?

  6. ljharb commented on Feb 22, 2017

    @ljharb
    Collaborator

    The primary argument against for..of is that loops are awful, and should always be avoided. forEach is not a loop, it's an iteration.

    The primary reason it's disabled in this guide is that Symbols can not be polyfilled, thus we forbid Symbols, thus Symbol.iterator is unavailable, thus for..of is useless in a generic sense.

  7. AKST commented on Feb 22, 2017

    @AKST

    The primary reason it's disabled in this guide is that Symbols can not be polyfilled, thus we forbid Symbols, thus Symbol.iterator is unavailable, thus for..of is useless in a generic sense.

    This thing is though, they are polyfilled... Just look at this bable output of typeof Symbol.iterator, it's pretty clear their not using typeof right out of the box...

  8. ljharb commented on Feb 22, 2017

    @ljharb
    Collaborator

    @AKST Symbol semantics can not be fully polyfilled, and typeof foo in dependencies will never print out "symbol". It's not a shim, it's a sham.

  9. AKST commented on Feb 22, 2017

    @AKST
  10. kouhin commented on Feb 23, 2017

    @kouhin

    @ljharb I wonder without ForOfStatement, how to loop Map.prototype.keys() and Map.prototype.values(),
    e.g.

    const map1 = new Map();
    // map1.set(someKey, someValue);
    
    for (let key of map1.keys()) {
      console.info(key);
    }

    map1.keys() and map1.values() are MapIterator. They are non-array and we can't use forEach or map1.keys().length.

    Should we convert MapIterator to Array for loop?

  11. ljharb commented on Feb 23, 2017

    @ljharb
    Collaborator

    @kouhin Array.from(mapOrSet, mapperFunction),Array.from(mapOrSet.keys(), mapperFunction), same for values/entries

    in other words, yes - convert it to an array.

  12. johannpinson commented on Mar 1, 2017

    @johannpinson

    @ljharb for...of allow us to use break and continue statement (which can be usefull) but not a Array.map or Array.forEach

    What's the solution to simulate this two behavior? (only encapsulate part of code in an if...else and so force to complete the iteration?)

    Thanks for your advice

  13. ljharb commented on Mar 1, 2017

    @ljharb
    Collaborator

    @johannpinson yes, you shouldn't need break or continue ever, that's GOTO. Can you provide a code example with a loop, and I'll try to provide a non-loop example?

  14. 128 remaining items

  15. BaliBalo commented on Feb 14, 2020

    @BaliBalo

    Sorry to add to the pile of comments, I agree that for the vast majority of cases map, forEach, find etc. can be used. The only case I came across that wasn't really answered was the one by @janpaul123 in #1271 (comment)

    @ljharb 's answer is not strictly equivalent as it returns the first item that contains the result, whereas the initial code was returning the result value (someOtherList[subItem.id]).

    Basically what I am looking for would be some kind of findValue rather than find/findIndex. A find that would return the first returned truthy value. Let's take this simplified example:

    function getFirstMatching(array) {
        for (let item of array) {
            const result = heavyTransform(item);
            if (result) {
                return result;
            }
        }
    }
    

    The few ways I can think of doing that with Array functions are

    array.map(heavyTransform).find(value => value);
    

    or

    const resultItem = array.find(heavyTransform);
    return resultItem && heavyTransform(resultItem);
    

    Both cases call the heavyTransform function more than necessary.
    The only other way to not have extra calls that I can think of seems a bit ugly to me, as I believe the find callback is not supposed to have side-effects (in this case assigning a variable outside its scope):

    let result = null;
    array.find(item => (result = heavyTransform(item)));
    return result;
    

    Is there any other way around that?

  16. ljharb commented on Feb 14, 2020

    @ljharb
    Collaborator

    @BaliBalo

    array.reduce((result, x) => result || heavyTransform(x), null)

    For an array of less than, say, millions of elements, the "stop early" performance doesn't matter.

  17. schalkventer commented on Feb 15, 2020

    @schalkventer

    @ljharb Interesting.

    Are there sources that you can point me to that goes further into this? I actually prefer to use reduce all around, however, I always assumed that you gain a lot performance-wise by being able to break or continue

  18. ljharb commented on Feb 15, 2020

    @ljharb
    Collaborator

    @schalkventer performance is both the least important consideration (far behind clarity), and also just doesn’t matter for non-large N. I’m not sure what resources you’re looking for, but you can surely benchmark your entire app with both approaches and see if it makes a difference.

  19. 0xAnon101 commented on Feb 17, 2020

    @0xAnon101

    correct me if I'm wrong, but if each call of someAsyncFunc is independent.

    for (const a of arr) {
        await someAsyncFunc(a);
    }
    

    can be

    await arr.map(a => {
        return someAsyncFunc(a);
    });
    

    Which also parallelizes the calls to someAsyncFunc. Like I said, each call needs to be independent.

    @Motoxpro
    If you want to read the files in parallel, you cannot use map indeed. Each of the async callback function calls does return a promise, but you're throwing them away instead of awaiting them. Just use map instead, and you can await the array of promises that you'll get with Promise.all:

    async function printFiles () {
      const files = await getFilePaths();
    
      await Promise.all(files.map(async (file) => {
        const contents = await fs.readFile(file, 'utf8')
        console.log(contents)
      }));
    }
    
  20. iwis commented on May 28, 2020

    @iwis

    The primary argument against for..of is that loops are awful, and should always be avoided. forEach is not a loop, it's an iteration.

    The primary reason it's disabled in this guide is that Symbols can not be polyfilled, thus we forbid Symbols, thus Symbol.iterator is unavailable, thus for..of is useless in a generic sense.

    We have 2020 year, the Symbol is supported by all modern browsers: https://caniuse.com/#feat=mdn-javascript_builtins_symbol, so Symbol doesn't have to be polyfilled anymore, does it? Does this mean that for ... of can be added to the Airbnb style?

    I am still learning JavaScript, so maybe I do not understand something.

  21. ljharb commented on May 28, 2020

    @ljharb
    Collaborator

    @iwis Airbnb still supports IE 11; many websites still need to support IE 9; Symbol can't be shimmed, only shammed; even with Symbols, loops are still not permitted by this guide.

  22. iwis commented on May 28, 2020

    @iwis

    @ljharb If someone doesn't support IE on their website, there is no other problem with using for ... of, is there? For some the for ... of is awful and for others it is more clear than Array.forEach(...).

  23. ljharb commented on May 28, 2020

    @ljharb
    Collaborator

    @iwis there is a problem even if you only support latest Chrome - the issue isn’t a technical one, it’s a conceptual one: don’t use loops, anywhere.

  24. erikeckhardt commented on May 28, 2020

    @erikeckhardt

    @iwis there is a problem even if you only support latest Chrome - the issue isn’t a technical one, it’s a conceptual one: don’t use loops, anywhere.

    A face-off between loops and iterations doesn't seem that useful. Loops are simply a tool—one that can be use to iterate—and thus while I could be missing something, saying absolutely that iteration is superior to loops seems off.

    Second, almost anything one might be tempted to call a loopless “pure” iteration almost certainly has loops going on under the covers. Taking a stance against loops per se seems like forbidding wheels but accepting machines full of wheels inside. To what benefit to have such a stance rigidly enforced?

  25. vdh commented on May 29, 2020

    @vdh
    Contributor

    @erikeckhardt There's already a long history of comments here on why, but in a nutshell, loops encourage lots of side effects and are often unclear about how async behaviour will flow. If you want a style guide to change how it recommends code style, you're going to need a better argument about code style further than just "it exists".

    Arguing about how (one of the many) engines implement the underlying internals is just absurd.

  26. erikeckhardt commented on May 29, 2020

    @erikeckhardt

    @vdh I guess I’ve just never had any trouble with loops. In my experience people are either confused by async or they’re not. They are either confused by deferred execution or they’re not.

    When confused, they inventively find all sorts of ways to do things wrong. Loops or no loops...

  27. vdh commented on May 29, 2020

    @vdh
    Contributor

    @erikeckhardt Style guides are about teamwork and clear communication of intent. Other people need to be able to read and understand your code, and vis versa. It's not just about you, and nothing will be gained from assuming the worst of your peers.

    Every reply here will notify everyone subscribed, so if you have something to say it should be something that
    a) is not a repeat of the many existing comments above, and
    b) is a compelling conceptual argument that does not ignore the project maintainer's existing reasoning he's already explained above.
    Anything else is just rude and creates extra noise.

  28. nitsujri commented on May 29, 2020

    @nitsujri

    I vote to lock this thread as this is no longer a discussion and hasn't been for some time.

    Whether you believe forEach to be right or wrong it's okay. AirBnB has their opinion and if you don't agree with it, it is not forced on you - there is a way to not use it.

  29. locked as resolved and limited conversation to collaborators on May 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions