DEV Community

Cover image for 5 Anti-Patterns to Avoid When Working With Collections in JavaScript

5 Anti-Patterns to Avoid When Working With Collections in JavaScript

jsmanifest on December 07, 2019

Find me on medium Working with collections in JavaScript can become an appalling task especially when there is a lot going on in a function block....
Collapse
 
blindfish3 profile image
Ben Calder • Edited

In section 1 you say:

Most developers especially those who are more into functional programming may find this to be clean, concise and performant at its best

I'm curious to know how many advocates of FP would write an add function in that way; where you use a callback to act on the result. You'd normally just return the result directly and avoid things that might cause unexpected side-effects (such as callback functions).

Also the uncondensed version is subject to the same bug:

numbers.forEach(function(nums, callback) {

The problem you demonstrate is that you need to be familiar with the argument signature passed from Array iteration functions. It's true that passing a function name means you may be less likely to spot the issue; but in my experience it's also rare to not write the function inline anyway.

Collapse
 
eenewbsauce profile image
Ryan Tracey • Edited

This is a misguided article. I like the idea but the actual examples are poor. It may lead beginners astray, which is more dangerous.

Collapse
 
softmantk profile image
NIKHIL CM • Edited

Thanks for this nice article!
What could be the possible solution for the problem no. 1, Prematurely passing functions as direct arguments ?

I could n't perceive. Sorry.

Collapse
 
larrybolt profile image
Larry Boltovskoi

Perhaps an inline function there would be less confusing if it's a one-time, otherwise having a function taking the array as a parameter and output an array as sums, and having a clear name what it does.

const numbers = [[1, 2], [2, 2], [18, 1], [4, 5], [8, 9], [0, 0]]
const numberSums = numbers.map(([a,b]) => a+b)
// [3, 4, 19, 9, 17, 0]
Collapse
 
suraneti profile image
Suraneti Rodsuwan

If an input is a heavy huge array, using simple for-loop or while-loop for me is the best choice for optimized performance.

Collapse
 
vonheikemen profile image
Heiker

I see that one as lack of information. It doesn't matter if you pass the reference to the function or create it inline, the function signature is what is causing the problem. The solution is to search documentation about both function and make sure they are compatible.