How does the Array.map() method work?
Asked on Jul 29, 2024
Answer
The Array.map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
<!-- BEGIN COPY / PASTE -->
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The Array.map() method does not modify the original array; it returns a new array.
- The provided function is called once for each element in the array.
- The function can take up to three arguments: the current element, the index of the current element, and the array itself.
- Array.map() is useful for transforming data in an array without mutating the original data.
Recommended Links:
← Back to All Questions