DEV Community

Discussion on: Example: Imperative vs. Functional

Collapse
 
lambdafalcon profile image
falcon

Loops are universal, and because they are, you need to read the code to understand whether the loop is searching for an element in a collection, mapping a collection to another, or reducing a collection to something.

Instead, with map/filter/reduce, the reader immediately understands what the intent of the code is.

A simple example: some "functional" code to sum up the lengths of a list of strings would read as follows:

const sum = (a, b) => a + b;
const getLength = (str) => str.length;

const strings = ['foo', 'bar', 'hello', 'world'];

const totalLength = strings
    .map(getLength)
    .reduce(sum);

Which is, in my opinion, much more understandable at a glance that the (one or two) generic for loops required to do this in imperative style.

And in any case, your argument is not really strong: there are countless functions that people know and use without the need to read the documentation every time, and this is because they remember what the functions do.
So, refusing to use map/filter/reduce in JS in 2019 is really just laziness and stubbornness against the more modern API.
Often, people who don't understand the functional array API are still using var instead of let and const.

Collapse
 
wagslane profile image
Lane Wagner

It's not a lack of understanding that I struggle with, it's the same problem I have with relying heavily on a framework imo. I would rather take the extra one line of code to be very explicit about what is happening, rather than rely on functions that are es6 specific. Const and let are totally different, they are keyword syntax, and provide functionality that didn't exist before.

Thread Thread
 
lambdafalcon profile image
falcon

The functions map, filter and reduce are definitely not es6 specific; and ES6 is anyway almost 5 years old.
They exist in almost every major language; in Java they are in the Streams API, in Python they are omnipresent, often used as list comprehensions, in Scala they are there, in Rust they are present in the standard library.

And by using them, you are extremely explicit about what is happening: if you use map, you are doing that and only that. With a for loop, instead, you might be using the for loop to map elements, or to filter them, or to reduce, and one would have to read the details to understand what exactly you are doing. This can take time, especially in larger applications.
Therefore, I argue that e.g. saying map instead of filter is more specific than writing a generic for loop that looks almost the same in the two cases.
It also results in less lines of code, and respects immutability, which in turn helps reducing the average number of bugs in the application.