Register to get access to 15+ free programming courses with interactive exercises

Mapping JS: Functions

Consider the following problem. Let's take the list of users and extract from it the names of all the users:

const users = [
  { name: 'John', age: 19 },
  { name: 'Richard', age: 1 },
  { name: 'Antony', age: 4 },
  { name: 'Alex', age: 16 },
];

const result = [];
for (const user of users) {
  result.push(user.name);
}

console.log(result); // => ['John', 'Richard', 'Antony', 'Alex']

Here we see the usual aggregation using the for...of. What if we need to extract an age? Repeat:

const result = [];
// Added destructuring
for (const { age } of users) {
  result.push(age);
}

console.log(result); // => [19, 1, 4, 16]

It is easy to see a pattern in the examples above. The same traversal is done in a loop, and the result is collected in the result array. The only thing that changes is the value we extract from the elements of the original array.

The operation we performed in both situations is called mapping. In our code, we took the original array and mapped it to another, operating as required on each element. It's crucial for the sizes of the resulting and the original array to be equal.

The task of displaying data in real code occurs literally every step of the way. This operation is so important that a special higher-order map() function was created for it:

const names = users.map((user) => user.name);
console.log(names); // => ['John', 'Richard', 'Antony', 'Alex']


const ages = users.map((user) => user.age);
console.log(ages); // => [19, 1, 4, 16]

// Or that the same thing
const callback = (user) => user.age;
console.log(users.map(callback)); // => [19, 1, 4, 16]

The map() method takes a function as the first parameter. Then, internally, map() goes through the elements of the passed collection and applies the passed function to each one. This inner function takes an element of the original array, and returns a new value which become an element of the new array that finally returns from map().

Compare the solution to the problem of getting a list of names through a loop and using the map() method. The latter has quite a few advantages. First, the code becomes much shorter. Second, the repetitive traversal logic is hidden from us. It is no longer necessary to explicitly define the cycle and perform all those operations by hand, which may be omitted. The map() method allows you to focus on the essence of what is happening, hiding unnecessary details (looping).

A usual example that different programming languages like to give in their map() documentation is to apply some arithmetic operation to each item in the collection:

const numbers = [5, 2, 3];

const newNumbers = numbers.map((number) => number ** 2);
console.log(newNumbers); // => [25, 4, 9]

const newNumbers2 = numbers.map((number) => number + 3);
console.log(newNumbers2); // => [8, 5, 6]

The example looks artificial, but captures the essence of the operation well.

Implementation

Let's write our own function myMap(), which works similarly to the map() array method:

const myMap = (collection, callback) => {
  const result = [];
  for (const item of collection) {
    // Call the passed callback on each item in the collection
    const newItem = callback(item);
    // The return from the callback is added to the resulting array
    result.push(newItem);
  }

  return result;
};

const numbers = [5, 2, 3];
const newNumbers = myMap(numbers, (number) => number ** 2);
console.log(newNumbers); // => [25, 4, 9]

The main difference between the myMap() (and the map() method) and the manual array traversal is that myMap() does not know what to do with each element of the array. So it takes as its second argument a function that it calls (that's why it's a callback) for each element of the original array, and the call result is written to the output array. The myMap() function doesn't know what this result will be, and it doesn't need to know that. Processing is the responsibility of the users.


Recommended materials

  1. map

Аватары экспертов Хекслета

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From zero to a developer. Refunds in case you won't get a job

Frontend Developer icon
Profession
New
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions

Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.