DEV Community

Discussion on: Practical Ways to Write Better JavaScript

 
adam_cyclones profile image
Adam Crockett 🌀

😆 the more you know, thanks Andy I have learned something today.

Thread Thread
 
pdandy profile image
Andy Thompson

It's an incredibly common misconception; I thought the two were incompatible for years too.

Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀

It does get discussed often as if the two things where oil and water. F# is one of the mid sized language I am still to research, but you have given me a reason.

Thread Thread
 
pdandy profile image
Andy Thompson

I think this is mostly a consequence of two things:

1) Almost universally, you learn only OOP in school / bootcamps / self-learning. You have to actively search out education on FP, which means that when you inevitably do come across it after years of writing OOP it can seem so alien as to be completely incompatible with what you know.

2) When most people think of FP they think of Haskell which:

  • Is statically typed
  • Is immutable
  • Doesn't have objects at all

Haskell being the poster child of FP has lead to a somewhat inaccurate representation of the field. Many people assume all FP is Pure (immutability, no side effects, referential transparency), when the reality is many functional languages describe themselves as pragmatic; allowing for controlled mutability, side effects, etc...

To bring this discussion back round to the original conversation. Modern javascript is getting very functional: we've always had first-class functions, but now with methods like map, reduce, and arrow functions we can write our code in a very functional style.

Typescript, on the other hand undoubtedly favours an OO style. You can still write functional code, but it's a bit more hassle and you'll often find yourself reaching for features found in other typed functional languages that just don't exist in ts / js.

In Elm, for example, there is a Result type that models a computation that can fail. It looks like this:

type Result e a
  = Ok a
  | Err e
Enter fullscreen mode Exit fullscreen mode

it looks like you can achieve this in typescript all the same:

type Result<E, A>
  = Ok<A>
  | Err<E>
Enter fullscreen mode Exit fullscreen mode

But if you know ts you know that this is invalid. In the Elm version Ok and Err are constructors for the type Result. In typescript, Ok and Err are types themselves, and so we need to go ahead and actually define them.

I could continue, but this reply is getting too long and I'm sure you (and others) get my point. Even fully typing a curried function becomes a jumbled mess:

const add = (a: number): ((b: number) => number) => (b: number): number => a + b
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀

My opinion stems for a video of functional c++ of all things. Anyway take this reply and make a post this is interesting!