Pure JS: Experimenting with a pure-functional subset of JavaScript

Sean Micklethwaite
2 min readApr 17, 2018

--

Photo by Sharon McCutcheon on Unsplash

Functional programming has entered the mainstream of JavaScript, with the most popular libraries of today based on functional principles: React, Redux, and RxJS spring immediately to mind.

Although JS is arguably now a functional language, with lots of constructs supporting functional style, it still isn’t pure. When writing reducers in Redux, for example, we have to be very careful not to accidentally mutate our state or cause side effects.

What if we could restrict JS to a pure-functional subset? How might that look? More importantly, how would it feel to program with?

As an experiment to answer this question, I have written and published a simple Babel plugin to test this out: babel-plugin-pure-js. It prohibits a few features of JavaScript:

  • Let and var (only const is allowed)
  • Assignments
  • This

These few restrictions have a knock-on effect that profoundly changes the language. For instance, loop statements of all forms (including Array.forEach) are now essentially useless, as they rely on side effects to produce any output!

I found Array.map now has limited utility too, as any changes to state outside the individual array elements can’t be carried forward through each iteration. Array.reduce is the real workhorse. Here’s some sample code:

A utility function I wrote to make map useful again

It’s hard to keep track of which state is the latest one, and to come up with new names for newer states (we only have const, so can’t reassign). I quickly started wishing for monads! That being said, I got around the issue by breaking up functions into smaller parts. This is what functional programming is all about: composing small, pure functions.

So what’s the outcome? Is this actually a practical way to program? Maybe. It is quite satisfying to write programs in this way, and feels somewhat natural if you’re used to writing Redux reducers. Perhaps with some support from some of JavaScript’s many functional programming libraries, it would be possible to work this way on a real project.

Give it a try!

--

--