Transform Values
map creates a new array by applying a function to each element.
It never changes the original array.
JavaScript Tutorial
map transforms every element in an array and returns a new array.
It is perfect for formatting data or converting shapes.
map makes transformations declarative and readable.
It avoids manual loops and keeps data pipelines clean.
array.map((value, index, array) => newValue)const nums = [1, 2, 3];
const squared = nums.map((n) => n * n);
console.log(squared);Transform each number into its square.
const names = ["ada", "sam"];
const caps = names.map((n) => n.toUpperCase());
console.log(caps);Create a new array of formatted strings.
map creates a new array by applying a function to each element.
It never changes the original array.
map always returns an array of the same length.
If you need fewer items, use filter instead.
The callback receives value, index, and the original array.
Use index when you need position-based logic.
const items = ["a", "b"];
const labeled = items.map((item, i) => i + ":" + item);
console.log(labeled);Use the index parameter when needed.
const users = [{ id: 1 }, { id: 2 }];
const ids = users.map((u) => u.id);
console.log(ids);Pick fields from objects into a new array.
Without
const out = [];
for (const n of nums) {
out.push(n * 2);
}With
const out = nums.map((n) => n * 2);Use forEach when you are not returning a new array.
Return new objects instead of mutating existing ones.
Use filter to remove items.
A new array with transformed values.
When you only need side effects; use forEach.
No, map does not mutate the original array.
Practice: Convert an array of prices to include tax at 18 percent.
const prices = [10, 20, 30];
// TODO: return prices with tax added
One Possible Solution
const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.18);
console.log(withTax);No, it returns a new array.
Yes, map can be chained with filter, reduce, and more.
A new array with the same length as the original.
Try mapping different transformations.