Functional loops in JavaScript

Ale Miralles
Jun 14 · 4 min read

The iterative approach in JavaScript

The most commonly used technique, and probably the one that comes to mind when you read “sum all items on a list”, is the iterative approach. That is a loop over the list of numbers and add them to an accumulator, once the list gets exhausted, return the accumulator to the caller.

function sum(numbers) {
let acc = 0;
for (let n of numbers) {
acc += n;
}
return acc;
}

The functional approach in Erlang

To see a real “functional loop” in action, we are going to port our little program to Erlang. A pure functional programming language.

  • Adds the value of the head to the accumulator.
  • Calls the “sum” function using the tail and the new value of the accumulator.
% Entry point.
sum(L) ->
sum(L, 0).
% Recursive call.
sum([H|T], Acc) ->
sum(T, H + Acc);
sum([], Acc) ->
Acc.

The recursive approach in JavaScript

Since in JS we don’t have a built-in mechanism to split an array into a [head|tail] structure, we are going to start from there and create two helper functions that will allow us to do that.

function head(list) {
return len(list) > 0
? list[0]
: null;
}
function tail(list) {
return len(list) > 1
? list.splice(1)
: null;
}
// Entry point.
function sum(list) {
return recSum(list, 0);
}
// Recursive call.
function recSum(list, acc) {
let h = head(list);
if (!h) return acc;
return recSum(tail(list), h + acc);
}

Conclusion

Aside from your personal preferences, there is a key take away in this exercise:

Data Structures from scratch — JS Edition

amiralles

Concise programming articles for those who code

Ale Miralles

Written by

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors.

amiralles

amiralles

Concise programming articles for those who code