Course

array.map()

In this lesson, you'll learn about the method in JavaScript, which is used to create a new array by applying a function to each element of an existing array.

Array.map()

The key difference between and is that the method allocates memory to store and return a new array, while does not allocate memory and returns .

The method is used for executing a function on each array element without returning a new array, whereas returns a new array with the results of applying a function to each element.

When using , you can think of it as iterating over each element and transforming it in some way, resulting in a new array.

How to use

Let's consider a local shop's inventory:

// A local shop's inventory
const inventory = [
    { price: 5, name: 'eggs' },
    { price: 5, name: 'ham' },
    { price: 5, name: 'mayo' },
    { price: 5, name: 'bread' },
];

// A customer asks for a list of all the inventory they have
const requestFullInventory = inventory.map(item => item);

console.log(requestFullInventory); // requestFullInventory is filled with the inventory that we have

How it works

  • Transformation: The method applies a function to each element of the array, transforming it in some way.
  • New Array: It returns a new array containing the transformed elements, leaving the original array unchanged.

The method is a powerful tool for creating new arrays based on transformations of existing arrays , making it an essential part of functional programming in JavaScript.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Array.filter()