71 points · by sunilsandhu · 4y ago · 118 comments
IMO it's the worst of both worlds and there's virtually never a good reason to use it. If you're going to write a side-effect-y loop, a classic for-loop (or more often, a for..of loop) helps to emphasize that the code is side-effect-y.
forEach emphasizes you are operating on each element of the loop in a semi-independent fashion and you explicitly don't have access to any kind of intermediary index/iterator variable.
When you "drop down" to a classic for loop you're telling the reader that you need access to the index/iterator for some reason (and there are plenty of valid reasons for that).
If you only use classic for loops then the reader has to be constantly vigilant you're not doing any index/iterator shenanigans. It's just higher "cognitive load"
I disagree with this point, specifically for JavaScript the for...of syntax is more pleasant to read and also does not infer that any index access is gonna be done. And as a plus, it is easier to be used with async/await.
Yeah, the “map and friends pass extra parameters that are usually ignored” plus the “lots of JS functions optionally take extra parameters that are usually unused” makes it so easy to think of a function as a one-arg function when its really one plus multiple optionals, use it bare in a map, and get stung by it.
You actually don't need `map`, you can easily implement that using `reduce` too ;)
Also I think `forEach` is great for cases such as `arr.forEach(f)` where `arr: Array<T>, f: T => void`.
ForEach does get you both.
I don't remember using for loop for at least 3 years previously as a frontend engineer :)
It is longer than:
array.forEach((value, index) => {})
… but forEach has too many limitations (no exits, no await, …)
I'll give you await (gotta use awkward reduce there) but if you want exit, you're better off with something like `find`
Another advantage is that array functions better convey what are you trying to do with this particular operation.
I strongly disagree.
> ['1', '2', '3'].map(parseInt)
[1, NaN, NaN]
> ['3', '2', '1'].map(parseInt)
[3, NaN, 1]// Consider: ["1", "2", "3"].map(parseInt); // While one could expect [1, 2, 3] // The actual result is [1, NaN, NaN]
// parseInt is often used with one argument, but takes two. The second being the radix // To the callback function, Array.prototype.map passes 3 arguments: // the element, the index, the array // The third argument is ignored by parseInt, but not the second one, // hence the possible confusion. See the blog post for more details
function returnInt(element){ return parseInt(element,10); }
["1", "2", "3"].map(returnInt); // Actual result is an array of numbers (as expected)
The normal solution is to write an inline function; “shortcutting” it by just passing a named function directly can be nice when it’s appropriate, but it often isn’t what you want to do
Yes, it is.
Its about .map(), and the broader design of the API around it. Yes, map passes extra args and parseInt takes optional args, and it wouldn’t be a problem if both of those weren’t true. It would be better if .map() was one-arg and had friends .map_with_index(), .map_with_collection(), map_with_index_and_collection().
(It would be better if .map() wasn’t an Array-specific method but part of a general collection protocol that returned [and was applicable to] generators instead of returning Arrays, and then you also had companion methods to like .enumerate(), but that’s…well, farther afield.)
> The normal solution is to write an inline function
Yes, that’s the solution, but that doesn’t say that the design of .map() isn’t a critical component of there being something to solve in the first place.
Also, the silently ignored argument count mismatch errors heavily contribute to the problem. You may have used other functions with map() and never knew it's always passing an extra argument in, because JS silently ignores this error.
Then every for-of loop example does not execute anything because it’s creating an inline arrow function without calling it.
>Off-by-one bugs are more probable. For example, you might write i<22 instead, and then the loop would end at 21, not 22.
Ironically, their implementation of a function called "range" differs from the (likely) best known function by that name (that of Python), causing exactly this problem. (Also, the Pythonic range is probably a better fit for a language with 0-based indexing.)
Even for engines that do, you do end up paying a cost for the JIT to warm up to monomorphize these functions.
To just say “there is cost” is not so useful; there is cost to everything.
While loops have their own special powers for recursion so those are still appropriate and not something I would label as “old school” but hell, maybe that makes me old school!
I can’t find a ton of good personal examples where I’ve needed a range function.
This article feels more like the author was “exploring” techniques rather than proposing a standard practice
Not a fan of "map" and its ilk, make code harder to understand and modify over time.
Is the idea behind FP that it's just much less likely for your code to be incorrect? Because to me it looks more like the sort of thing code-golfers love, because it allows for cramming even more implied functionality into ever-tighter, ever-harder-to-read spaces. Which, I suppose, is fine if everyone is on the same level, but I'm not sure how I'd apply something like this in a larger organisation / code base.
Again, I am speaking from ignorance and openly displaying this ignorance intentionally so that I may be proven wrong. I am inviting this, as I'd like to know more about FP.
More interestingly, programming in a functional style encapsulates a lot of complexity in concepts. Once you grasp a concept, it all falls in to place. But getting there is hard.
Java-style OOP gives you a loose bag of conceptually simple pieces, but that quickly devolves in to a horde of rabid infants with jetpacks. Then you need to memorise several dozen patterns to contain the chaos.
Intrinsic vs extrinsic complexity.
I've been loving all of the push towards more functional style programming lately. It makes code so much more intuitive for me.
That's really all there is to it. Functional programming just means some more expressive, higher-level operations at your disposal. Rather than repeating code to initialize, transform, and iterate over state (tasks you spend relatively more time doing homework on in iterative code), you can spend more energy on your problem domain instead.
When you're using a typed language, it's just that: an implementation detail. All that matters is the type you get out, so you can start ignoring all those details and just focus on your program at a higher level, like "first we start with an array of id's, then we map that into an array of employees, then we reduce it into a sum". Much harder to make a mistake compared to "okay, I'm going to maintain a running counter. Then, within a loop, take an id and find the employee, then add the employee's salary to the running sum. After all this I should have a total salary value".
It took a while of actually using some FP patterns for a couple of things to sink in. First, that I'd already been using these patterns in an ad-hoc way, I just didn't have the terminology for it, and second was realising just how repetitive these patterns were in my work. A lot of the code I wrote would either iterate over collections to do stuff to the contents / build a modified collection (map), or iterate a collection and determine something about the contents, like does the user have product x in their cart, or something (reduce).
These days I find code more readable when it uses mapping / reduction and other FP patterns, it's not so much that there's less boilerplate (maybe a couple of lines, nothing drastic), but the grammar itself expresses meaning, I don't have to trace through an entire nested loop section to understand the developer's intentions from the outset.
For instance if I see map, I understand they must be producing a collection based on the input. If they're using reduce, they're figuring out some property of the entire collection.
Also (this is a big plus), the developer would have to go out of their way to modify the original collection, which is always a fun source of unexpected functionality when reading through traditional loops; map and reduce avoid this by design as modified collections are produced as output and don't surreptitiously modify the input. Basically by design you end up with fewer mega-loops that cram in updates, computation, and modify the source data in sneaky ways.
Without reading the contents of the mapping and reduction functions, the grammar of this is very clear to me: "newCollection = (collection.reduce({criteria})) ? collection.map({abc}) : collection.map({def})" - I can see that I'm checking the collection for some criteria, then mapping the collection based on one of two criteria. The grammar itself tells me exactly what's going on before I even have to read the contents of the mapping and reducer functions. Sure that can also be accomplished with a couple of loops, but then I'd have to read through the loops to understand exactly what the broader intention is.
Anyway as I said I consider myself a pragmatist rather than an evangelist for any particular methodology. I don't consider myself a FP programmer but I've found some of the concepts useful tools to have around. Like anyone on a wage, time is money and I use whatever gets the result the client wants in the best way from time, budget, and maintainability perspective. But I hope at least the concept seems a bit less pointless / like code golf with the above context?
elements.map(toSomethingElse)
Reads like Hemingway to me.Generators are very useful in more complex scenarios, but when used in simpler environments they'll just add confusion - in fact the article is a good example of adding confusion with a Generator.
Personally, when dealing with arrays I favour using .map, .reduce, .filter and .forEach.
One of the best tools I found to really dive into functional programming in JavaScript was Lodash's "fp" variant. It will swap the order of the arguments to its functions and curry them all by default. So you're building a function to "add one"
const addOne = map(function(n) { return n + 1 });
Can then be applied against an array of numbers: addOne([1, 2 ,3])
> [2, 3, 4]
This is fairly basic though. Where it really shines is when you start to use the `flow` function will can be used to compose multiple functions together (and makes the order of execution follow from left to right) flow(addOne, reverse)([1, 2, 3])
> [4, 3, 2]
I find this is one of the small redeeming features of JavaScript! addOne :: [Int] -> [Int]
It's not idiomatic in FP (as far as I'm aware) to bake the structure in like that. const addOne = (n) => { return n + 1}
map(addOne)([1, 2, 3])
> [2, 3, 4]
Would decompose the addOne into its own standalone function.My only excuse was that I was in a hurry due to Minecraft time with my son.
pipe(
xs,
reverse,
A.map(addOne),
)Theres also Ramda (https://ramdajs.com/), which I slightly prefer because the documentation is significantly better.
That said, if I was on a project with a bunch of developers that really grok'd FP concepts then Rambda would be my first pick, absolutely.
A note from personal experience: never mix fp and normal variants of date-fns and lodash in one project. If you import isAfter from date-fns/fp in one file and date-fns in another (or your editor imports it for your) you‘re gonna have a BAD time.
If you're a JavaScript developer and you want to learn Functional Programming, then learn Elm. It's a small, easy language, and learning it will make you a better JavaScript programmer.