Refreshing JavaScript – Map Method – Detailed Explanation

Sathish Nadarajan
 
Solution Architect
April 26, 2019
 
Rate this article
 
Views
609

Refreshing JavaScript – A new Series which I am planning to write in depth about Javascript/JQuery methods, usages, samples in a simpler way.  As part of that, the first method, we focus today is MAP.

Definition:

.map() – A method which iterates through an array or collection and returns a new processed array.  The items in the array will be replaced with the manipulated item object.

Example:

I have an Array of Names.

 var arr = ["File1","File2","File3"]; 
         console.log(arr);
 
         var arr2 = arr.map(function(itm){
             return itm.toUpperCase();
         });
 
         console.log(arr2);
 

The output of the above code will be like,

 

In the original Array, the items are in the lower case and I want the items to be converted to Upper Case.  For that, either I can use the for or foreach loops as well.  But, in those cases, I need to declare the array.  Have a look on the below code.  The same is been implemented by for and foreach loops.

For Loop:

 var arrFor = [];
         for(i = 0;i<arr.length;i++)
         {
             arrFor.push(arr[i].toUpperCase());
         }
 
         console.log(arrFor);
 

For Each Loop:

 var arrForeach = [];
         arr.forEach(function(a){
             arrForeach.push(a.toUpperCase());
         });
 
         console.log(arrForeach);
 

In both the above methods, we need to initiate an array arrFor and arrForeach.  But, in the map method, we don’t need to declare any array.  The method returns an array and we can directly assign that to a array variable.

And moreover, with the arrow operator, the map method becomes very simple and clean.

 var arr = ["File1","File2","File3"]; 
         console.log(arr);
 
         var arr2 = arr.map(a => a.toUpperCase());
 
         console.log(arr2);
 

Hope that helps and in the upcoming articles, we will see some other method.

Happy Coding,

Sathish Nadarajan.

 

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment