Could JavaScript support Parallelism like in Haskell?

Multithreaded JavaScript has been published with O'Reilly!
DEPRECATED: This post may no longer be relevant or contain industry best-practices.

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 Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.