I think your specific question can be answered by this video. It explains how
all branching was
removed by refactoring an imperative-style function into functional-style. The original code is on the top, the refactored code is on the bottom:
https://youtu.be/GyYME8btMHE?t=1473Besides being shorter and easier to reason about, functional-style can be easier to test because there are fewer logical paths to test (statement/condition/branch/etc coverage).
Of course, it's still totally possible to write bad code in a functional-style!
Some little advantages of creating arrays in functional-style TS (vs declaring an empty array [] and filling it imperatively with `push()`):
- TS can autumatically infer the type of the array; no need to explicity type.
- Can declare the array as const/readonly if it doesn't change
---
The OP question was at the code-level, the small scale. However FP can be used at both the large and small scales. (And via traditional "non-functional", "inperative" languages.) "Functional programming" is a paradigm and way of thinking; not just a programming language.
In fact, many of the good parts of FP have been borrowed by non-FP languages to the point people don't consider them "functional programming" anymore[0]. (Like JS `.map()` and `.reduce()`. Even Excel macros now support first-class lambda functions[1].)
Another major pillar of FP is immutability (functional purity). Actually Grokking Simplicity[2] states it most elegantly: it's not about avoiding mutation because "mutation is bad." In fact, mutation is usually the desired result, but care must be taken because mutation depends on when and how many times it's called.
So good functional programming isn't about avoiding impure functions; instead it's about giving extra care to them. After all, the purpose of all software is to cause some type of mutation/effect (flip pixels on a screen, save bits to storage, send email, etc). Impure functions like these depend on the time they are called, so they are the most difficult to get right.
In general, I think these are the main promises of functional programming:
1. Program design/code that is easier to reason about/debug.
2. Programs that are shorter, yet more descriptive.
3. Programs that are more performant.
4. Programs that can be easily parallelized.
I wrote a whole article expanding on this: https://blog.leftium.com/2023/04/more-performant-testable-co...
---
Here's a short list of my top introductions/explanations of FP:
- Grokking Simplicity: https://www.manning.com/books/grokking-simplicity
- Functional Core, Imperative Shell: https://hw.leftium.com/#/item/18043058
- ScottWlaschin: https://hw.leftium.com/#/item/21879368
- Greg Young on Event Sourcing: https://youtu.be/8JKjvY4etTY
- https://project-awesome.org/stoeffel/awesome-fp-js
[0]: https://hw.leftium.com/#/item/21280429
[1]: https://hw.leftium.com/#/item/26900419
[2]: https://www.manning.com/books/grokking-simplicity