Member-only story
Functional Programming Snippets in JavaScript and Julia
A comparison of small code snippets to show some of the advantages of Julia for functional programming
A recent Twitter discussion on the use of the reduce
function in JavaScript inspired me to write this story. I primarily write Julia code and I noticed with the examples of how reduce
was used, that the issue seemed to be more about JavaScript than reduce
. This got me thinking about what makes a language suitable for functional programming.
Even though people seem to love functional programming in JavaScript, it is not really a language well designed for it. However, Julia does it quite well. Why is that? A key reason is because functional programming is all about functions and don’t mesh well with object-oriented design. I hope to make this clear with some examples.
For these comparisons I am using the Julia and Node.js REPL environments.
Computing the Sum of a List of Elements
Say you have some collection of elements and you want to add them up. With JavaScript, people commonly use the reduce
function.
> xs = [2, 4, 8]
[ 2, 4, 8 ]> xs.reduce((total, x) => total + x)
14