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.
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
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)
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:
For this specific reason, I come back to for loops.
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 mustawait
the resolution ofPromise.all
. Or you can also use.then
.In considering this comment I discovered one can use .reduce() to return promises in sequence (which I also thought cool enough to share):
Good thoughts, that's for leading me to that find.
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
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 (:
thanks, buddy, I am also the map syntax lover. I can't imagine the React without the map
Hopefully, JS will add something like IAsyncEnumrable like C#, sometime soon.
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.
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
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.
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.
Ohh! I didn't know you can that.
This is sad 😔
I wonder why dev would make this feature 🤔
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
Do you have actual data to back that up?
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
Like this...
github.com/dg92/Performance-Analys...
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 thatmap
that you chose to use instead of afor
loop).Yes! This is what I mean. Engineers should consider performance when deciding which method to use.
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.
Aggred
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.
Yes shubham. While making the simple or small web app the map function doesn't make any impact on performance
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.
hehe, thanks buddy. I think why not to use the Punjab cities name, for example, let's also make them famous in dev.to
How are you going to use iterators then. Do use for loops, do use array functional methods too.
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
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.
This post seems misguided from the very beginning.
Some comments have been hidden by the post's author - find out more