JavaScript Array’s map () Method

The JavaScript Array’s map ()  method is a high-order array function in JavaScript that allows you to transform each element of an array according to a given mapping function.

 JavaScript map() method  iterates through the elements of the array, applies the provided function to each element, and creates a new array with the results of these function calls. The original array remains unchanged.

Basic syntax for map() method :

				
					const newArray = originalArray.map(function(currentValue, index, array) {
  // return transformed value based on currentValue
});

				
			
  • currentValue: The current element being processed in the array.
  • index: The index of the current element.
  • array: The array being iterated.

For example, suppose you have the following array element:

 

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

Now imagine you are required to multiply each of the array’s elements by 3. You might consider using a for loop as follows:

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

for (let i = 0; i < arr.length; i++){
  arr[i] = arr[i] * 3;
}

console.log(arr); // [9, 12, 15, 18]
				
			

Iterate over an array using for loop

But you can actually use the Array map()  method to achieve the same result. Here’s an example:

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

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

console.log(modifiedArr); // [9, 12, 15, 18]
				
			

Iterate over an array using map() method

 For more information about JavaScript:

click here for YouTube video…

Leave a Reply

Your email address will not be published. Required fields are marked *