DEV Community

Cover image for Fundamentals of Functional JavaScript

Fundamentals of Functional JavaScript

Animesh Pandey on March 06, 2021

Introduction Is Functional Programming any style of code that utilizes functions? If only it was that simple! Functions are indeed at th...
Collapse
 
bmehder profile image
Brad Mehder

I find FP to be intriguing, but I have been making apps with Svelte lately. I find it difficult to use FP patterns with a framework that is based on a MVVM pattern. How can I make use of FP with MVVM?

I am looking forward to the rest of the articles in this series. Thank you for doing this!

Collapse
 
anmshpndy profile image
Animesh Pandey

Agreed. FP patterns, in general, can sometimes be difficult to implement with many frameworks. In that case, we can only try our best to accommodate them. Perhaps, I'll try to cover this by taking examples of some common frameworks. I personally haven't worked with Svelte yet, I'll check it out sometime.

In my own view, a framework that doesn't allow enough freedom to try various design patterns, is too restrictive to work with; since it basically feeds you its own guidelines at that point, and forces you to only think along those lines.

This might be a good idea to cover later. Thanks for the suggestion!

And, thank you for enjoying this! It takes a lot of time to put these together, but it is very rewarding if it helps even one person out.

Collapse
 
myleftshoe profile image
myleftshoe

Have you seen cyclejs? Didn't/hasn't really taken off - possibly because it's too far from the norm. It's a "framework" that suffers the opposite restrictiveness problem to most others - forces you to think functionally

Thread Thread
 
anmshpndy profile image
Animesh Pandey

Ah, no hadn't heard of it yet. It looks really interesting from an overview of its docs. Time to try it out someday? Thanks for sharing!

Thread Thread
 
myleftshoe profile image
myleftshoe

Check out the authors videos about it too - really good

Thread Thread
 
anmshpndy profile image
Animesh Pandey

Are you talking about these ones on Egghead? app.egghead.io/playlists/cycle-js-...

Thread Thread
 
myleftshoe profile image
myleftshoe

Sorry, haven't got the link anymore but there's one where he describes the philosophy behind it

Thread Thread
 
myleftshoe profile image
myleftshoe
Thread Thread
 
anmshpndy profile image
Animesh Pandey

Oh my. It is ultra insightful! Will have to go through it a couple of times to properly appreciate.

Thread Thread
 
johnkazer profile image
John Kazer

Might also like Hyperapp

Thread Thread
 
anmshpndy profile image
Animesh Pandey

Thanks!

Collapse
 
marwaneb profile image
Marwan El Boussarghini • Edited

Very cool article thanks for writing it. I'm also super enthusiastic about FP and it's good that people write content about it 😄

About the section "a. Early Returns" I tend to disagree with you: let's take this code

function getPokemonWeaknesses({ types = [] }) {
  let weaknesses = []

  if (types.includes('WATER')) {
    if (!types.includes('EARTH')) {
      weaknesses = ['ELECTRICITY']
    } else {
      weaknesses = ['PLANT']
    }
  }
  if (types.includes('FIRE')) {
    if (!types.includes('WATER')) {
      weaknesses = ['WATER']
    } else {
      weaknesses = ['PSY']
    }
  }
  return weaknesses
}
Enter fullscreen mode Exit fullscreen mode

I generally feel that I would have far more troubles debugging it and understanding it at first glance than a code like this one:

function getPokemonWeaknesses({ types = [] }) {
  if (types.includes('WATER')) {
    if (!types.includes('EARTH')) return ['ELECTRICITY']
    return ['PLANT']
  }

  if (types.includes('FIRE')) {
    if (types.includes('WATER')) return ['PSY']
    if (types.includes('PLANT')) return ['COMBAT']
    return ['PLANT']
  }

  return []
}
Enter fullscreen mode Exit fullscreen mode

Maybe it's more of a personal preference but I would be super interested to read how people feel about this 👍🏽

PS: sorry for my knowledge on Pokemon types, it has been a long time since I've played any Pokemon game 😅

Collapse
 
anmshpndy profile image
Animesh Pandey • Edited

Haha, thanks. 😊

In the end, I guess the point is to make the code more readable. In your example, for sure, the early returns can look more obvious to read. In many cases, they make people lose the flow and intention of the code.

My own preference would certainly depend upon the specific case under consideration, but this was a piece of general advice I have received from many throughout my journey.

Anyway, the main idea of mentioning early returns in the article was to explain that they exist and can be used as an exit from a function (as a function output), but if they complicate the readability too much, it's better to have a single return.

Even my Pokémon knowledge is rusty now. Looking forward to the Diamond and Pearl remakes, and Pokémon Legends. :D

Hope you'll stick around for more! Take care!

Collapse
 
marwaneb profile image
Marwan El Boussarghini

Thanks for the answer, I agree we always need to be cautious about readability !
I always like to challenge my knowledge and the things I do without even thinking about them, it's cool to read some interesting articles that help me do so 👍🏽

