JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 7: Functional Array ProcessingLesson 32 of 150About 40 minutes

Lesson 32: map and transformations

01Opening question

A price list in dollars must be shown in euros, with labels. How do you turn every element of an array into something new without changing the original?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

map returns a new array of the same length, built from each callback's return value.

const prices = [10, 25, 4];
const withTax = prices.map((p) => p * 1.2);
console.log(withTax);
console.log(prices);

03Objective and prerequisites

Learning objective: Use map to transform every element into a new array, return values correctly from callbacks, map arrays of objects to new shapes, and keep the original unchanged.

You need: Lesson 31: forEach and iteration

Skills practised: Functional array processing, Transforming with map.

04Explanation

list.map(fn) calls fn for each element and collects the return values into a new array of the same length.

The original array is not changed. You get a new array: const labels = prices.map((p) => "$" + p);.

The callback must return a value. With braces { } you need return; without braces the expression is returned automatically.

map is perfect for turning objects into strings for display, or into new objects with a different shape: users.map((u) => u.name).

05Definitions

map
Creates a new array from the return value of a function called on each element.
Transformation
Turning each input value into an output value.
Pure function
A function whose result depends only on its inputs and that changes nothing outside.
Projection
Mapping objects to just the properties you need, such as names.
Implicit return
An arrow function without braces returns its expression.

Open the full glossary

06Visual learning object

Map transformation visualizer. Each input element, the value the callback returns and the new array, side by side.

Loading the interactive object…

Open the full Map transformation visualizer page with its guided experiment.

07Examples

ex-032-01Transform numbers Browser-executable JavaScript

One output for every input; the original stays the same.

const celsius = [0, 20, 37];
const fahrenheit = celsius.map((c) => c * 9 / 5 + 32);
console.log(fahrenheit);
console.log(celsius);
Sample input
None
Expected output
[32, 68, 98.6] [0, 20, 37]
Common mistake
Expecting map to change celsius.
Try this
Round each Fahrenheit value with Math.round.
Source
examples/ex-032-01-transform-numbers.js (repository pending publication)

ex-032-02Objects to display strings Browser-executable JavaScript

map turns data into lines to show.

const products = [
  { name: "Lamp", price: 30 },
  { name: "Rug", price: 12.5 }
];
const labels = products.map((p) => `${p.name}: $${p.price.toFixed(2)}`);
console.log(labels.join(" | "));
Sample input
None
Expected output
Lamp: $30.00 | Rug: $12.50
Common mistake
Forgetting join and printing the array brackets.
Try this
Add the index to each label.
Source
examples/ex-032-02-objects-to-strings.js (repository pending publication)

ex-032-03A block body needs return Browser-executable JavaScript

Without return, every element becomes undefined.

const nums = [1, 2, 3];
const wrong = nums.map((n) => { n * 10; });
const right = nums.map((n) => { return n * 10; });
console.log(wrong);
console.log(right);
Sample input
None
Expected output
[undefined, undefined, undefined] [10, 20, 30]
Common mistake
Adding braces and forgetting return.
Try this
Rewrite right without braces.
Source
examples/ex-032-03-missing-return.js (repository pending publication)

ex-032-04New objects, original untouched Browser-executable JavaScript

Spread copies each object and adds a property.

const cart = [
  { item: "Pen", qty: 3, price: 1.5 },
  { item: "Pad", qty: 1, price: 4 }
];
const lines = cart.map((line) => ({ ...line, total: line.qty * line.price }));
console.log(lines[0].total, lines[1].total);
console.log("total" in cart[0]);
Sample input
None
Expected output
4.5 4 false
Common mistake
Writing line.total = ... inside map, which changes cart.
Try this
Also add a label property.
Source
examples/ex-032-04-new-objects.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Return from the callback

Fix a map callback that returns nothing.

const names = ["ada", "grace"];
const capitalised = names.map((n) => {
  n[0].toUpperCase() + n.slice(1);
});
console.log(capitalised);

Convert currency

Map numbers to formatted strings.

const usd = [10, 45.5, 3];
const RATE = 0.9;
// TODO: map to euro strings like "€9.00"

Student report cards

Map objects to new objects without mutating the source.

const students = [
  { name: "Ada", scores: [90, 85, 95] },
  { name: "Linus", scores: [70, 65, 80] }
];

09Prediction

Commit to an answer first, then run the real code to compare.

const r = ["10", "10", "10"].map(parseInt);
console.log(r);

What is printed?

10Debugging investigation

Showing sale prices changes the catalogue

After showing a 50% sale view, the normal catalogue also shows half prices.

const catalogue = [{ name: "Mug", price: 20 }];
const sale = catalogue.map((p) => {
  p.price = p.price / 2;
  return p;
});
console.log("Sale:", sale[0].price);
console.log("Normal:", catalogue[0].price);

More cases in the Debugging Detective Laboratory

11Practical scenario

Formatting an order history

An account page receives order objects from the server and maps them into display rows: date, item count and formatted total. The server data is never modified.

const orders = [{ id: 7, total: 19.5 }, { id: 8, total: 7 }];
console.log(orders.map((o) => `#${o.id} $${o.total.toFixed(2)}`));

12Knowledge check

1. What is printed?

console.log([1, 2, 3].map((n) => n * 2));
  • [2, 4, 6]
  • [1, 2, 3]
  • undefined
  • 12

2. How long is the array map returns?

  • Shorter
  • The same length as the original
  • Longer
  • It depends on the callback

3. What is printed?

console.log(["a"].map((s) => { s.toUpperCase(); }));
  • ["a"]
  • [undefined]
  • ["A"]
  • An error

4. Why does the original cart change?

const out = cart.map((l) => { l.total = l.qty * l.price; return l; });
  • map always mutates
  • The callback changes each object before returning it
  • join mutates
  • Spread mutates

5. What is printed?

console.log([{ name: "Ada" }, { name: "Bo" }].map((u) => u.name));
  • ["Ada", "Bo"]
  • [{name: "Ada"}, {name: "Bo"}]
  • Ada,Bo
  • undefined

6. Which converts strings to numbers safely?

  • list.map(parseInt)
  • list.map(Number)
  • list.forEach(Number)
  • list.map(String)

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Return from the callback: Prints the names; capitalised is correct
  • Convert currency: Prints euros; usd unchanged; Uses map
  • Student report cards: Prints the cards; toCard works alone; students unchanged
  • ex-032-01: output matches the documented expected output
  • ex-032-02: output matches the documented expected output
  • ex-032-03: output matches the documented expected output
  • ex-032-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-07-functional-array-processing/lesson-032-map-and-transformations/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • map returns a new array of the same length.
  • The callback must return the new value.
  • map does not change the original, unless the callback mutates objects.
  • Use spread to create new objects inside map.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation map transformations
Context: I am learning map transformations in JavaScript.
Task: Explain map with prices and objects, including why the callback must return a value.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction map transformations drill
Context: I have practised map transformations.
Task: Give me six map calls and ask for the resulting arrays, including one parseInt trap.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging map transformations bug
Context: My map returns an array full of undefined.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation map transformations practice
Context: I finished the map transformations exercises.
Task: Create three map exercises that reshape arrays of objects.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review map transformations review
Context: Here is my code that uses map transformations.
Task: Review my map callbacks for missing returns and accidental mutation.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.