Patterns in Functional JavaScript part 1

It’s frustrating to watch the discussion around modern JavaScript as a functional programmer. With ES6 we’re getting a host of important syntactic improvements — a lot of them make for a more expressive language but it seems like everyone is focused on turning JS into a more typical OOP language even if it means just adding unnecessary syntactic sugar over existing features. In this blog post I explore functional ways of implementing these features and I do it using tools that are available to you right now.

Class syntax

Using objects as containers for functions you can essentially do anything that a class allows you to do without resorting to the clunky prototype syntax. Inheritance and proxying (another new ES6 feature) can be achieved by overwriting an object’s properties.

Dog = (name) ->
bark: -> “Ruff! My name is #{name}!”
wagTail: -> “*swish* *swish*”
Laika = (inSpace) ->
laika = Dog “Laika”
bark: laika.bark
wagTail: ->
if inSpace
“In space no one can hear you wag your tail”
else
laika.wagTail()

Another nice thing about this syntax is you don’t need to do context handling for `this` since all object state is managed in a closure.

Class properties

ES7 proposes syntax for class properties.

class Cat {
name = ‘Garfield’;
static says = ‘meow’;
}
new Cat().name; // Garfield
Cat.says; // meow

I almost feel silly for including this

Cat = -> name: “Garfield”
Cat.says = “meow”
Cat().name
Cat.says

Generators and iterators

let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}

The fibonacci sequence could be implemented in a functional way like so

fibonacci = (pre, cur) ->
value = pre + cur
[value, -> fibonacci cur, value]
[n, f] = [0, -> fibonacci 0, 1]
while n < 1000
[n, f] = f()
console.log n

This shows a few examples how writing functional code in CoffeeScript can be simpler and more expressive than using the new features provided by ES6. While ES6 might go a long way to make writing functional JavaScript tolerable, the fact is that most of the new syntax has been available in CoffeeScript for a while now.