Back to all blogposts

7 reasons to use functional programming on frontend

Wiktor Toporek

Wiktor Toporek

Senior Frontend Developer

Functional programming has recently become a big thing in the frontend development domain. Why so? Is it an example of hype-driven development or are there any reasonable arguments to use it? To answer this question, I’ve prepared a list of seven reasons which may make you decide to use functional programming on frontend during your next software project. 

I’ll cover a few topics:

  • What is functional programming?
  • What are examples of functional programming languages?
  • What is a functional programming style?
  • What were the issues with functional languages in the past?
  • What is a function in programming?
  • What are some functional programming examples?
  • And finally – what are the real reasons to use functional programming on frontend?

1. JavaScript object-oriented programming used to be weird in the past (functional programming language issues)

This is one of the reasons why functional programming on frontend might have gained such popularity rather than an argument to use the functional programming paradigm. Although, it’s worth mentioning this “weirdness” in the name of a better context. A little bit of history…

In the early days, object-oriented programming in JavaScript used to be slightly weird. It was possible to use this kind of programming, however, it wasn’t even close to the OOP known in C++, Java, or other popular OOP languages. There were some issues with functional programming languages. Just take a look at this example:

It’s due to the fact that JavaScript offered a prototype-based inheritance in contrast to a class-based one which is the most popular approach in other object-oriented programming languages. So, why JavaScript took the other way?

In the 90s, we had less powerful computers and obviously, less sophisticated browsers. When JavaScript was invented, prototype-based inheritance has been chosen. It was easier to create an interpreter for it and preserve OOP features at the same time. And probably that’s the reason.

Before the age of transpilers like Babel and alternative frontend programming languages, there was almost no alternative for programming languages than those running in a browser. If we exclude plugins like Java Applets and Flash. Oh… and VBScript which worked on the famous Microsoft Internet Explorer only.

It took 20 years before ECMAScript 6 with final semantics for classes were introduced

What’s more, it took 20 years before ECMAScript 6 with final semantics for classes were introduced. Before that, people got used to the prototypes and some of them also made use of JavaScript functional programming features. These were truly powerful concepts and were available a long, long time before ES6 classes.

Hence, it might be the reason why not all the people adopted ES6 class syntax in their codebase. Of course, classes have become popular in React or Angular-based apps, although considering standalone micro-libraries which NPM repositories are famous for, the class keyword is rare and the functional approach beats it.

2. Immutability can reduce bugs

JavaScript is now something more than just an extra script

Thanks to the solutions like single-page applications, JavaScript is no longer just an extra script that improves the user experience when navigating through the page. Enabling JavaScript support in the browser is something you must do if you want to surf the internet these days.

Sites became applications and the bigger apps are, the more complex issues developers have to deal with.

Frontend developers already have a “bug-friendly” environment thanks to the things like:

  • browser inconsistencies,
  • an innumerable amount of devices with different parameters where the app should display correctly (responsive web design tries to deal with it),
  • API connection problems have to be handled neatly.

And many more. So, naturally, tools and approaches which help narrow the scope of problems down are highly appreciated.

Functional programming itself has a more strict variations called “pure functional programming”. Pure FP is a paradigm that imposes strong restrictions: immutability and side-effects avoidance.

At first glance, these may feel like an unnecessary complication (especially for developers with an imperative programming background). But they bear fruit when it comes to the master application state.

In terms of immutability, let’s study the two following functions:

Perhaps you have already spotted a bug. ???? Nevertheless, let’s test their behavior in JS console:

> median([2, 1, 3, 7, 2, 4, 0, 5])
2.5

> getLast([2, 1, 3, 7, 2, 4, 0, 5])
5

They seem to work properly and would pass the unit tests easily. But note what happens in the following code:

The console.log output for such a case is:

  • 5 for getLast which is correct,
  • 2 for median which is not the value that we expected.

The problem is that values.pop function inside getLast function mutates the array which is passed into by popping the last of elements.

So, let’s redefine getLast function with the immutable (or, so-called, pure) principle in mind:

Then, let’s try again:

Did it work as expected or not? Well, there’s another bug we might have missed.

Let’s try to change just one, tiny thing. Namely – let’s swap the console.log lines:

The console.log output is as follows:

  • median gives us 2.5, as we expected,
  • getLast gives us… 7!?

