The mystic term of Functional Programming (FP) must be familiar to any JS developer. The first impression when we say “JS supports functional programming paradigm” or “JS is a Functional programming language”, could be, well I use functions in JS, so I’m already doing Functional programming. This is the myth that we’re going to bust together.

You might be using the FP unknowingly but there’s a lot more to the world of Functional programming which takes years of experience to master. It involves re-wiring your thinking process to observe and implement the FP patterns in your style of writing programs.

Preface

Researching online about FP can leave you inundated with mathematical information that you have no awareness of. This is probably why it’s not that popular among the developer community (due to the steep learning curve involved). Even if you learn some of FP concepts in Javascript, like currying or composing, you may find yourself wondering “How the heck can I use it in my real-world projects?” That’s the same situation I found myself in when I learned about currying (which I wrote an article two years back here wherein I explained it with the help of a contrived example). Guess what, the most common question was, “How and when can I use it in the real world? And is that all Functional Programming is all about?” We’ll address all these questions here.

But before we go any further, we need to understand the basic pillars of FP and why is it worth learning FP in general.

What is Functional Programming?

Functional Programming (FP) is a programming paradigm or a way/style of programming which has the following characteristics:

  • We build programs by composing reusable “Pure functions”.
  • Write declarative code instead of imperative.

It’s more of a way of adapting your brain to think of the FP patterns in your programs.

We’ll learn about all of this using practical examples in a moment.

Why Functional Programming?

Below are the convincing reasons to learn FP:

Imperative vs Declarative code

Consider this code snippet which gets the best products out of an array of products.

Image for post

It does the job, it gives the correct output. But we had to read through the whole code like a story or a series of steps we’re telling the computer to execute in order to make meaning out of it. A computer is excellent at this job of executing programs step by step as a sequence of instructions. And above is a classical example of Procedural programming. So, even though the keyword “function” is used here, it doesn’t make it qualify for Functional Programming because it violates the fundamental principles of FP like pure functions and no side-effects.

Let’s see a declarative version of the above snippet.

#javascript #react #haskell #functional-programming #curry #function

Functional Programming in Javascript 
1.65 GEEK