Posted by & filed under JavaScript.

Any of my regular followers are probably aware of my little adventure into the land of Haskell, a purely functional (FP) language. One of the benefits of a pure FP language is that there are no side effects when running functions. Translated, this means that whenever you run a function, given a set of inputs, the outputs will always be exactly the same. It also has no access to data outside of the function, such as global data or class variables. Contrast this with a class method of a class based language or a JavaScript function relying on data provided from a higher scope.

One of the benefits of pure FP functions is that they can be run concurrently, that is, in parallel on a separate core. Due to the lack of purity in JavaScript, this seemingly cannot be done. As soon as a value your function depends on changes, your function is now coming up with wrong data. Or, code running on two separate cores can attempt to change the value in memory they both use simultaneously, which causes all sorts of chaos.

I’ve been wondering though… Is there perhaps a special syntax we can use in JavaScript to say that a particular function is side-effect free? Say, for example, you wanted to calculate fibonacci numbers. This is quite simple, just pass in an integer, and it relies on no other data than what was passed in. Could it be possible that future versions of JavaScript offer a backwards-compatible method for stating this function is side-effect free and run it on a separate CPU?

Here’s my little idea, borrowed from the “use strict” syntax of EcmaScript 5; Just throw in the string “concurrent” or “side-effect free” or something like that:

function fibonacci(n) {
    "concurrent";
    if (n <= 1) return n;
    return fibonacci(n - 2) + fibonacci(n - 1);
}

In older versions of JavaScript, that string would be ignored, and the function would block your CPU as usual. In future versions of JavaScript, it would know that function is side effect free, and a safe candidate for separate-core processing. This concurrent option would throw an error as soon as the function in question mentions an outside variable.

This is just an idea I had though, and I’m sure there is something important I’m completely overlooking. Let me know in the comments what you think.

Thomas Hunter II

Support Thomas on Patreon. Thomas is the author of Advanced Microservices and a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.

Tags: