JavaScript

map() Method Returns Undefined in JavaScript [Fixed]

The map function is used to map one value to another, and it returns a new array, and elements of arrays are the result of the callback function. If you will not return anything from the callback function, it returns an “undefined”.

This article will explain the occurrence and the solution to the mentioned error.

How Does “map() Method Returns Undefined in JavaScript” Occur?

As you know, the map() method returns an array that contains elements/values returned by the callback function. So, when you return nothing from the callback function to the method, it will give “undefined”.

Example
In the given example, first, we will create an array of odd numbers:

const array = [1, 3, 5, 7, 9];

Then, call the map() method, and in the callback function, we will multiply all the array elements with “2”:

const newArray = array.map(element => {
 var result = element * 2;
});

Finally, print the resultant array on the console:

console.log(newArray);

The output shows the undefined values in an array because nothing is returned from the callback function:

How to Fix “map() Method Returns Undefined in JavaScript” Issue?

To fix the above-discussed issue, return the value from the callback function to the map() method. Here, we will call the map() method and return the result to the method after multiplying every element of an array with “2”.

const newArray = array.map(element => {
 var result = element * 2;
 return result;
});

Output

That’s all about fixing the map method returns undefined in JavaScript.

Conclusion

The map() method returns undefined when you will not return anything in the callback function to the method. To fix it, you must return the value from the callback function to the map() method. Because the map() method gives an array that contains the values/elements returned by the callback function. In this article, we explained the occurrence and the solution to the mentioned error.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.