Nice article. You require for loops for situations where you have to adjust the current index of the loop or step by steps other than 1. Even when dealing with arrays, you don't always want to loop over the array item per item.
You raise a great point. As I said, sometimes you’ll have no choice but to use for loops. It’s up to us as devs to decide if and when they should be used. In the interest of minimising their use, it’s good to creatively explore alternatives.
Adjusting index is a tricky one -- my understanding is that if you want to do that as part of something like a binary search, there’s no real alternative to for loops. If you expect small input sizes, you could get away with Array.prototype.indexOf(): O(n) complexity vs O(log n) for a binary search.
Iterating by steps other than 1 is a bit easier. You can do this by chaining Array.prototype.filter() and Array.prototype.forEach():
constSTEP_SIZE=3;myArray.filter((element,index)=>!(index%STEP_SIZE)).forEach(nthElement=>{// Do stuff here});
Array.prototype.reduce() also works. Yes, element ends up being unused, but this is nonetheless preferable to using a for loop.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice article. You require for loops for situations where you have to adjust the current index of the loop or step by steps other than 1. Even when dealing with arrays, you don't always want to loop over the array item per item.
You raise a great point. As I said, sometimes you’ll have no choice but to use
for
loops. It’s up to us as devs to decide if and when they should be used. In the interest of minimising their use, it’s good to creatively explore alternatives.Adjusting index is a tricky one -- my understanding is that if you want to do that as part of something like a binary search, there’s no real alternative to
for
loops. If you expect small input sizes, you could get away withArray.prototype.indexOf()
: O(n) complexity vs O(log n) for a binary search.Iterating by steps other than 1 is a bit easier. You can do this by chaining
Array.prototype.filter()
andArray.prototype.forEach()
:Array.prototype.reduce()
also works. Yes,element
ends up being unused, but this is nonetheless preferable to using afor
loop.