4 ms·
I disagree on items.forEach(function(item) { doSomething(item); }); being an anti pattern. Many of these looping functions actually pass mor
by ufo 12y ago
I disagree on
items.forEach(function(item) {
doSomething(item);
});
being an anti pattern. Many of these looping functions actually pass more than one argument to the callback, so writing
items.forEach(doSomething);
will break if doSomething is a function with optional arguments.
- mrspeaker 12y agoYeah - not being aware of this will screw you up! ['10','10','10','10','10'].map(parseInt) // [10, NaN, 2, 3, 4]
- marcosdumay 12y agoSeveral "wat!"s on that line... I didn't know "10" was a number in base 0.
- Bognar 12y agoIt gets even weirder: parseInt('10', {test: 'test'}) 10 parseInt('10', 'test') 10 parseInt('10', '2') 2
- serve_yay 12y agoIndeed. The first version is actually more explicit in the sense that you know that only the `item` parameter is being passed to the function. The extra verbosity is worth it in my opinion. It's true that in many cases the shorter version would not be harmful, but I have been bitten by a somewhat similar case where I meant for for the callback to be called with no arguments. Since the callback was passed in the latter style, it was called with arguments and the undesired behavior was difficult to debug. Or rather, it would have been, except that I work with incredibly smart people who saw the problem almost instantly.
- bahmutov 12y agoThis point-free programming style is good thing but requires knowing the exact method signatures. Luckily there are ways to easily adapt callbacks http://bahmutov.calepin.co/point-free-programming-is-not-pointless.html http://bahmutov.calepin.co/point-free-programming-is-not-poi...
- lgas 12y agoSince this is a common occurrence, it might make sense to define a helper function to make it more natural, maybe something like: function only1(f) { return function(x) { return f(x); }; } then your example becomes: items.forEach(only1(doSomething)); Edit: just realized this is what "spots" in the blog post bahmutov linked to does (except spots is more flexible).