The map() function enables you to loop over every element in an array and modify it and then return a different element to replace the initial element. The JavaScript map() function does not change the original array, it will always return a new array. You will still have the same amount of elements as the original array.

The map() method takes a function that accepts three arguments. 

  • The first one is the current value.
  • The second one is the index.
  • The third one is the original array.

For example:

 First, create an array…

let val = [1,2,3,4];

Using the map() function

let newVal = val.map((v) => {
  return [v * v, v * v * v, v + 1];
});
console.log(newVal);

That’s pretty straightforward…right?

The map function returns a new array. Let us go through a new array. 

let languages = ["kotlin", "java", "rust", "react", "node", "python"];

Now let us create a .map function, Inside this function, we need to have a return statement and whatever we return will become the content of the new array...

let language = ["kotlin", "java", "rust", "react", "node", "python"];
console.log(language);
let langLength = language.map(function(item, index, array){
  return 6;
});
console.log(langLength);

The new array now has six 6s' in it. This means it ran twelve times and it inputs the value 6 in as the next element of each array.

Let’s put the index (second argument) in the array and see what it returns...

let language = ['kotlin', "java", "rust", "react", "node", "python"];
console.log(language);
let langLength = language.map(function(item, index, array){
  return index;
});
console.log(langLength);

You will see in your console that it outputs the index number of each array.

Now, pass in the third argument (array) of the function to the return statement...

let language = ['kotlin', 'java', 'rust', 'react', 'node', 'python'];
console.log(language);
let langLength = language.map(function(item, index, array){
  return array;
});
console.log(langLength);

When you log into the console, you will see that it lists out each item in the array.

To return multiple items, use the flatMap() function…

A better approach to returning multiples from an array is by using the flatMap() function.

const num = [2,4,6,8];
const newNum = num.flatMap((v) => [v *v, v*v*v, v+1]);
console.log(JSON.stringify(newNum));
//this would be your result [4,8,3,16,64,5,36,216,7,64,512,9]

Conclusion:

If you are running your code on the backend (node.js), especially version 10.18.1, you might get an error. Another alternative is to use [].concat() function.

The map() function returns an array of the same length as the input array so it’s not efficient when you want to create a different length result. That is where the flatMap() function comes in.