View profile

Essential Array methods in JavaScript. Part 3 - map

Coderslang Master
Coderslang Master
Hey, there! I hope you’re getting closer and closer to your goal of becoming a Full Stack JavaScript developer!
A couple of months back, I started a series on the essential array methods in JavaScript. As the summer break is over, let’s get back to work.
In the previous issues, you learned about 2 of them:
Today, you’ll learn how you can use the function map to transform the JavaScript array by applying a mapping function to all of its elements. vs Array.forEach
In the most basic use case, the built-in array function map could be used exactly like forEach to iterate over the array element.
map could be used exactly like forEach
map could be used exactly like forEach
The biggest drawback of the forEach loop is that it doesn’t return anything useful.
If you want to get an array doubleArr where each element is equal to the element arr multiplied by two, then forEach won’t help.
To get an array equal in length to the initial array but with modified elements, use the map function.
use to modify the array elements
use to modify the array elements
Note that the array arr has not changed in any way.
Together with the filter, the map method is one of the most used array methods in JS.
Both filter and map return an array so that you can combine them into chains.
Chaining and Array.filter
Let’s go back to the user example.
The task is to create an array with the names of all users whose age is less than 18 years.
Let’s first apply the filter function to throw away all the underage users and then use map to transform an array of objects into an array of strings.
you can use chaining with and Array.filter
you can use chaining with and Array.filter
It will become very easy for you to read such code after you get used to the syntax.
The task of creating a new array from an existing one arises so often that the forEach loop can safely be called
the most useless method in JavaScript. It’s almost always better to use map or a regular for loop instead.
That’s it for now! Next time, I’ll tell you about how you can iterate over an array with the function reduce and how you can use it to compress any JS array to a single value.
Coderslang: Become a Software Engineer
Don’t miss out on the other issues by Coderslang Master
Did you enjoy this issue? Yes No
Coderslang Master
Coderslang Master @coderslang

Coderslang: Become a Software Engineer

You can manage your subscription here.
In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Created with Revue by Twitter.