In this tutorial you’ll learn how you can use the function map to transform the JavaScript array by applying a mapping function to all of its elements.

The biggest drawback of the forEach loop is that it doesn’t return anything useful. If we want to get an array doubleArr where each element is equal to the element arr multiplied by two, then forEach won’t help.

To get an array equal in length to the initial array, but with modified elements, use the map function.

const arr = [ -1, 2, 4, 0, -5, 7 ];
const doubleArr = arr.map(item => item * 2);

console.log(arr); // [ -1, 2, 4, 0, -5, 7 ]
console.log(doubleArr); // [ -2, 4, 8, 0, -10, 14 ]

Note that the array arr has not changed in any way.

Together with filter, the map method is one of the most used array methods in JS.

Both filter and map return an array, so you could combine them into chains.

Let’s go back to the user example. The task is to create an array with the names of all users whose age is less than 18 years.

Let’s first apply the filter function to throw away all the underage users and then use map to transform an array of objects to an array of strings.

const users = [
  {name: 'Jake', age: 15},
  {name: 'John', age: 16},
  {name: 'Jill', age: 25},
  {name: 'Bill', age: 82},
];

const kidsNames = users
  .filter(user => user.age < 18)
  .map(user => username);

console.log(kidsNames); // [ 'Jake', 'John' ]

It will become very easy for you to read such code after you get used to the syntax.

The task of creating a new array from an existing one arises so often that the forEach loop can safely be called the most useless method in JavaScript. It’s almost always better to use map or a regular for loop instead.