1
[1, 3, 4, 5, 5, undefined, 4, 3, 4].map((item) => {
    if (item) {
        return item
    }
})

The output of the above code is

enter image description here

Why is undefined also returned, shouldn't it be stopped by the if loop?

Ivan
  • 34,531
  • 8
  • 55
  • 100
Shiva Sai
  • 463
  • 4
  • 12
  • 3
    You're probably looking for `filter` because `map` return the same size like the original array – Alon Eitan Dec 26 '20 at 09:26
  • 2
    Does this answer your question? [Removing undefined values from Array](https://stackoverflow.com/questions/28607451/removing-undefined-values-from-array) (or [How to remove undefined and create a new array Javascript?](https://stackoverflow.com/questions/44749528/how-to-remove-undefined-and-create-a-new-array-javascript), or [Why does javascript map function return undefined?](https://stackoverflow.com/questions/16037049/why-does-javascript-map-function-return-undefined) – pilchard Dec 26 '20 at 11:12

1 Answers1

2

Your map function doesn't return anything explicitly if the item is falsy, hence it returns undefined (per default).

As another comment has pointed out, you are probably looking for Array.prototype.filter:

console.log([1,3,4,5,5,undefined,4,3,4].filter((item)=>{
  if(item){
    return item;
  }
}));

Note that the above is slightly verbose, .filter(x => x) would suffice, filter calls ToBoolean on the return anyways. It will still filter out any falsy values though, e.g. 0.

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33