JavaScript as an Intro to Functional Programming

We have seen that JavaScript can be a great language. Especially for those who are learning Functional Programming.

In the last few months, I saw functional programming everywhere and you probably did too. I'm going to show you some Functional Programming concepts I’ve seen in JavaScript/React/Redux in the last couple of months.

If you have used React and Redux, you have done some functional programming, and you didn't even know it.

Yes, you can do FP in JavaScript

Actually, you can do FP in any language. Of course, it's better to use a pure functional language, because, you will be forced to use functional features.

We can find on the internet a lot of blog posts talking about how to do FP in JavaScript. There is also an Awesome list of Functional Programming for JavaScript.

This will not be another blog post teaching you how to do FP in JavaScript, but a blog post saying what things JavaScript helped me to see in the last several years.

Pure Functions

Pure functions make Functional Programming happen. You probably know what functions are and how to use them, but what are pure functions?

A pure function will always return the same value every time when called with a given argument. It is not changed by any external state. Think in terms of mathematical functions - x^2 doesn’t care about the external state, right?

If you are using React, and you are using stateless components, you are working with pure functions.

Let's see ‘Hello World’ in React:

function HelloWorld() {
  return <div>Hello, world!</div>
}

React has introduced me to pure functions, and it has done this for a lot of other people as well.

Immutability

Immutability is another thing that makes Functional Programming happen. We can use ImmutableJS to make immutable data structures. I am using Immutable especially when I write React code together with Redux. My state is immutable.

ImmutableJS introduced to me the real-world usage of immutability.

Function as components

React introduced to me function as components. Composability. We tend to break our code into small functions or components, and this is one of the things we can do with React. This can also help you avoid repeating yourself.

Summary

Using JavaScript in the last few months helped me understand some Functional Programming concepts better. Maybe this post helps you put names to some concepts you hadn’t been thinking about yet.

Resources