JavaScript : How to creates a new array populated with the results of calling a provided function on every element : map()

Java Script @ Freshers.in

JavaScript arrays are fundamental data structures used extensively in web development. Among the array methods available, map() stands out for its versatility in transforming array elements. In this article, we’ll delve into the intricacies of map(), its syntax, functionality, and practical applications with detailed examples.

Understanding map()

The map() method in JavaScript creates a new array populated with the results of calling a provided function on every element in the calling array. It offers a concise and powerful way to transform array elements without mutating the original array.

Syntax

The syntax for map() is straightforward:

array.map(callback(currentValue, index, array), thisArg);

Here, array represents the array to be traversed, callback is the function to execute for each element, and thisArg (optional) is the value to use as this when executing the callback.

Examples

Let’s explore various scenarios to understand the versatility of map():

Example 1: Doubling Array Elements

const nums = [1, 2, 3, 4];
const doubledArray = nums.map(num => num * 2);
console.log(doubledArray);
// Output: [2, 4, 6, 8]

Example 2: Mapping to Objects

const people = [
  { name: 'Sachin', age: 30 },
  { name: 'Raju', age: 25 },
  { name: 'Babu', age: 35 }
];

const names = people.map(person => person.name);

console.log(names);
// Output: ["Alice", "Bob", "Charlie"]

Example 3: Using thisArg Parameter

const nums = [1, 2, 3, 4];
let sum = 0;

function addToSum(num) {
  sum += num * this.multiplier;
}

nums.map(addToSum, { multiplier: 2 });

console.log(sum);
// Output: 20 (2*1 + 2*2 + 2*3 + 2*4)

The map() method in JavaScript provides a powerful tool for transforming array elements, enhancing code readability and maintainability. Whether it’s doubling numbers, extracting properties, or performing custom operations, map() streamlines the process with its intuitive syntax and functionality.

Author: user