Collapse
 
youpiwaza profile image
max

Waow, what a great article. I'm a teacher and this will greatly help some of my students which want to improve in JS.

Some returns to improve it :

  1. Prefer using let instead of var, new JS stuff :p
  2. You should differenciate logs & returns, and not using the same "output" term, in your examples ;)

Thanks a lot for this great work, have a nice day :)

Collapse
 
anmshpndy profile image
Animesh Pandey • Edited

Thanks! Glad you liked it!

And also thank you for your feedback. There was really no reason for me to prefer var over let, it was just my own habit. The outputs/returns could use some improvement though. I am looking into better ways to inject executable code into an article, so it could be of more help. Right now the best option seems to be CodePen. I will revisit and update all previous articles once I am satisfied.

Well, stay tuned for more! Thanks again!

Collapse
 
_genjudev profile image
Larson

Pure functions have no side effects yes. That does not mean that "implicit output" is a side effect. Pure functions have as first rule: the same input gives the same output. (That's the important part)

Implicit outputs is also not a kind of style. it's just lazy. And a bad programming. You working with globals and that could be a real problem in real world. You should more clarify that, because for beginners it looks some kind of cool. And wow its easy. But its the opposit, the code get fast messy and working with other developers would be hard.

But realy nice you are writing about functional programming. And im looking forward to read more. You should go on: "Curry and Function Composition" in some of your next chapters. They are the real deal and helpful af.

Collapse
 
anmshpndy profile image
Animesh Pandey

Yep, thanks for mentioning that. I think I accidentally glossed over this, because the article was already getting too long.

I thought of covering Pure Functions and Side Effects very properly in the next one, after introducing relevant terms here in this one to aid in understanding the upcoming concepts.

Will be definitely going over Composition and Currying in a later one!

Thanks a lot for liking it!

Collapse
 
johnkazer profile image
John Kazer

Thanks, that was a good intro. JavaScript I've found is really a good way to learn functional programming. it allows you to slowly integrate the style into your day-to-day.

The funny thing is that the more I converted to using functional JavaScript the more I was able to understand a more completely functional language like Clojure. As ClojureScript is a variant that compiles to JavaScript and can use JavaScript libraries I am now wondering what really is the point anymore of writing JavaScript at all?

Collapse
 
anmshpndy profile image
Animesh Pandey

Haha, I once had to contribute to a project written in ClojureScript long ago, for a bounty. Back then, I didn't have much understanding of FP, so I was absolutely blown away! Eventually, I got the hang of it, and I'm looking forward to making something of my own out of it! But it was probably the steepest learning curve of my life, so far.

I was going to bring it up eventually, in one of the articles to come, about how exceedingly amazing FP implementation can be in ClojureScript, for someone coming from a JavaScript or similar background.

JavaScript on its own, in my opinion, has a sweet balance between imperative and declarative styles, hence quite amazing for learning any new concepts.

Thanks for liking the article! There's so much to cover under the umbrella of "fundamentals", it's no wonder many learners are flabbergasted when they are directly skipped over to some advanced FP concept.

Hope you'll like the next one too!

Collapse
 
costa86 profile image
Lourenço Costa

Man, this article is pure gold! It should be in a curated list for anyone who uses JS! I have not finished it, though. Is there any particular reason for the use of "var" over "let" or "const" in your samples provided?

Collapse
 
anmshpndy profile image
Animesh Pandey

Thanks! I appreciate it.

Choosing "var" / "let" / "const" wasn't really relevant to the concepts being explained, so I just went with the simple "var". No particular reason for it.

Collapse
 
pris_stratton profile image
pris stratton

Great article, looking forward to the next chapter!

I love FP - there's a great podcast by a guy called Eric Normand which is on Spotify which got me into it.

Collapse
 
anmshpndy profile image
Animesh Pandey

Thanks a lot! :)

Oh, I'll check the podcast out too. Maybe there'll be a reference from it next article?

Collapse
 
pris_stratton profile image
pris stratton

It’s called “Thoughts on Functional Programming” if you do search for it.

Thread Thread
 
anmshpndy profile image
Animesh Pandey

Yep, found it! Pretty good, thanks!

Of all development and programming-related platforms, I didn't think there'd be something like this on Spotify, haha! 😆

Collapse
 
ashleyo profile image
Ashley Oliver

a. Early Returns

There is a mistake in your test case. f(12) should clearly return 13.

Collapse
 
anmshpndy profile image
Animesh Pandey

Yep, you are right! Thanks a lot!

Collapse
 
davidyaonz profile image
David Yao

Very detailed explanation, even though FP has some of kind of steep learning curve, but it is definitely worth mastering if developers want to dive more. Thanks for the effort.

Collapse
 
anmshpndy profile image
Animesh Pandey

Glad you liked it! Thank you!

Collapse
 
anmshpndy profile image
Animesh Pandey

Thanks! Hope it helped just a little bit, atleast!