[1, 3, 4, 5, 5, undefined, 4, 3, 4].map((item) => {
if (item) {
return item
}
})
The output of the above code is
Why is undefined
also returned, shouldn't it be stopped by the if
loop?
[1, 3, 4, 5, 5, undefined, 4, 3, 4].map((item) => {
if (item) {
return item
}
})
The output of the above code is
Why is undefined
also returned, shouldn't it be stopped by the if
loop?
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.