Elm, ScalaJS and GHCJS – a “better JavaScript” shootout

At our dev meeting this week, we talked about three different alternatives to JavaScript – Elm, ScalaJS and GHCJS. All three allow you to write code in a modern, statically-typed functional language, and then produce output in JavaScript that can be run in a browser.

Chris had previously talked about Elm a few weeks ago, in “Elm and Punishment”. Elm is a Haskell-inspired language, designed specifically as a web language that compiles to JavaScript, HTML and CSS. Chris has written a sliding blocks puzzle (source) in Elm as a learning exercise.

Inigo was inspired by Chris’s work in Elm to look at ScalaJS. ScalaJS is a plugin for Scala/SBT that allows standard Scala code to be compiled to JavaScript. It covers the vast majority of the Scala standard library (although it excludes a few areas like reflection and reading files from disk). It doesn’t convert JVM bytecode, only Scala sourcecode, so Java code first needs to be converted to Scala, and it’s not possible to immediately use standard Java libraries. Inigo also wrote a sliding blocks puzzle (sourcecode) and a minesweeper clone (source).

Rodney took a different approach – he implemented Flattris – a flat version of Tetris (source). Rather than using Elm, which is inspired by Haskell, he used GHC JS – which actually is Haskell (the Glasgow Haskell Compiler’s JavaScript compiler).

All three of the languages turned out to be very similar in approach and in results. All of them worked very well. The core languages (Elm, Scala and Haskell) are all more powerful languages than JavaScript. The generated JavaScript is bulkier than hand-written JavaScript would be (from 150kb for ScalaJS, up to about 1MB for GHC JS), but this still isn’t particularly huge compared to the size of modern web pages. All three implementations used a pure functional approach (this is standard in Elm and Haskell, and recommended in Scala), and the sourcecode for the two different sliding blocks implementations ended up remarkably similar. ScalaJS and Elm both emit sourcemaps that allow the generated JavaScript to be debugged e.g. by stepping through the Scala source directly in the browser, or via IDEA. All three were enjoyable to program.

We’re not planning to embrace any of the three as a core language we use at 67 Bricks yet, but we were pleasantly surprised by how well they all worked, and we’re certainly considering them for the future.