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:
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 arraymap()
was called upon.
thisArg
(optional): A value to use asthis
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
Example 2: Using arrow function
Example 3: Using index and array parameters
Example 4: Chaining with other array methods
Example 5: Using thisArg
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.