7 reasons to use functional programming on frontend 2/2

Read time
7 min

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. Now, it’s time to study some other features which are more frontend-related.

4. Time-travel debugging

Sometimes going back in time is the only way to fix a bug

Have you ever used Redux DevTools? It’s a very helpful tool if you want to debug React + Redux combination based app. Redux is a library capable of managing app state. One of its core principles is the ability to change the state only through pure functions.

The assumption that the app state is modified only through pure functions makes it simple to go back in time and study the application state. For example – right before a bug occurred. In fact, pure functional programming makes the “undo” feature easy to implement. It’s because you have a guarantee that before a new state is presented, the former one is not affected, so it can be easily stored in history.

However, Redux is just a JavaScript library and cannot enforce developers who use it to avail themselves of pure functions. Moreover, typical React app is not only about the state. There are many side effects to be made, AJAX requests to be sent, some components with their own state to be rendered in the DOM and so on. Because of that, Redux and Redux DevTools may get tricked if a developer does not follow the pure functions convention. But there are some alternatives which can fix that problem too. One of these is Elm programming language.

Using Elm can help you solve some problems

Elm is a frontend programming language which compiles to JavaScript. In contrast to JavaScript, it’s a pure functional programming language. One of the fun features which Elm offers is a time-travel debugging which is not limited to a raw app state as it is in Redux DevTools. In Elm’s Time Travelling Debugger, it’s possible to go back in time and observe the real app (instead of its raw state tree) in the way the users see it in their web browser.

What’s more, this tool can also import/export app state so a developer can debug any state saved in a file. This can be helpful not only for debugging sessions but also can give the QA team another tool that can improve the bug reports.

In fact, Redux has been inspired by Elm. Also, Dan Abramov (the creator of Redux) has been inspired by Elm Time-Travel Debugger and you can watch his cool presentation how he achieved a similar effect for React + Redux.

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.

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.

Memoization

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.

Conclusion

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.

 


Looking for top-notch frontend developers?

Tags:

Contact us

We will get back to you in less than 24 hours

Tomasz Mróz

Tomasz Mróz

New Business Manager