How to use the map function in JavaScript?

How to use the map function in JavaScript?
How to use the map function in JavaScript?

Introduction

Sometimes we need to apply a function or operation on each element of an array to get a new array with modified values. This can be done by iterating over the array by the use of for() or forEach() loop. But there is another built-in function in JavaScript called array map() that can help you perform this type of operations gracefully without manually iterating over the array.

Using the array map function, you can perform these operations efficiently while maintaining the sanity of your code and avoiding writing the big loops. But the map() function can be a bit confusing if you are starting with your coding journey in javascript

If you want to know about the map function in Javascript in detail, then stay with me – here’s a detailed breakdown of the map function with its implementation.

What is the map() function?

The map() method creates a new array and fills them with the value obtained by applying the given function on each original array element. It is a non-mutating method, i.e., the map function does not change the original array elements. Instead, it creates and stores the value in a new array. The map function was introduced in javascript 5 (ECMAScript 5).

For example, you have an array of basic details about a group of persons, and you want to get each person’s name, then you can apply the map function.

Image Source: medium.com

Before starting the implementation, make sure you have node js runtime setup to run javascript programs on the terminal. If you are not having a node js runtime setup, you can choose any online compiler. There are plenty of online compilers available.

If you are using chrome, you can also run programs on the chrome developer tools console. You can access the chrome developers tools console by pressing Ctrl+shift+J (Windows) or  Ctrl+Option+J (Mac).

Syntax

The syntax for the map() function is as follows:

blog banner 1
array.map(function(currentValue, index, arr), thisValue)

The syntax of the map() contains two-arguments – the callback function and thisValue.

Let’s discuss these arguments in detail.

  • function(currentValue, index, arr): this is the callback function that runs on each element of the given array, and the value returned by this function is stored in the new array. The callback function accepts the following arguments:
    • currentValue: This holds the value of current elements being processed by the function. This is a required parameter.
    • Index: This parameter holds the array index of the current element being processed by function. This is an optional parameter.
    • arr: this parameter holds the array on which the function is being called. This is an optional parameter.
  • thisValue: it stores the value to be used as “this” while executing the callback function. This is an optional argument. The default value of “thisValue” is undefined.

How to use map() function?

Now we know the basics of map function and its syntax in detail. We should start to implement the map function. To understand how to use the map() function, let’s consider an example:

Consider you are having an array of the following elements:

let arr = [1, 2, 3, 4, 5];

And you want to multiply each element of the array by 2. You can implement this by the use of the map function as follows:

let arr = [1, 2, 3, 4, 5];
let temp = arr.map(function(element){
return element * 2;
})
console.log(temp);

You may implement the same by the use of a for loop as follows:

let arr = [1,2,3,4,5];
let temp = []
for(let i = 0; i < arr.length; i++){
temp.push(2 * arr[i]);
}
console.log(temp);

Image Source: medium.com

But, notice that you don’t need to create an empty array while using the map function, unlike the for loop method, where we need to create an empty array.

The code written using the map function is concise and easy to implement. We can write the same code even better by the use of the arrow (=>) function.

let arr = [1, 2, 3, 4, 5];
let temp = arr.map(element => element * 2);
console.log(temp);

Compare these three codes side by side, and you will notice how the map function can drastically cut down the length of code with the enhanced readability of the code. The map method also reduces the chances of error as we don’t need to declare and initialize the variables while using the map function. 

How to use map() function on an array of objects?

Suppose we are given an array of objects. The object encapsulates length and breadth as the fields to define the object as a rectangle. The array would look like this:

let rectangles=[{length: 10, breath: 5},
{length: 20, breath: 5},
{length: 12, breath: 4},
{length: 16, breath: 10}
];

You want to calculate the area of each rectangle. Then can you use the map() method to iterate over the array and get the area of rectangles by multiplying length and breadth? 

Yes, we can calculate the area of the rectangle by the use of map() function. 

The value of length and breadth of a rectangle can be accessed by using the key. Remember – Rectangle is an object!

let rectangles = [{length:10, breadth: 5},
{length: 20, breadth: 5},
{length: 12, breadth: 4},
{length: 16, breadth: 10}
];

let area = rectangles.map(function(rectangle){
        return (rectangle.length) * (rectangle.breadth);
});

console.log(area);

Similarly, we can perform operations on an array of objects having more than two properties.

Advantages of using map() over for loop

The advantages of using a map over loop are as follows:

  • Immutable: the map() function is immutable, i.e., your original array will remain intact. This is very useful if you need your original array elsewhere.
  • Cleaner code: the map function helps cut down unnecessary lines while writing code, thus helping you keep your code clean and more readable.
  • Quickness to code: the map function provides a quicker way to code than the conventional loops. 

When not to use map()?

You should not use the map function if,

  • You are not using the array it returns
  • You are not returning any value from the callback function

You should not use the map function in both these cases. Instead, you should use for() or forEach() loop in such scenarios.

Frequently Asked Questions

What is map () in JavaScript?

The map() method creates a new array and fills them with the value obtained by applying the given function on each original array element. It is a non-mutating method, i.e., the map function does not change the original array elements.

Is the array map async?

No, array map is not an async function. Array map is a synchronous function.

Is map a callback function?

No map is not a callback function.

Key Takeaways

This discussed the map function in Javascript and how you can use this function with different types of arrays in javascript. We also briefly discussed the advantages of using the map function with some of its limitations.

By Pranchal Agrahari