Back to all blogposts

7 reasons to use functional programming on frontend 2/2

Wiktor Toporek

Wiktor Toporek

Senior Frontend Developer

In the first part of “7 reasons to use functional programming on frontend”, we’ve focused on some basics. I’ve mentioned immutability, pure functions and referential transparency and time-travel debugging. Now, it’s time to study some other features which are more frontend-related.

5. Functional patterns

Every JavaScript developer these days has to deal with its asynchronous nature. When Node came out, one of the anti-patterns became famous – callback hell:

In frontend, the asynchronous nature of JS can also be a problem for junior devs. Tasks like the following may not be easy for junior devs when relying on callbacks:

  1. post some data through AJAX to endpoint X and on success, get new data from endpoint Y,
  2. get data from endpoint X, Y and Z. Wait for all responses, combine them and then finally – display the combined data.

There are some patterns able to control the asynchronous code

But, there are Promises for the rescue. Promise is a well-known pattern that makes it easier to control the asynchronous code and can make it more readable in contrast to the typical callbacks. There are many tutorials in the web about it and also some other patterns which deal with asynchrony in JS that became popular, like “async-await”. But there is one thing that is worth mentioning in FP context. Promises have much in common with Monad which is a functional programming concept. What the Monad is? It is not crucial to understand it for the purpose of this article but there is a great cartoon-illustrated guide which I recommend if you want to learn more.

The thing is that Promise is a really similar pattern to Monad. As Monads can help you with wrapping a value to some context and can add specific behavior to operations that are applicable to them, Promises will help you with wrapping future value (which will come from asynchronous operation) and they add specific behavior which enables you to chain operations to be performed next through the chain of then.

Consequently, we can benefit from functional programming on frontend whilst day to day programming, even though at first glance it offers features which may look like complex structures closer to mathematicians terminology.

📚 The State of Frontend 2022 is out and ready for you!

Built on surveys by 3700 frontend developers from 125 countries, enriched with 19 expert commentaries, divided into 13 topical sections. State of Frontend is the most up-to-date information source.

Check where do you (and your organization) fit within the modern frontend landscape.

6. Declarative-style is readable when describing visual aspects

HTML, CSS and SVG are languages describing the structure of the elements rendered on the browser

When it comes to visual aspects, declarative style is desirable on the frontend side. HTML, CSS and SVG are languages which describe the structure and appearance of the elements rendered on the browser. So, naturally, when it comes to JavaScript frameworks, this approach is also popular.

For example, in Angular, you’ve got templates which look very similar to the plain HTML. There are also some additions like custom components, directives, interpolation through `{{}}` and other features. Template languages can make things better, although they have at least one disadvantage – new syntax to be learned. For instance, take this Angular snippet:

It does not look too complicated if you learn the syntax, although you have to admit that `*ngFor` attribute thing with “let hero of heroes” expression looks a little fancy to a person who just got started with Angular.

Functional programming is a declarative paradigm at the same time. Consider the following functions as an example:

We can read it like this:

  • add is a function which result is a sum of two arguments passed into it;
  • sum is a function which result is passed in array, reduced using the add function and 0 as an initial value.

Of course, we can try to read imperative programs in a similar manner but the point here is that in FP, functions are often written as expressions instead of a block of multiple instructions to be executed from top to the bottom. So our programs are more like definitions what the stuff is, instead of how a program should behave step by step.

Hence, when you learn a functional programming language, it can be reused also for visual aspects of your program in contrast to learning another separate syntax for templating. In React for example, thanks to the ingenious Virtual DOM system, we can easily apply: map, filter and reduce functions, well known in the functional programming. They can be easily applied in component rendering definition:

JSX syntax, which looks like a mix of HTML and JS is just a syntax sugar. You can write equivalent code in standard JavaScript. The thing is that functional programming functions can fit nicely when expressing the stuff to be rendered.

What’s more, we can extend this approach to some other visual APIs that are not purely declarative in standalone HTML. I’m thinking about the Canvas element which requires some imperative JavaScript code to paint a stuff on it but you can use for instance react-canvas which enables you to use the canvas as its contents were DOM elements like <Image>, <Text> (similarly to SVG):

And this is cool because you won’t be bothered with stuff like when to repaint the picture and how to do it, but your app code can focus on definition how app state should be represented visually. It can be implemented just with a simple function which takes the app state as an input and returns what’s to be rendered as an output. Doesn’t it sound great when you also think about the testing?

7. Straightforward optimization

