Languages that compile to JS

 

Elm

Elm is the strangest language I have encountered in this list.

Let’s get started. To install, lets download the package from https://guide.elm-lang.org/install.html and install:

Screen Shot 2016-12-21 at 7.52.18 PM.png

Now, let’s familiarize ourselves with the commands we would need:

// This gives us a command-line interface for Elm
elm-repl
// Compile Elm code to HTML/JS
elm-make Main.elm --output=main.html

Now, let’s do a simple exercise on Elm. We would do an app that has two buttons that can increment/decrement a counter. But first, let’s familiarise ourselves with the “structure” of Elm apps. This structure is reminiscent of backbone:

  • Model – This is where the data is stored.
  • Update – Equivalent to the controller in Rails, this is where we place the logic/functions to implement ways on how to manipulate the data
  • View – This is where we place the HTML and we bind the functions made in the Update part to events in the DOM.

Now, let’s dive into the real example:

First, we import the HTML modules of Elm, exposing elements like button, div and text. We also import HTML events such as onClick.

screen-shot-2016-12-21-at-8-07-32-pm

We now define the model. We define the model as an integer initialised with the value of zero.

Screen Shot 2016-12-21 at 8.15.05 PM.png

Now, we define three functions that try to update the model.

screen-shot-2016-12-21-at-8-08-31-pm

Here, we define these three functions, and how they change the model.

Screen Shot 2016-12-21 at 8.20.27 PM.png

Here, we define the view.

screen-shot-2016-12-21-at-8-09-39-pm

TypeScript: The Best Parts

// install Node.js first
// then use node to install typescript
npm install -g typescript

// check if we have typescript
tsc -v
// compile typescript to JS
tsc main.ts

Typescipt is made for reverse compatibility with classic JS and JS 2015. In short, Typescript is made to be a superset of these two. This feature makes it attractive for people with systems filled with native JS code. They can migrate their systems to TS module by module.

The best use of Typescript is it’s use of Optional Static Typing. Below, we see that we declare variables to have a certain type, and when we try to place values that aren’t the type supplied in the declaration, it results in an error.

var burger: string = 'hamburger', // String  
burger = false // results to an error
var calories: number = 300, // Numeric 
var tasty: boolean = true; // Boolean

Typescript takes Static Typing to next levels by placing expected data types on parameters of functions.

function speak(food: string, energy: number): void { 
console.log("Our " + food + " has " + energy + " calories."); 
}

Typescript also allows interfaces, or having to define types that we can use to check against functions, or declare variables with.

interface Food { 
name: string; 
calories: number; 
}

Now, we can use this interface to safeguard the types of our objects we plug into our functions, and the kind the function returns

function speak(food: Food): void{ 
console.log("Our " + food.name + " has " + food.calories + " calories.");
 }

Classes are fun in Typescript.

class Menu { 
// Our properties: 
// By default they are public, but can also be private or protected. 
items: Array; // The items in the menu, an array of strings. 
pages: number; // How many pages will the menu be, a number. 

// A straightforward constructor.  
constructor(item_list: Array, total_pages: number) { 
this.items = item_list; // The this keyword is mandatory.
this.pages = total_pages; 
} 

// Methods list(): void { 
console.log("Our menu for today:"); 
for(var i=0; i<this.items.length; i++) {
 console.log(this.items[i]); 
} 
} 
} 

// Create a new instance of the Menu class. 
var sundayMenu = new Menu(["pancakes","waffles","orange juice"], 1); 

// Call the list method. 
sundayMenu.list();

Dart

Dart is Google’s Compile to JS language and despite of that, Google made Typescript the Compile-to-JS language of Angular 2.0. One of the reasons why is the difficult to port nativeJS libraries to dart and the other way around.

Dart has the following data types, each discussed briefly:

  • Num (has type Int and Double)
  • String (has string interpolations)
    • ‘Dart has $s, which is very handy.’
    • ‘${s.toUpperCase()} is very handy!’
  • Bool
  • List
  • Maps
    • var nobleGases = {
       // Keys: Values
       2 : 'helium',
       10: 'neon',
       18: 'argon',
      };
  • Runes (Unicode Characters)
  • Symbols

Variables are reference to objects. If not initialized with a value, the default value is null. We can also add const or final to make constants in Dart.

bool isNoble(int atomicNumber) {
 return _nobleGases[atomicNumber] != null;
}
void enableFlags(
{bool bold = false, bool hidden = false, [String device]}) {
 // ...
}

We can also cascade commands in a very slick way.

querySelector('#button') // Get an object.
 ..text = 'Confirm' // Use its members.
 ..classes.add('important')
 ..onClick.listen((e) => window.alert('Confirmed!'));

CoffeeScript

  • It removes global variables by wrapping all scripts with an anonymous function and putting in var before variables. But you can create global variables if you explicitly do so.
  • Functions
    • sum = (nums...) ->
       result = 0
       nums.forEach (n) -> result += n 
       result
    • Invocation is through sum(1,2,3)
  • Context
    • this.clickHandler = -> alert “clicked”
      // we used the fat arrow so “this” in clickHandler
      // would be the local scope and not of element
      element.addEventListener “click”, (e) => this.clickHandler(e)
  • Hashes
    • object1 = {one: 1, two: 2}

      # Without braces
      object2 = one: 1, two: 2

  •  Conditional Statements
    • # (1 > 0) ? "Ok" : "Y2K!"
       if 1 > 0 then "Ok" else "Y2K!"
  • String Interpolation
    • question = "Bridgekeeper: What... is your favorite color? Galahad: #{favorite_color} Bridgekeeper: Wrong!"
  •  Looping
    • for name, i in ["Roger the pickpocket", "Roderick the robber"]
      • alert "#{i} - Release #{name}"
  •  Lists
    • firstTwo = ["one", "two", "three"][0..1]
  •   Alias
    • @saviour = true // is this.saviour = true
    • User::first = -> @records[0] // User.prototype.first
    •  cool if jamby? //  if (!jamby == null) {cool}

 

  • Elm
    • Takes a getting used to
    • Has it’s own HTML library so your entire code could be in Elm
  • Typescript
    • Built for gradual migration of native JS/JS2015 to Typescript
    • It’s emphasis for type checking is good
    • Angular 2.0 team is using it
  • Dart
    • difficult to port nativeJS libraries to dart and the other way around.
  • CoffeeScript
    • It’s ruby-like syntax makes JS a joy to code with.
    • It also hides the bad parts of JS to help you make less mistakes

 

Languages that compile to JS

Leave a comment