Menu
Coddy logo textTech

Map

Lesson 13 of 18 in Coddy's Array Methods in JavaScript course.

map() is a built-in method for arrays that acts like a transformation machine. It iterates through each element in the array and applies a function you define (the callback function) to each element. This function can modify, transform, or create something entirely new based on the original element. The result of these transformations is then used to populate a brand new array.

Imagine you have a list of product prices (numbers) and you want to create a new list showing discounted prices (transformed elements). Here's how map() comes into play:

const prices = [10, 15, 20, 25];

// Callback function to apply a 10% discount
const discountedPrices = prices.map(price => price * 0.9);

console.log(discountedPrices); // Output: [9, 13.5, 18, 22.5]

In the above example, it uses map() to create a new array discountedPrices containing prices with a 10% discount. The map() method iterates through prices and applies the discount calculation (price * 0.9) to each item, resulting in the discounted prices in the new array.

challenge icon

Challenge

Easy

You have given an array inventory of numbers representing item quantities in stock.

Your task is to write JavaScript code that creates a new list displaying the quantity of each item doubled, then logs the updated list.

Try it yourself

const inventory = [5, 3, 2, 1];

// Write code here

All lessons in Array Methods in JavaScript