Employing .Map() For Iterating Through Array Items in JavaScript

We’re aware of the various techniques and methods employed to iterate through datasets in JavaScript, ranging from classic for loops to the forEach() method. One particularly popular method is the .map() method.

This method serves various purposes when working with arrays. In this article, we’ll explore the utilization of .map() in JavaScript for invoking a function on array elements and examine a use case in LWC.

Invoking a Function on Every Item in an Array

.map() receives a callback function as one of its arguments, with a crucial parameter being the current value of the item undergoing processing by the function. This parameter is obligatory. Leveraging this parameter, you can alter each item within an array and return it as a modified element of your new array.

const numArray = [2, 3, 4, 5, 6]
const numArray = numArray .map(numItem => {
return numItem * 2

The following output is printed to the console:

Output[ 4, 6, 8, 10, 12 ]

This can be simplified even further as:

// create a function to use
const makeSpicy = makeSpicy => makeSpicy * 2;

// we have an array
const makeSpicier = [2, 3, 4, 5, 6];

// call the function we made. more readable
const makeSpicyArray = makeSpicy .map(makeSpicier );


The same output is logged to the console:

Output[ 4, 6, 8, 10, 12 ]

Now, let’s examine how it’s utilized in LWC:

Consider a wire adaptor used to call an apex function and we iterate on the returned data using map:

this.accountList = data.map(item=>{

let newType = item.Type === 'Customer - Channel'? 'Channel':'Direct'
return (newType);