functional programming
map function
JavaScript
higher-order functions
coding tutorials

Understanding the map function

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The map function is a fundamental higher-order function in programming that applies a transformation to every element of a collection and returns a new collection with the results. It is a core building block of functional programming, available in virtually every modern language — JavaScript, Python, Java, Ruby, Go, Rust, and more.

How map Works

map takes two arguments: a function and a collection. It applies the function to each element and returns a new collection of the same size:

 
map(f, [a, b, c])[f(a), f(b), f(c)]

The original collection is never modified.

JavaScript: Array.prototype.map()

javascript
1const numbers = [1, 2, 3, 4, 5];
2
3// Double each number
4const doubled = numbers.map(n => n * 2);
5console.log(doubled);  // [2, 4, 6, 8, 10]
6
7// Convert to strings
8const strings = numbers.map(n => String(n));
9console.log(strings);  // ["1", "2", "3", "4", "5"]
10
11// Extract properties from objects
12const users = [
13  { name: "Alice", age: 30 },
14  { name: "Bob", age: 25 }
15];
16const names = users.map(user => user.name);
17console.log(names);  // ["Alice", "Bob"]

map with Index

JavaScript's map provides the index and full array as additional callback parameters:

javascript
const letters = ['a', 'b', 'c'];
const indexed = letters.map((letter, index) => `${index}: ${letter}`);
console.log(indexed);  // ["0: a", "1: b", "2: c"]

Python: map() and List Comprehensions

python
1numbers = [1, 2, 3, 4, 5]
2
3# Using map()
4doubled = list(map(lambda n: n * 2, numbers))
5print(doubled)  # [2, 4, 6, 8, 10]
6
7# Using list comprehension (more Pythonic)
8doubled = [n * 2 for n in numbers]
9print(doubled)  # [2, 4, 6, 8, 10]
10
11# With a named function
12def square(n):
13    return n ** 2
14
15squares = list(map(square, numbers))
16print(squares)  # [1, 4, 9, 16, 25]

Python's map() returns a lazy iterator — results are computed on demand:

python
result = map(str, range(1000000))  # no computation yet
first_five = [next(result) for _ in range(5)]  # computes only 5

Java: Stream.map()

java
1import java.util.List;
2import java.util.stream.Collectors;
3
4List<Integer> numbers = List.of(1, 2, 3, 4, 5);
5
6List<Integer> doubled = numbers.stream()
7    .map(n -> n * 2)
8    .collect(Collectors.toList());
9// [2, 4, 6, 8, 10]
10
11List<String> strings = numbers.stream()
12    .map(String::valueOf)
13    .collect(Collectors.toList());
14// ["1", "2", "3", "4", "5"]

Chaining map with Other Operations

map is most powerful when chained with filter, reduce, and other functional operations:

javascript
1const products = [
2  { name: "Widget", price: 25, inStock: true },
3  { name: "Gadget", price: 50, inStock: false },
4  { name: "Doohickey", price: 15, inStock: true },
5  { name: "Thingamajig", price: 35, inStock: true }
6];
7
8// Get names of affordable in-stock products
9const result = products
10  .filter(p => p.inStock)
11  .filter(p => p.price < 30)
12  .map(p => p.name);
13
14console.log(result);  // ["Widget", "Doohickey"]
python
# Python equivalent
result = [p['name'] for p in products if p['inStock'] and p['price'] < 30]

map vs forEach

map returns a new array; forEach returns nothing and is used for side effects:

javascript
1const nums = [1, 2, 3];
2
3// map: transforms and returns
4const doubled = nums.map(n => n * 2);  // [2, 4, 6]
5
6// forEach: side effects only
7nums.forEach(n => console.log(n));  // prints 1, 2, 3; returns undefined

Use map when you need the result. Use forEach when you just need to do something with each element (logging, DOM updates, API calls).

Real-World Applications

  • Data Transformation: Transforming and cleaning data sets by applying operations uniformly across elements.
  • Functional Composition: When combined with other functional programming constructs, map helps build complex operations step-by-step.
  • Parallel Processing: In frameworks like Spark, similar functions enable distributed computing by applying transformations over large-scale data collections.
  • API Response Mapping: Converting raw API response objects into application-specific data structures.
  • React Components: Rendering lists of components from data arrays (items.map(item => <Item key={item.id} {...item} />)).

Common Pitfalls

  • Forgetting to return: In JavaScript arrow functions with braces, you must explicitly return. nums.map(n => { n * 2 }) returns [undefined, undefined, ...] — use nums.map(n => n * 2) or add return.
  • Mutating the original: map should not modify the input array. Avoid side effects inside the callback — keep map pure.
  • Using map for side effects: If you do not need the returned array, use forEach instead. Using map without its return value wastes memory.
  • parseInt with map: ["1","2","3"].map(parseInt) returns [1, NaN, NaN] because map passes (value, index) and parseInt interprets index as radix. Fix: .map(s => parseInt(s, 10)).
  • Performance: For very large arrays, map creates a new array in memory. If you only need to iterate, use a for loop or lazy evaluation.

Summary

  • map applies a function to every element of a collection, returning a new collection
  • It never modifies the original data — it creates a new array/list
  • Available in JavaScript (.map()), Python (map() / list comprehensions), Java (Stream.map()), and most languages
  • Chain with filter and reduce for powerful data pipelines
  • Use map for transformations, forEach for side effects

Course illustration
Course illustration

All Rights Reserved.