The problem here is that our median function is not pure. It mutates the array that is passed in as it was in our first implementation of getLast.

What makes this function not pure is that it calls another not-pure function – Array.prototype.sort:

Array.prototype.sort behavior may confuse. It returns a sorted version of an array that has been passed into it, although the sorted version is just a reference to the original array which has been mutated.

Taking the functions from the preceding code examples into consideration, we can see that mutation made them not work properly when we used them one by one and swapped the order of their execution. It has revealed another bug that might have been missed at first glance.

So, let’s finally fix the code example:

What we’ve done in the code above is that we implemented a sort function. And it does not mutate the original array.

Our pure sorting solution makes use of a simple trick of calling Array.prototype.slice(). It creates a copy of the original array before sorting. This behavior guarantees that our sort function won’t mutate the passed in argument, hence it is pure.

And as we use our pure sorting function in the median function, it’s also pure. It guarantees that the median won’t mutate the argument either.

Now, no matter which function is executed in the first place, the results are always predictable and correct:

3. It’s easier to test (and pure function can help)

No matter which programming language I use, there’s a thing that I always associate with tests. It’s mocking/stubbing. When you write unit tests, sooner or later you’ll have to fake some objects and functions that the tested unit relies on.

Pure functions can help you with that. The way they work is simple:

Here is how pure functions work

Just compare them to functions that are not pure:

Here is how non-pure functions work

Due to the fact that in pure functions there is no mutation, side-effects and functions have referential transparency (we’ll focus on this later), it’s guaranteed that the only place where you can change the result of such function are arguments that are input.

Consider how much easier is to write tests for functions that rely only on what you pass to them explicitly. For instance, functions that have to deal with date and time. Normally, it would be tempting to write such a code:

But because such a function relies on the current time (which passes by), you’ll have to mock the date object before testing the function. Although this function is easy to write, it’s more difficult to test, as it requires you to fake the time when writing the tests.

Referential transparency is something that can help us in such cases because it guarantees that the function is deterministic. Referential transparency guarantees the specific input which will always give you the same result – no matter how many times (and when) a function is called. Hence, call expressions of functions that met the referential transparency condition can just be replaced with output values like in the following example:

The number variable can be replaced with the following:

let number = 4;

So, coming back to our tokenExpired function example. We can rewrite it to a pure version that meets the referential transparency requirement:

This function will no longer depend on the current time behind the scenes, and the tests can be simplified as the current time has to be passed explicitly as the second argument:

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 the 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, a 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, a 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 the Elm programming language.

Using Elm can help you solve some problems

Elm is a frontend programming language that 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 states 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 about how he achieved a similar effect for React + Redux.

📚 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.

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 that deal with asynchrony in JS that became popular, like “async-await”. But there is one thing that is worth mentioning in the 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 values (which will come from an 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 that 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 that 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 that look very similar to 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 the “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 whose result is a sum of two arguments passed into it;
  • sum is a function in which the result is passed in an 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 of 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 functional programming. They can be easily applied in component rendering definition:

JSX syntax, which looks like a mix of HTML and JS is just 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 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 the definition of how the app state should be represented visually. It can be implemented just with a simple function that 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 a purely functional manner may have an impact on the performance. After all, Pure FP programs assume that values like the 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 an array with a new value-added on the end. Looks like a lot of stuff is 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 the 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 a 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 proof that it’s possible to write FP programs that 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 a function is called with specific arguments for the first time cache and returns the result,
  • when a 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 memorize 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 optimization 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 that touches on Concurrent Functional Reactive Programming topic.

Conclusion

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

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 the 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 number of various types 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 the 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 it in your favorite 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 the 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.

Interviews
CTO vs Status Quo

Find the exact rules Tech Managers used to organize IT & deliver solutions the Board praised.

Read here

The Software House is promoting EU projects and driving innovation with the support of EU funds

What would you like to do?

    Your personal data will be processed in order to handle your question, and their administrator will be The Software House sp. z o.o. with its registered office in Gliwice. Other information regarding the processing of personal data, including information on your rights, can be found in our Privacy Policy.

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

    We regard the TSH team as co-founders in our business. The entire team from The Software House has invested an incredible amount of time to truly understand our business, our users and their needs.

    Eyass Shakrah

    Co-Founder of Pet Media Group

    Thanks

    Thank you for your inquiry!

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