Basic Functional Programming with Javascript

marpme profile image marpme (Marvin) ・4 min read

Functional programming - hmm sounds interesting - but I have actually no clue about this topic? ... Well, then you are welcome to read this article to its full extent.

  1. It will give you some basic knowledge about how functional programming works
  2. Basic components of functional programming
  3. What difference is to the commonly known object-oriented programming.

Let's get actually started!

Basic Functional programming knowledge

For this, we first have to look up how functional programming is defined. The explanation for this is actually quite simple:

"Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects." - Eric Elliott (Master the JavaScript Interview: What is Functional Programming?)

Well... yeah too many buzzwords! Let's quickly decompose this sentence by its important parts, afterward, we should come up with those:

  • pure functions

Pure Function

It basically follows the principle of having the same output for any given input at any time.

This behavior is also called determinism of a function. So a normal function does have its input(s) and calculates its output(s), but those haven't to be same at any time due to changes within the global variable or certain side effects.

A pure function tho will have the same requirement as a normal function, but with the difference that it isn't allowed to access any global/external state, so it's consistent with a given input there follows the same output. (like an one-to-one relationship)

  • avoiding shared state

No shared state between functions. So function A shouldn't know what's done in function B and also the way around. Also not by using a global state.

  • avoiding mutable data

Data should never be modified while working with them. In more common functional programming languages, values are memory copied and returned as a new object. For supporting such immutable data, javascript has the following functions to offer: Map, Reduce, RightReduce, filter ...

  • avoiding side-effects

Side effects are being introduced by, for example, relying on reading in a text file from somewhere. The File's content could be easily changed and can, therefore, cause huge differences (aka. side-effects) without you ever noticing it.

namespace studentExample {
  const costPerStudentPerMonth: number = 200;
  const months: number = 2;
  const students: Array<{ name: string }> = [
      name: 'lulu'
      name: 'lala'
      name: 'lili'
      name: 'lele'

  //normal function
  // + side effects, when changing any variable
  // + relying on a shared state
  const calculateStudentsCost = (students: Array<{ name: string }>) =>
    `${students.length * costPerStudentPerMonth * months} $`;

  // pure function
  // - side-effects, same input = same output!
  // - no shared state
  const pureCalculateStudentsCost = (studentsCount: number) => (
    monthsToCalculate: number
  ) => (costPerStudentPerMonth: number) =>
    `${studentsCount * costPerStudentPerMonth * monthsToCalculate} $`;

  console.log(calculateStudentsCost(students)); // 1600 $
  console.log(pureCalculateStudentsCost(students.length)(months)(costPerStudentPerMonth)); // 1600 $

Enter fullscreen mode Exit fullscreen mode

What you may already notice is one of the biggest downsides by using functional programming is that everything gets a bit more verbose and maybe also harder to wrap your head around. Your brain is really well trained to understand certain concepts by using an object-oriented approach.

So for example, if someone would come up with a task to calculate the diameter and circumference of a circle most people would just go for the object-oriented approach as it seems quite easy to understand. First, you would create a circle class which gets all necessary class variables and also the needed methods to calculate the required numbers.

By experience, fewer people would actually go for a function as it feels less natural doing it this way, but what I've also noticed is, that mathematic functions are a good example of being projectable as a functional approach. Let's try it with the circle example from above:

namespace circleExample {

  // diameter = radius * 2
  const circleDiameter = (radius: number) => radius * 2;

  // Circumference = π × Diameter
  const circumferenceWithDiameter = (diameter: number) => Math.PI * diameter;

  // Circumference = π × radius × 2
  const circumferenceWithRadius = (radius: number) => Math.PI * radius * 2;

  // area = π × radius ** 2
  const areaWithRadius = (radius: number) => Math.PI * radius ** 2;

  // Example calculation

Enter fullscreen mode Exit fullscreen mode

To me, this seems very practical and also quite readable as you can just read the functions together with their inputs. You get a sense of what's happening there without having a look into the code at all. Beside this certain project example, math is always a good example of showing how powerful functional programming can be.

Besides this, did you notice that we never change any variable within our programming examples, that's a nice effect of using functional programming.

In the end, I hope you could gain some knowledge from reading this and I also hope you keep this in mind when touching your personal or work-related projects again. It's only a very basic insight into the functional programming paradigm and there's so much more to explore about this. Feel free to leave me some feedback on this so we can see if we can have a deeper look into it. :)


Editor guide
estebanrocha profile image
Esteban Rocha

Great article!

jvanbruegge profile image
Jan van Brügge

Your "normal" function is in fact pure too: the data it is referencing might be not an argument, but is constant, it wont change making it pure too.

marpme profile image
marpme (Marvin) Author

Thank you Jan, actually that’s true, yes. Maybe you can suggest a better example? I would be really curious if you got a better one in mind.