How to Use the map() Method in JavaScript

How to Use the map() Method in JavaScript

·

3 min read

Definition

JavaScript map() method is a powerful and commonly used array method that creates a new array by applying a given function to every element of the original array.

The key characteristics of map() is that it does not modifies the original array but rather it creates a new one based on function's result.

Syntax

original_array.map( (value,index,array) => {
    // method to preform on each element
})
  • original_array -> the array on which we apply function

  • callback function -> The callback can accept upto three arguments and this callback will run for every element

  • value -> The current element being processed in the array

  • index -> It is optional to add. It is the index of current element being processed

  • array -> It is optional to add. It is an Original array

Usage

let arr = [1,2,3,4,5]
arr.map( (val,index, array) => {
    console.log(val*2, index , array)
})

/* Output ->
2 0  [1, 2, 3, 4, 5]
4 1  [1, 2, 3, 4, 5]
6 2  [1, 2, 3, 4, 5]
8 3  [1, 2, 3, 4, 5]
10 4 [1, 2, 3, 4, 5]
*/

Using ES6 Feature

If you want to store the result in a new array you can declare the variable and assign the method in that variable. Also if you are going to store the values in a new array then make sure to use return statement because this is the only way you can store the values or data in a variable while applying a method in to it.

// storing the result in a variable
let arr = [1,2,3,4,5]
let newArr = arr.map((value) => {
    return value*2
})
console.log(newArr) // [2, 4, 6, 8, 10]

Creating Callback function

we can call a function instead of doing all that in one line, well it is recommended to pass the function as arrow function instead of creating a new one and pass the reference in place of that callback.

In this we do the things which we have done in above method, The only differences are the line numbers. We need to write more code if we pass the function as args. But the result will be same so you can select any way.

let arr = [1,2,3,4]
let newArr = arr.map(fun)

function fun(value){
    return value * 2
}
console.log(newArr) // [2, 4, 6, 8]

JavaScript map() method creates a new array by applying a function to each element of the original array without modifying it. It can be used with callback functions or stored in a new array using ES6 features.


Congratulations !!!!! You have learned something new today...

Instagram ----> React Mastery Series is going on

LinkedIn

I hope you have learned something new today. If yes, then follow me for more such valuable content.


Written By MOHIT SONI