[SOLVED] – Map Function Returns Undefined in JavaScript

why map function returns undefined in javascript

If you use .map function and add some conditional statements in the callback function it may return undefined. Here is a simple example where .map function returns undefined.

Using filter instead of map function

In most cases where you are using a conditional statement inside the map, you can fix it by just using .filter function. Check the example below, you can just replace .map with .filter to fix the undefined issue.

In some situations, you may want to use .map function not filter because of some calculations. Let’s say you want to map through all the elements and if the element meets a condition you want to perform some calculations. Check the example below where we have to return a modified element.

Getting rid of falsy values with filter method

Now, you can’t replace .map with .filter to get your desired results because the filter method doesn’t return a modified element. In this case, to get rid of undefined from the output use filter at the end of map function with Boolean argument. Check the example below.

 

In the above example, we are returning a modified element from the .map function and at the end of the map, all the falsy values are filtered with the .filter method.

Conclusion

You can either use the filter function instead of the map function to get rid of undefined values, or you can filter all the falsy values with the help of the filter method after the map function.

Leave a reply

Please enter your comment!
Please enter your name here