I know that map() is meant to iterate lists, run a function on each member and return (or not return) a value as a list item. But what if I use it the same way as I would use forEach()?
Example:
var stuff = [1, 2, 3];
var newStuff = {};
var moreStuff = [];
stuff.forEach(function(value, key){
newStuff[value] = {'value' : value};
moreStuff.push({'other_stuff': value});
});
$('body').append('<div>1. ' + JSON.stringify(newStuff) + '/' + JSON.stringify(moreStuff) + '</div>');
//vs.
newStuff = {};
moreStuff = [];
stuff.map(function(value, key){
newStuff[value] = {'value' : value};
moreStuff.push({'other_stuff': value});
});
$('body').append('<div>2. ' + JSON.stringify(newStuff) + '/' + JSON.stringify(moreStuff) + '</div>');
results...
1. {"1":{"value":1},"2":{"value":2},"3":{"value":3}}/[{"other_stuff":1},{"other_stuff":2},{"other_stuff":3}]
2. {"1":{"value":1},"2":{"value":2},"3":{"value":3}}/[{"other_stuff":1},{"other_stuff":2},{"other_stuff":3}]
https://jsfiddle.net/0n7ynvmo/
I'm pretty sure, async considerations are the same (and might botch this example), and results are the same, but for the sake of discussion of best practices, what are the drawbacks to one way vs. another? Is it an abuse of the map() method to change a previously scoped variable within the function and not actually return anything? Is the correct answer simply a matter of discretion?
mapinstead offorEachwhen you're not interested in the result ? And why aren't you just buildingmoreStuffas a returned value ofmapin this precise case ?mapworked and that tymeJV's answer probably addressed this confusion, but just to make sure :mapwill always return a transformed array, whose values will be the result of the application of the provided function to the original array's values. If said function does not explicitly return any value, it will be an array ofundefinedvalues (as implicitly returned by the function)