Javascript: Functional Programming

In this blog, we will look into what is functional programming in javascript.

Deepak jha
3 min readJul 23, 2020

What is functional programming?

So, functional programming is a programming paradigm like object-oriented programming language(OOPS). Each programming paradigm has different rules for structuring our code to solve any problem. Functional programming was invented in the 1950s but it gains popularity over the past few years.

Functional programming is dividing a problem into many small and reusable problem functions that take some input and return a result and they don't mutate or change data.

The main benefits of this small reusable functions are, easies to Debug and Test, they are more concise and scalable because we can run many functions call in parallel and take benefit of multiple cores of our CPU. So these are the main reason functional programming is gained a lot of popularity. But you should also know that javascript is a multi-paradigm programming language and not a purely functional programming language like Closure and Haskell.

As you already know javascript function is first-class citizens which means we can treat a function as a variable, we can assign a function to a variable and pass a function as an argument and also return a function.

Example: function assign to a variable.

output

Example: return a function.

output

Example: function pass as an argument.

output

Higher-order function

A higher-order function takes a function as an argument or returns a function or both. So instead of working on any value like string, boolean, or numbers, a javascript function can go higher and also work on function, that's why these functions called a higher-order function and you might don't know but there is a chance, you already used these higher-order function multiple time, like the map and setTimeout function which take a function as an argument.

Example: map and setTimeout

output

Functional Composition

As we already study that in functional programming we write many small and reusable functions and then compose them to build a more complex function to solve a real-world problem.

We can learn this by an example in which we take a string as an argument and convert that argument into lowercase and then wrap that input inside a div element for doing this we can use a reusable functional component on each step.

output

In this example, the first method, which is an arrow function takes to take an argument to convert that into lowercases and then second function wrapInDiv that takes a string as an argument and wrap that string into Div element. We pass the first function which is convertToLowerCase as an argument to wrapInDiv which wraps the convertToLowerCase result with Div element.

--

--