DEV Community

Cover image for Don’t use for loop for JavaScript Arrays

Don’t use for loop for JavaScript Arrays

Kushal sharma on April 24, 2020

Lets first Talk about the Array in the Programming world I assume that if you belong from the programming world then you must playing with this stu...
Collapse
 
gstvds profile image
Gustavo da Silva

I was using map to handle loops, but I found out that it struggles when handling asynchronous requests. Map doesn't wait till the previous request end to start a new one, even when you use:

array.map(async data => {
  // Promise
});
Enter fullscreen mode Exit fullscreen mode

For this specific reason, I come back to for loops.

Collapse
 
aminnairi profile image
Amin • Edited

This is because you are returning an array of pending promises. If you want to fulfill these promises, you can use Promise.all. And if you want the result, you must await the resolution of Promise.all. Or you can also use .then.

function sleep(seconds: number) {
    return new Promise(function(resolve) {
        setTimeout(resolve, 1000 * seconds);
    });
}

function increment(input: number) {
    return input + 1;
}

async function main() {
    const nums = await Promise.all([1, 2, 3, 4, 5].map(async (num) => {
        await sleep(1);

        return increment(num);
    }));

    console.log(nums);
    // [ 2, 3, 4, 5, 6 ]
}

main();
Collapse
 
dsbarnes profile image
dsbarnes

In considering this comment I discovered one can use .reduce() to return promises in sequence (which I also thought cool enough to share):

function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  )
}

// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5)
  })
}

// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2)
  })
}

// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
 return a * 3
}

// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4)
  })
}

const promiseArr = [p1, p2, f3, p4]
runPromiseInSequence(promiseArr, 10)
  .then(console.log)   // 1200
Enter fullscreen mode Exit fullscreen mode

Good thoughts, that's for leading me to that find.

Collapse
 
sharmakushal profile image
Kushal sharma

yes for loop is the fastest among all the other methods. yes everything has the pro and cons we have to choose wisely what to use in which situation

Collapse
 
gstvds profile image
Gustavo da Silva

absolutely!

but that was a very helpful post!
I really like using map. It syntax combined with the fact that it doesn't change the original array it's very handy. If they improve async I'll definitely switch back to map (:

Thread Thread
 
sharmakushal profile image
Kushal sharma

thanks, buddy, I am also the map syntax lover. I can't imagine the React without the map

Collapse
 
mccshreyas profile image
Shreyas Jejurkar

Hopefully, JS will add something like IAsyncEnumrable like C#, sometime soon.

Collapse
 
steveblue profile image
Stephen Belovarich • Edited

Did you compare the performance of either in addition to considering the interface? Just because map can be more human readable doesn’t necessarily mean you shouldn’t use a for loop. for could be more performant for the end user.

Collapse
 
sharmakushal profile image
Kushal sharma • Edited

Yes, sir totally agreed with you that the for loop is much faster than the other javascript array functions. Everything has pros and cons. so we have to choose wisely what to use in which situation

Collapse
 
zicsus profile image
Himanshu Mishra

This is a very weak argument. I don't like the thinking that write whatever you wanna write because your pc's hardware can take it. Software is not in good place today because of that, especially web.
For and map have there own use cases. Use them wherever they suits the best.

Thread Thread
 
mburszley profile image
Maximilian Burszley • Edited

He's hiding any comments pointing out his weak arguments, so it makes sense. Terrible feature to be able to hide legitimate criticisms on DEV.

Thread Thread
 
zicsus profile image
Himanshu Mishra

Ohh! I didn't know you can that.
This is sad 😔
I wonder why dev would make this feature 🤔

Thread Thread
 
sharmakushal profile image
Kushal sharma

I made it hidden by mistake. I am new at this platform so just testing some features, if you know how I can revert it, then plz tell about the procedure

Collapse
 
steveblue profile image
Stephen Belovarich

Do you have actual data to back that up?

Thread Thread
 
sharmakushal profile image
Kushal sharma

You can easily get the performace metic on online b/w for and other functions . And every thing has pro and cons . I also has used for loop insted of the map in many situations

Thread Thread
 
steveblue profile image
Stephen Belovarich
Thread Thread
 
savagepixie profile image
SavagePixie • Edited

Oh, you mean those tests in which if you place forEach before for then forEach becomes faster? The same tests in which if you actually use the result of the operation afterwards map becomes faster than for?

"Because performance" doesn't seem a particularly good argument to choose one option over another. How fast a for, map, etc will run depends on more than its name, like optimisations that the runtime can do. So just choosr whichever fits your needs and if you run into performance issues profile and see what's causing the bottleneck (which probably won't be that map that you chose to use instead of a for loop).

Thread Thread
 
steveblue profile image
Stephen Belovarich

Yes! This is what I mean. Engineers should consider performance when deciding which method to use.

Collapse
 
joeattardi profile image
Joe Attardi

There are still perfectly valid use cases for the for loop. For example, if you want to break out of the loop early there’s the break keyword.

Or if you want to not iterate over the items of an array, but rather just repeat something a certain number of times, a for loop is useful there too.

A for loop also lets you have more complex logic for when you should continue looping. Remember that for loops are not only used for iterating over an array.

Collapse
 
sharmakushal profile image
Kushal sharma

Aggred

Collapse
 
shan61916 profile image
Shubham Sharma

Many comments about speed and performance here, but I believe in doing max-optimisations only when they make a noticeable difference for the end-user/service, thus I would endorse using Map if possible.

Collapse
 
sharmakushal profile image
Kushal sharma

Yes shubham. While making the simple or small web app the map function doesn't make any impact on performance

Collapse
 
vikasrai91 profile image
Vikas Rai

Hey Kushal, Thanks for your post. I read your post and what made me more indulged into this topic was that you mentioned my home town "LUDHIANA" in your first example.

Collapse
 
sharmakushal profile image
Kushal sharma

hehe, thanks buddy. I think why not to use the Punjab cities name, for example, let's also make them famous in dev.to

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

How are you going to use iterators then. Do use for loops, do use array functional methods too.

Collapse
 
sharmakushal profile image
Kushal sharma

It depends upon what is the situation , if i had to just loop over then i will use foreach , else if i had to do asynchorons work inside loop i swith back to the for loop , as for each doesnot support asynchonous

Collapse
 
pris_stratton profile image
pris stratton

What is map built on - is it a for loop underneath or is it a recursive function, or does that depend on the implementation of JS you are using? Not sure why it is slower than a for loop.

Collapse
 
mburszley profile image
Info Comment hidden by post author - thread only accessible via permalink
Maximilian Burszley

An array is a global object that can hold different elements or objects.

This post seems misguided from the very beginning.

Some comments have been hidden by the post's author - find out more