4m1r 4m1r - 4 months ago 14
Javascript Question

Is it bad practice to use JavaScript Array.prototype.map with scoped variables

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?

Answer

Not really many drawbacks - except in forEach you're not returning a new list. But in your case, you want a new list, so use .map

var newStuff = {};

moreStuff = stuff.map(function(value, key){
    newStuff[value] = {'value' : value};
    return {'other_stuff': value};
});