Array method returns undefined for every item
Locate the failed assumption, reproduce it, then repair the cause.
What actually caused it
There are two related symptoms to distinguish. Map collects each 's returned value. If a braced callback calculates a result but never returns it, the mapped contains for each visited item.
ForEach does not build a transformed at all. Its own return value is , even if its returns a value. Assigning the result of forEach therefore gives a single undefined value, not an array of undefined items.
Inspect both the and the 's return paths. A callback can also return on one branch and forget to return on another, producing only some entries.
Minimal reproduction
Map without a return
const values = [1, 2];
const doubled = values.map(value => { value * 2; });
console.log(doubled);Expecting a result from forEach
const values = [1, 2];
const doubled = values.forEach(value => value * 2);
console.log(doubled);The fix
Use map when you need one output per input, and return the transformed value on every intended path. An -body arrow returns implicitly; a braced body needs return.
Keep forEach for when no transformed result is needed. Use filter for selection instead of returning nothing from map to discard an item. Neither automatically waits for callbacks; async collection requires its own promise strategy.
Map and return each result
const values = [1, 2];
const doubled = values.map(value => {
return value * 2;
});
console.log(doubled);