You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Using 'ForOfStatement' is not allowed (no-restricted-syntax) #1271
Reacted by Alex Mantsurov, Alex Kai, Vladimir Varbanov, n4nn31355, Alex Rififi, Andrew Lam 🌱, Julien Karst , David Nunez, Mikhail S., Q-back and 11 more
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.
Reacted by Nikola Šijakinjić, Ahmed Elhady, Adam Misiorny, Aleksey Levenstein, Angus, sattellite, Michael Flores, Will, 99thpixel, Bartosz V. Bentkowski and 99 more
Reacted by Scott Gibson, Lee Comstock, Victor Villas, Alex Mantsurov, Jesse Niininen, Ali Kosar Hosseinkhani, ylfzq, Luis Hernandez, juan-hiq, Joe Miller and 55 more
Reacted by Emmanuel, Adam Misiorny, Pedro Carriço, Naimur Rahman, Aymeric Robini, Josiah Kaviani, Moritz Roessler, Alex Haines and Mauro Pineda
Reacted by Flynn, Gabriel Morcote, Alexey Vykhrystyuk, Benjamin Zhang, Peter Harding, Yaroslav Osypenko, Jimmy Wärting, fnyquist, Adam Rackis, David de Lusenet and 40 more
Reacted by Daniel Gray, Andrey Efimov, Tomas Gonzalez, Naimur Rahman, Timur Kasiev, josiah m nyarega, Aymeric Robini, Keni, Shiveen Pandita, PavelGriza and 13 more
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.
Reacted by Spencer Murray, Mario Volke, Ilan Schemoul, Danil, bla-k, Ruslan @doasync, MrHubble, Dan Dascalescu, felixhayashi, Stepan Sadovnykov and 142 more
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.
Reacted by Reinis Ivanovs, Vasil Rashkov, Joshua Koudys, Omeid Matten, Peter Harding, Adam Rackis, Rafał Sawicki, Joar Wilk, Andy, Karolusrex and 74 more
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 forEacheach 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.
Reacted by Ispen, Tamás Halasi, Alexandru Rosianu, Andrew Lam 🌱, Juan Pablo Sala, meryzaq and Mathieu Darse
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?
Reacted by Joshua Kleckner, Casey Britt, Andrei Dushkou, Dan Dascalescu, Micky, Kelvin Abrokwa-Johnson, sd890623, ilia, Mehul Thakkar, Viktor Bogutskii and 131 more
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.
Reacted by Aldo Fregoso, Daniel Gray, Rinat Valiullov, Amal Karunarathna, baconcheese113, Oskar Jaskólski and benvasseur
Reacted by Andy, Matthew James Briggs, Jingbo Jin, fredericgermain, Denis Khvostov, Jake Niemiec, Yaroslav Osypenko, Jacob Smith, Chiu Yue Chun, Alex Melman and 116 more
Reacted by Ruslan @doasync, Allan Berry, felixhayashi, aksel, Ian J. Miller, Mario Camacho, Yacine Hmito, Daniel K O'Leary, Flynn, Stan Luo and 59 more
Reacted by Sebastian Di Luzio, FabianL1, sr9yar, Mukesh, Nitanshu Vashistha and Albert
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.
@kouhinArray.from(mapOrSet, mapperFunction),Array.from(mapOrSet.keys(), mapperFunction), same for values/entries
in other words, yes - convert it to an array.
Reacted by @brody2consult - Chris J. Brody
Reacted by Jimmy Wärting, Massimiliano Torromeo, Alexander, Jingbo Jin, fredericgermain, Abhishek Nandgaonkar, dominictobias, danilo neves cruz, Eneko, Scott Gibson and 59 more
@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
Reacted by Bence Szabó, 21emerald, Alexander Pirozhkov, Ilan Schemoul, Bartosz V. Bentkowski, Ira Ladson, Sjors van Heuveln, Jimmy Wärting, Jingbo Jin, Shiquan Wang and 28 more
@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?
Reacted by Shirsh Zibbu, Gideon MW Jones, Rinat Valiullov, Hilton Perantunes, Sam King and Simon Isler
Reacted by Jesse Niininen, Mitchell de Rijcke, johnlop, Santiago Castillo, matt coubrough, Joe Miller, Zach Zodkoy, Nebular Streams, Jan-Eric Duden, Engin Yapici and 38 more
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
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;
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
@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.
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:
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.
@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.
@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(...).
@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?
@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.
@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...
@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.
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.
Activity
ljharb commentedon Jan 20, 2017
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.
AKST commentedon Feb 21, 2017
While I get this is an opinionated linter, the readability of
forEachoverfor ofis pretty debatable. But more importantlyfor ofis actually more polymorphic as you can add the iterator property to any data type.Plus It's also more consistent, as the jQuery implementation of
forEachorders 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 ofis simply a more powerful feature.For people landing here via google, here's the original definition if you want to over load it.
ljharb commentedon Feb 21, 2017
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
Symbolis not polyfillable nor available in every browser we support. This guide does not allow using symbols currently.AKST commentedon Feb 22, 2017
True, but if the original argument against
for ofis that it isn't readability, then this isn't a strong argument in favour offorEach.It's less the ordering of the elements and more the ordering ordering of the parameters on invocation, the function you pass to jQuery
forEacheach passes the index through the first argument and the actual element in the second.However if the readability of
Array.prototype.forEach.callisn'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 useawaitin an async function (unless this rule accommodates for this).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 ofbeing disabled? Because surely stuff like iterating in a generator or async function is something that's been considered.petertrotman commentedon Feb 22, 2017
I'd just like to chime in and say that I would also like a justification for why
ForOfStatementis restricted. I would like to usefor (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.maphas functional connotations and we shouldn't be producing side effects in the closure.array.forEachis an option, but I personally don't like it for this sort of imperative work.So I think the
ForOfStatementshould be removed from the restricted syntax for the above reasons - anyone with any conflicting viewpoints? Do we know what the original justification is?ljharb commentedon Feb 22, 2017
The primary argument against for..of is that loops are awful, and should always be avoided.
forEachis 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.iteratoris unavailable, thusfor..ofis useless in a generic sense.AKST commentedon Feb 22, 2017
This thing is though, they are polyfilled... Just look at this bable output of
typeof Symbol.iterator, it's pretty clear their not usingtypeofright out of the box...ljharb commentedon Feb 22, 2017
@AKST Symbol semantics can not be fully polyfilled, and
typeof fooin dependencies will never print out "symbol". It's not a shim, it's a sham.AKST commentedon Feb 22, 2017
kouhin commentedon Feb 23, 2017
@ljharb I wonder without ForOfStatement, how to loop Map.prototype.keys() and Map.prototype.values(),
e.g.
map1.keys()andmap1.values()areMapIterator. They are non-array and we can't use forEach or map1.keys().length.Should we convert MapIterator to Array for loop?
ljharb commentedon Feb 23, 2017
@kouhin
Array.from(mapOrSet, mapperFunction),Array.from(mapOrSet.keys(), mapperFunction), same for values/entriesin other words, yes - convert it to an array.
johannpinson commentedon Mar 1, 2017
@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
ljharb commentedon Mar 1, 2017
@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?
128 remaining items
BaliBalo commentedon Feb 14, 2020
Sorry to add to the pile of comments, I agree that for the vast majority of cases
map,forEach,findetc. 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
itemthat 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
findValuerather thanfind/findIndex. A find that would return the first returned truthy value. Let's take this simplified example:The few ways I can think of doing that with Array functions are
or
Both cases call the
heavyTransformfunction 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
findcallback is not supposed to have side-effects (in this case assigning a variable outside its scope):Is there any other way around that?
ljharb commentedon Feb 14, 2020
@BaliBalo
For an array of less than, say, millions of elements, the "stop early" performance doesn't matter.
schalkventer commentedon Feb 15, 2020
@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
breakorcontinueljharb commentedon Feb 15, 2020
@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.
0xAnon101 commentedon Feb 17, 2020
@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:
iwis commentedon May 28, 2020
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 ... ofcan be added to the Airbnb style?I am still learning JavaScript, so maybe I do not understand something.
ljharb commentedon May 28, 2020
@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.
iwis commentedon May 28, 2020
@ljharb If someone doesn't support IE on their website, there is no other problem with using
for ... of, is there? For some thefor ... ofis awful and for others it is more clear thanArray.forEach(...).ljharb commentedon May 28, 2020
@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.
erikeckhardt commentedon May 28, 2020
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?
vdh commentedon May 29, 2020
@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.
erikeckhardt commentedon May 29, 2020
@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...
vdh commentedon May 29, 2020
@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.
nitsujri commentedon May 29, 2020
I vote to lock this thread as this is no longer a discussion and hasn't been for some time.
Whether you believe
forEachto 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.