Functional programming can make some programs predictable

You may think that programs written in the purely functional manner may have an impact on the performance. After all, Pure FP programs assume that value like array cannot be reused if you want to add a new element to it. Instead, you’re imposed to create a new version of such array with new value added on the end. Looks like a lot of stuff to be done (copying every element to a new array before appending the new one) by CPU, right?

Well, FP languages behind the scenes can be smarter than that. The fact that FP programs cannot perform some stuff directly limits the programmer. But on the other hand, it guarantees that program won’t do anything fancy on the runtime. In other words, it makes such programs predictable.

Moving back to the array appending example, we can just use an abstraction that looks like an immutable array, but under the hood it may store data in memory more efficiently, so creating a new version of an array (with new element appended) would reuse the previously allocated resources in contrast to copying blindly the values from the previous version for no reason. There is a great article that explains how immutable.js library achieves that. But that is just a proof that it’s possible to write FP programs which aren’t worse than imperative equivalents in terms of performance. Let’s study some examples where we can benefit from pure functions.


For instance, consider the memoization technique. Let’s simplify how it works a bit:

  • when function is called with specific arguments for the first time cache and return the result,
  • when function with specific arguments is called again, return the cached result.

This can be fairly easily implemented in JS. It can be really useful in cases when the time cost of calling a function is high and it’s often called. There is only one requirement – functions that you want to memoize in that way have to be pure because otherwise it is not guaranteed that the remembered result is the correct one that we expect after a call. Hence, score to pure functions.

Virtual DOM + laziness

Another good example where pure functions can shine in terms of optimisation is Virtual DOM. For instance, in Elm programming language, we can optimize re-rendering some DOM elements by decorating the function that produces a lot of DOM elements on each call with  Html.lazy function. Although you probably are not familiar with this programming language yet, I encourage you to read an article which explains how it works. In my opinion, the following quote together with diagrams from that article helps to grasp that idea:

One of the cool things about Elm is the “same input, same output” guarantee for functions. So, whenever we run into two “lazy” nodes while diffing virtual nodes, we ask is the function the same? Are the arguments the same? If they are all the same, we know the resulting virtual nodes are the same as well! So we can skip building the virtual nodes entirely! If any of them have changed, we can build the virtual nodes and do a normal diff.

By “same input, same output” we understand pure functions and we can clearly see that they can do a really good job in making an optimizable ecosystem. Perhaps, you may see some analogy in React’s Pure Components together with their implementation of shouldComponentUpdate method.

Concurrency and parallelism

Although JavaScript engines run the single-threaded event loop, it’s possible these days to use concurrency in your apps, we have WebWorkers API for instance. It’s worth noting that programs that are written in Pure FP manner are easier to be parallelized than imperative snippets. Also, Evan Czaplicki, the creator of Elm (frontend functional programming language) wrote a great thesis which touches Concurrent Functional Reactive Programming topic.


There are some arguments for functional programming not being only a matter of hype

It’s time to answer the question that we’ve asked in the previous part of this article. Functional programming is not only a hype. The concepts that it introduces have already become handy in frontend development practice. Let’s wrap up what we’ve learned about functional programming on frontend in both parts:

  • it proved that object-oriented programming is not the only way of composing maintainable apps,
  • it can help when dealing with a large amount of various type of data which our app state consists off,
  • it can make some contribution to TDD by simplifying or eliminating mocking,
  • time-travel debugging is possible,
  • it fits well for expressing visual content which frontend domain is about,
  • even if an immutable approach to the data may look wasteful for the memory resources and performance at first glance, it opens the doors that enable optimization just at another level of abstraction,
  • perhaps you use some patterns because that’s the way you are told to do in your favourite framework without being aware of the fact that the used framework has been inspired by ideas from the functional programming world?

More reasons could have been listed here in favor of the functional programming on frontend approach. I hope that the examples that I’ve chosen, convinced you to write your frontend code in FP style (if you’re not doing it willingly already). Especially in the era when it is difficult to avoid it.

You may also like

State of Frontend 2022 - Global report

With 3700 devs, 19 experts, 13 topics. This report will rock your front!

Claim free copy

What would you like to do?

    This site is protected by reCAPTCHA and the Google
    Privacy Policy and Terms of Service apply.

    They are more than just a software company. They are the partner who will help you achieve what you want to achieve.

    Nick Gold

    Managing Director at Speakers Corner


    Thank you for your inquiry!

    We'll be back to you shortly to discuss your needs in more detail.