5 ms·
It's very easy to write JS in a functional style, since as you point out, it already supports first-class functions, which is the most important building block.
by qsymmachus 7y ago
It's very easy to write JS in a functional style, since as you point out, it already supports first-class functions, which is the most important building block.
To really go whole hog, try setting one constraint for yourself: only use immutable data. Make all your variables `const`s, and only use immutable data structures (Immutable.js is a useful library for this).
You'll discover that it's basically impossible to write code in the familiar imperative style – everything needs to be a pure function, that just takes an input and returns a consistent output, without mutating state. This really is the "secret sauce" of FP.
- dan-robertson 7y agoThis seems to be missing the point which the GP makes that a significant advantage for FP is not so much the functions (or even the immutability) as it is the domain modelling. In JavaScript a float is a float and the fact that it is immutable won’t save you from accidentally confusing two things that happen to be numbers (say the width of an element and the duration of an animation, or the price of some product and the amount in stock, or a pipe length in feet and thickness in millimetres). The other domain-modelling-in-FP feature missing from JS is discriminated unions (aka sum types or enums in some languages). This domain modelling is a big important feature in rust too (with more invariants which may be expressed using ownership constraints) but no one claims it’s a particularly functional language. Indeed I don’t think one needs FP for this kind of domain modelling that we get via ML-family languages.
- mettamage 7y agoYep, true, DDD with FP looks practical. I love defining new words, and that talk in F# simply made it really clear. It was weird to see a talk like that and realize to myself "but this is just how my brain works!" I happen to be quite a noun-driven person [1]. And I guess I fell into the trap that this made everything seem so easy and understandable! Which is why I got excited :P I just bought his book, lol. That was too easy to understand and yet entertaining at the same time while feeling useful as well. [1] Sometimes even creating new nouns into the Dutch language to make arcane but important concepts clear. My most fun noun is "search term scavenger hunt" (in Dutch it is conjugated) for the situation where you know what you're looking for but don't know the right term to get hits on a search engine and you're hunting for the right word.