Map Function in JavaScript

Map Function in JavaScript

Lets deep dive into map() function

In JavaScript, map() function is generally used with arrays. The map() function is a higher order function. It takes another function as a parameter. It calls the function which is passed as a parameter against all the elements in the array and returns a whole new array containing the new elements. Lets take an example :

const arr = [1,2,3,4,5];
//lets say we have to create a new array which contains squares of all the elements present in the array arr.

function square(num){
   return num*num;
}

const newArr = arr.map(square);

console.log(newArr);
//output : [ 1, 4, 9, 16, 25 ]

//console.log(arr) output=>[1,2,3,4,5]

In above code, the function square is passed as a parameter to map() function It calls the square function for all the elements present in the array arr and returns a whole new array which contains the squares of all the elements.

NOTE: map() function do not mutate/change the original array. ex. if we output the original array in above code, the arr is still the same!

There are many ways to write a map() function. The first way was the one which we used in the above code. Now, lets see some another ways:

const arr = [1,3,5,7,4];
//suppose, we have to create a new array which contains all the elements triple of their value in arr.

/***first way****/
//const newArr = arr.map(function(num){
//     return num = num * 3;
//})

/*** best way and mostly used ***/
const newArr = arr.map((num) => {
return num = num * 3})

console.log(newArr); // output => [ 3, 9, 15, 21, 12 ]

Practical use of map() function :-

In ReactJS, map() function is used to display the data in the array fetched from an API. Generally, APIs contain there data in the form of arrays so, using map() function we can show UI for each element in the array easily. lets implement that:

//lets say, we have a fake users api which contains fake data of users which will be an array of objects
// our task is to show the list of all the users with their firstname and lastname fetched from the API

const users = [
               {firstname:"Elon", lastname:"Musk", age:51},
               {firstname:"Donald", lastname:"Trump", age:76},
               {firstname:"Bill", lastname:"Gates", age:66},
               {firstname:"Jeff", lastname:"Bezos", age:58},
               ] 

const userList = users.map((user) => {
   <li>{user.firstname + " " + user.lastname}</li>
})

ReactDOM.render(
 <ul>{userList}</ul>,
 document.getElementById('root')
);