DEV Community

Cover image for JavaScript .map() Method πŸ“
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

JavaScript .map() Method πŸ“

Hello Everyone. Hope you all are safe and wearing masks😷.
So today, as promised, we shall be discussing about .map() method in JavaScript.

The Map Method

The Array.map() method allows us to iterate over an array and modify its elements using a callback function. In other words, the map() method creates a new array with the results of calling a function for every array element. It calls the provided function once for each element in an array, in order. Do keep in mind, that does not execute the function for empty elements. Hence, when using it, make sure, the array you are mapping over, exists. Else your code may stop running. And, the most incredible feature about map(), it does not change the original array. You get a new result, with the original array still intact.

Syntax

array.map(function(element, index, array), this)
Enter fullscreen mode Exit fullscreen mode

The callback function() is called on each array element, and the map method always passes the current element, the index of the current element, and the whole array object to it.
The this argument will be used inside the callback function. By default, its value is undefined. Using this, is completely optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value.

Examples

let arr = [3, 4, 5, 6];

let modifiedArr = arr.map(function(element){
    return element *3;
});

console.log(modifiedArr);
// [9, 12, 15, 18]
Enter fullscreen mode Exit fullscreen mode

Map over an array of objects

let users = [
    {firstName: "Mursal", lastName: "Furqan"}
    {firstName: "Muhammad", lastName: "Ali"}
    {firstName: "Vedant", lastName: "Khairnar"}
];

let userFullnames = users.map(function(element){
    return `${element.firstName} ${element.lastName}`;
});

console.log(userFullnames);
// ["Mursal Furqan", "Muhammad Ali", "Vedant Khairnar"]
Enter fullscreen mode Exit fullscreen mode

Changing default value of this

Here's how to change the "this" value to the number 06:

let arr = [2, 3, 5, 7]

arr.map(function(element, index, array){
    console.log(this) // 06
}, 06);
Enter fullscreen mode Exit fullscreen mode

You can also use predefined methods in a lot simpler fashion. In the next example, we shall show how you can take square root of an entire Array, in two lines using map().

const numbers = [16, 81, 4, 25];
const newArr = numbers.map(Math.sqrt)
// And we are done with taking square root of our array. Let's see it in console

console.log(newArr)
// [4, 9, 2, 5]
Enter fullscreen mode Exit fullscreen mode

In our next article, we shall discuss something even cooler 😎
Or, you can suggest in the comments 🧧 below what should we write on next. πŸŽ†

Top comments (0)