JavaScript map(callback) method


The map() method in JavaScript creates a new array populated with the results of calling a provided callback function on every element in the calling array. It is commonly used for transforming data within an array.

Syntax:

let newArray = array.map(callback(currentValue, index, array), thisArg)
  • callback: A function that is called for each element in the array. It can accept up to three parameters:
    • currentValue: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array map() was called upon.
  • thisArg (optional): A value to use as this when executing the callback function.

Return Value:

  • A new array containing the results of applying the callback function to each element in the original array. The original array is not modified.

Key Points:

  • Creates a new array: The map() method returns a new array, leaving the original array unchanged.
  • Does not modify the original array: Unless explicitly done within the callback, the original array remains unaffected.
  • Works with all array elements: It processes each element in the order they appear in the array.

Example 1: Basic usage

let numbers = [1, 2, 3, 4]; let doubled = numbers.map(function(number) { return number * 2; }); console.log(doubled); // [2, 4, 6, 8] console.log(numbers); // [1, 2, 3, 4] (original array unchanged)

Example 2: Using arrow function

let fruits = ['apple', 'banana', 'orange']; let fruitLengths = fruits.map(fruit => fruit.length); console.log(fruitLengths); // [5, 6, 6]

Example 3: Using index and array parameters

let numbers = [10, 20, 30]; let results = numbers.map(function(number, index, array) { return number + index; // Adding index to each element }); console.log(results); // [10, 21, 32]

Example 4: Chaining with other array methods

let numbers = [1, 2, 3, 4, 5]; let squaredEvens = numbers .map(number => number * number) // Square each number .filter(squared => squared % 2 === 0); // Filter only even squares console.log(squaredEvens); // [4, 16]

Example 5: Using thisArg

let multiplier = { factor: 3 }; let numbers = [1, 2, 3]; let multiplied = numbers.map(function(number) { return number * this.factor; }, multiplier); console.log(multiplied); // [3, 6, 9]

Summary:

  • The map() method is a powerful tool for transforming elements in an array.
  • It creates a new array based on the results of applying the callback function to each element in the original array.
  • It is commonly used in functional programming paradigms for data transformation and manipulation, allowing for clean and readable code.