Updated:

✒ Reference: MDN Web Docs - Array.prototype.map()

map() function

map() creates a new array from calling a function for every array element. It calls a function once for each element in the array, and does not execute the function for empty elements.

It returns an array, where each array element is the result of the given function.

// Arrow function
map((element) => { ... })
map((element, index) => { ... })
map((element, index, array) => { ... })

// Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Inline callback function
map(function(element) { ... })
map(function(element, index) { ... })
map(function(element, index, array){ ... })
map(function(element, index, array) { ... }, thisArg)
Parameters  
function() Required. A function to be run for each array element.
element Required. The value of the current element.
index Optional. The index of the current element.
array Optional. The array of the current element.
thisArg Optional. Default value undefined. A value passed to the function to be used as its this value.

Examples

// Map an array of numbers to an array of square roots:

let numbers = [1, 4, 9]
let roots = numbers.map(function(num) {
    return Math.sqrt(num)
})
// roots is now     [1, 2, 3]
// numbers is still [1, 4, 9]

Leave a comment