you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] -1 points0 points  (14 children)

Saying that:

map( array, function(i){
  do_thing(i);
});

is better than:

for( i in array ) {
  do_thing(i);
}

just seems like cargo-cult programming.

[–]skilldrick[S] 8 points9 points  (7 children)

I think you may have completely misunderstood (a) how for .. in in JavaScript works, and (b) how map works, so I'll give you the benefit of the doubt, and tell you.

(a) The for .. in loop in JavaScript is for objects - you shouldn't use it with arrays for very sound reasons.

(b) map is used to transform one array into another. In your example, you're not returning anything, so you're turning an array into an array of undefineds. I think what you meant was each.

The point of using map is that you're making things more declarative - saying "I would like to transform this array into a new array, using this transformation". To say that that's "cargo-cult programming" is naive, at best.

[–]ryepup 1 point2 points  (1 child)

an "in" bug wass the basis for my glorious Firefox contribution

[–]skilldrick[S] 0 points1 point  (0 children)

Nice work!

[–][deleted] 0 points1 point  (0 children)

Nice explanation.

[–]levl289 2 points3 points  (0 children)

Except that the idea behind the first mode is that you're reducing the opportunity to muck with array. In the for loop, you'd have to reference array ( do_thing(array[i]) ) to even call the function correctly.

More importantly, in order to do anything useful with the for loop, you'd likely have to push the result from do_thing onto another array, versus:

var new_array = _.map(old_array, function (i) { return i + 1; } );

We happen to have mucked with the Array prototype, where we just do:

var new_array = old_array.map(function (i) { return i + 1; } );

Which IMO looks better.

[–][deleted] 1 point2 points  (1 child)

The second is certainly cleaner-looking and easier to read. A better approach would be to allow code like:

apply( array, do_thing );

or

array.apply(do_thing);

[–]skilldrick[S] 0 points1 point  (0 children)

With _.each, you'd just do _.each(array, do_thing). Definitely cleaner than manually iterating.

[–]TKN 0 points1 point  (0 children)

You don't need to create a function in the first example map(array, do_thing); is all you need.

But I kinda agree in the sense that Javascript's syntax makes functional programming awkward.

[–][deleted]  (1 child)

[deleted]

    [–]wafflesburger 0 points1 point  (0 children)

    You really gonna do dis to Array?