In this tutorial, we will be exploring how the method map()
works and how to use it effectively.
Method map()
that only works on arrays that goes through an array and iterates all the data inside and creates a new array along with a function applied to the elements of the array, leaving the original array untouched.
The syntax is as follows:
array.map(function(element, index, array), thisValue)
the method works by creating a callback function and every time it is called, it goes through each element
, index
or array
and returns the result as a new array.
Parameters
*element: This parameter holds the value of the elements.
*index(optional): This parameter holds the current index of the current value of the array.
*array: The original array that was created.
*thisArg(optional): This function is used when we execute the callback function.
Map in action
First things first, we need to create an array, to do so, we need to declare a name of the array and in this case we are going to call our array myToys
.
Now we are ready for the next step which is using map()
.
In this example, we are going to convert all the letters from our myToys
array into uppercase letters and use the thisArg
function.
To use map()
we will need to create a new variable for the array, so for our new variable we will call it myToys2
.
Then we will create a name for our callback function so for that we will name it convertToys
.
Then we will use this.
function in order to convert them all to uppercase.
The result should look like this.
Arrow function
We can also use the arrow
function to further shorten our code which makes it less cluttered in your workspace.
In this example, we are going to create a new array that contains the number of letters in each toy.
See how short that syntax is?
This is what it looks like if we print it out
To wrap things up, the map()
method has a lot of uses, and it is mostly used to clean up your workspace. Sure there are other methods that gets you the same result such as the for()
loop but the syntax is more complicated than the arrow function that we used; it is clean and fast
Also the benefits of using map()
is that it does not harm the original array as it creates a new one leaving the original one untouched and can be used as a reference.
Top comments (0)