a blog for those who code

Sunday, 16 December 2018

Understanding map() function in JavaScript

In our earlier days with JavaScript we might have used the classic for loop and then forEach method. Recently one of the popular method is .map() method and everyone talks about it. Let's go through some of the examples to understand what exactly is .map() function.

One of the main difference between the previous methods and .map is that .map() function creates a new array, by iterating over each item of the array and calling a provided the function.

Let's take an example :

const arr = [1,2,3,4,5]
const newArr = arr.map(a => {
  return a * 2

As you can see in the above example, we are iterating over each element of the array and then doubling its value. The value of newArr will be [2,4,6,8,10]. The .map() method calls a predefined function on every element in the array and resturns a new array of the same size.

Since .map() function is not updating the existing values and returning a new array, it is much faster than other classic methods. One more reason of using .map() function is that you do not have to worry about updating existing array and can create a new array from the existing one also keeping the existing one.

Let's just modify our existing example and see what else we can do with the .map function.

const arr = [1,2,3,4,5]
const newArr = arr.map((val,i) => {
  return {
    oldVal: val,
    newVal : val * 2,
    index: i

Now as you can see we have created a multi-dimensional array having old value, new value and an index. Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment