Sitemap

The function map() in Javascript

2 min readAug 18, 2021

--

The map() , filter() and reduce() are the essential and well known functions in javascript that run provided callback on each element of an array. The map() method is generally used to iterate over an array and calling function on every element of array.

In this article, we will be discussing on how effectively we can use map() method.

Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on each element in the calling/original array.

The map() method calls the provided function(callback) once for each array element .

This method doesn’t change the original array but, simply it returns a new array with each elements being the result of callback function.

Syntax

array.map(function(currentValue, index, arr), thisValue)

function(currentValue, index, arr) Required

The callback function accepts three parameter( currentValue,index,array)

1. currentValue : Required parameter. The current element being processed in the array

2. index : Optional parameter. It is the index of current element that being processed in the array.

3. array : Optional parameter. The original array map was called upon.

Get Radheshyam Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

thisValue : Optional. A value to be use as “this” when executing callback function.

Examples :

Example 1 :

Calling A Function on Each Item in an Array

const array2=array1.map((element)=>{  return(element*2)
})
console.log(array2)//output: Array [6,8,18,32]

In the above example when we call array1.map() then the callback function will be run once for each element in array1. So at first time, callback will be executed for the first element of array1 which is 3 and after processed (after multiplied by 2) it will be returned to array2 as 6 (processed result).Similarly this process will repeat for remaining elements of array1 and after multiplied by 2 it will be returned to array2. So the array2 becomes[6,8,18,32].

Example 2 :

Now consider the below example:

const array1 = [3, 4, 9, 16];const array2=array1.map((element,index)=>{ return(element*index)})console.log(array2)
//output Array [0, 4, 18, 48]

Here , current element as well as index value is passed as parameter in callback function.So in each iteration elements will be processed as follows:

1st : element=3, index=0 ,element*index=0

2nd: element=4, index=1, element*index=4

3rd: element=9, index=2 , element*index=18

4th: element=16, index=3, element*index=48

so the array2 will be [0,4,18,48]

Example 3 :

Mapped array contains undefined when undefined or nothing is returned

let numbers = [1, 2, 3, 4]
let filteredNumbers = numbers.map(function(num, index) {
if (index < 3) {
return num
}
})


// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]

Keep Learning!!!!

--

--