JavaScript map() Function
Subject: JavaScript
The map() function in JavaScript is a built-in array method that creates a new array by applying a transformation function to each element of the original array. It’s a core concept in functional programming for manipulating data without altering the original source.
What is map() in JavaScript?
The map() method executes a callback function once for every element in the array and returns a new array of the results.
✅ The original array is not modified.
Syntax
Parameters:
currentValue: The current element being processed.index(optional): The index of the current element.array(optional): The arraymap()was called upon.
Example 1: Basic Transformation
Example 2: Using Index with map()
Example 3: Mapping Array of Objects
Example 4: Creating JSX/HTML-like Strings
Chaining map() with Other Methods
You can combine map() with other methods like filter(), reduce(), etc.:
When to Use map() vs forEach()
| Feature | map() | forEach() |
|---|---|---|
| Returns | New array | Undefined |
| Mutation | Doesn’t mutate original | Doesn’t mutate original |
| Use Case | When you want a new array | When you're performing side effects like logging |
Key Takeaways
map()is great for transforming data in arrays.- It returns a new array of the same length.
- The original array is never modified.
- Works well with arrow functions and chaining.
- Ideal for generating HTML, JSX, or transformed datasets.