DEV Community

Discussion on: Write Clean Code Without Loops

Collapse
 
costinmanda profile image
Costin Manda

Big fan of LINQ and am using it a lot to achieve a cleaner and easier to understand code. Sometimes, though, for loops are more descriptive, so... Golden Hammer.

However, I often see the comparison between LINQ and Javascript array functions. They are NOT the same. LINQ is optimized to work only on the items you indicate, while Javascript map/filter/reduce just apply a function on each of the items!

With new Javascript functionality we can do that in Javascript as well. Shameful self promotion here: siderite.dev/blog/linq-in-javascri...

Collapse
 
shanif profile image
Shani Fedida

I would love if you share an example of when foreach loops are more descriptive.

I didn't compare LINQ to js functions. Map filter and reduce are known from the functional programming paradigm and implemented in a lot of languages.

LINQ is lazy which makes it more efficient in some cases. I deleted the explanation about this from the post because it is long enough and I want to keep the readers focus.

Collapse
 
costinmanda profile image
Costin Manda

One example from the top of my head is finding the minimum and maximum of a list. One can use list.min() and list.max(), but it means iterating twice even if it is clearer code. One can use a reduce/Aggregate with a seed that is a tuple, but it's difficult to read. In the end, good old for or foreach loop is the simpler option.

Maybe that's not the best example, but it's what I came up with on a short notice.