This site runs best with JavaScript enabled.

Array.prototype.map()

Kevin Beck

June 27, 2019


The other day I was asked to explain the .map() method in Java Script although I use it I found I stumbled explaing it so here is a better expernation:

'The map() method creates a new array with the results of calling a provided function on every element in the calling array.' MDN

So for each element in an array you can run a function and with the results create a new array for example:

Mapping an array of numbers to an array of square roots

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

Source & more examples