Javascript Fundamentals · Array Methods

Transform every element

map

Transform every element

You have a list of prices, and you need each one shown with tax added. The old list still matters — you want the adjusted numbers alongside it, not instead of it. So you reach for a transform that walks the list and returns a fresh one.

That transform is map. It runs a callback on every element and builds a new array: the result has the same length as the input, element i in becomes element i out, transformed. The original array is left untouched.

const prices = [10, 20, 30];

const withTax = prices.map((price) => price * 1.1);
// [11, 22, 33]

prices; // [10, 20, 30] — unchanged

map hands the callback each element (and its index, if you ask for it) and collects the return values in order into a fresh array. Because it never writes to the source, prices still holds the originals — withTax is a separate array you can pass around freely.

The pitfall: map always returns a new array of the same length. It cannot drop or add elements — if you want fewer results you are describing filter, and there is no way to skip a slot: something lands at every position.

Export withTax from index.js. Given a list of prices and a tax rate, return a new array where each price has tax added, leaving the input list unchanged.

Challenge

A list of prices comes in, and every one is quoted before tax. Adding the tax by hand means writing the same loop each time, and it is easy to reuse the source array by mistake. Export a withTax function from index.js to do the transform safely.

withTax takes an array of prices and a tax rate (for example 0.1 for 10%), and returns a new array where each price has its tax added: price * (1 + rate). The source array must not be changed.

index.js
export function withTax(prices, _rate) {
  return [...prices];
}

export function render(mount) {
  const prices = [10, 20, 30];
  const taxed = withTax(prices, 0.1);

  mount.textContent = `With tax: ${taxed.join(', ')}`;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.