DEV Community

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

Posted on

Don’t use for loop for JavaScript Arrays

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 stuff called Array ,array can hold different elements or objects. We can also use an array as a list, a stack, or a queue in JavaScript. While the other languages like c and c++ JavaScript can contain items of same data type or a mixture of data types.

Alt Text
As JavaScript coders, we always work with arrays and lists. If I told you to do the coding without using the Array, you stop writing the code within 2 minutes.

We use them to collect objects, split strings, search, sort, etc. Obviously we use our old friend for-loop to perform such actions, but these loops can get complex and hard to maintain pretty fast. You can write the super awesome logic with the help of for loop. But think about your co-workers or the person who is going to handle your code after. So in this tutorial, I am going to explain some awesome JavaScript array techniques that you can implement in your project.

What we have been doing so far?

Var arr = [1,2,3,4,5]
Let sum =0;
For (let i=0; i < arr.length ; i++){
……. Our logic
}

As a beginner, we always follow this method, whatever logic implementations we want to do for array we put that logic inside the for a loop . absolutely we love For loop our best friend. but its time to get rid of this syntax
Alt Text
Sometimes we need to modify the given array but we also don’t want to lose the original array values. so in these types of situations, the map function can help us.

first, let's look at the old method

const persons = [
{ name: ‘kushal’, city: ‘Jalandhar’, distance: 145},
{ name: ‘rahul’, city: ‘amritsar’, distance: 200},
{ name: ‘hemunt’, city: ‘ludhiana’, distance: 100}
]

here we have the persons array which contains the person object and we want to convert the distance which was in the kilometers into the miles

Old method

const convertedDistances = []
for (let i = 0; i < persons.length; i++) {
convertedDistances.push({
…persons[i],
distance: persons[i].distance * 0.621371
})
}

here we iterate through the array and convert the kilometers into miles by the formula and push it to the new array of convertedDistances. let's do the same thing with the map function

New method

const convertedDistances = persons.map((person)=>
{
…person,
distance: person.distance * 0.621371
}
)

Why should You Use Map
It lets you avoid making changes to the main array
You can modify the items you want
It gives you a more readable code.

Note: For loop is fastest from the map but in the current situation we have a lot of processing power for the client browser so it doesn't affect the performance that much.

I hope you like this Blog. This is my first ever blog post on any platform and I know that I have done a lot of mistakes, I always like to listen to feedback, if you have any for me then please write that one on the comment. and if you like to read more like this one then give a follow

Top comments (28)

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