“This is the 26th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

JavaScript is not the best language, especially in complex applications, where it may not be up to the task. To avoid this, compilers for new or existing languages have been created to produce code that runs in the browser without writing a line of JavaScript or considering the language’s limitations.

This article describes several languages that can be compiled to JavaScript and executed in a browser or node.js.

Personally, I prefer ClojureScript for code brevity, which allows complex logic to be implemented in short code.

I wanted to try out TypeScript for my latest project because I saw reports of TypeScript everywhere on Google and wanted to try out TypeScript project development.

1. TypeScript

Official website: Get Started with TypeScript

TypeScript is a free and open source programming language developed by Microsoft that is a superset of JavaScript. A valid JavaScript project is also a valid TypeScript project with static typing added. The compiler can also act as an ES2015+ translator to the current implementation, so you always get the latest features.

Unlike other languages, TypeScript keeps the spirit of JavaScript intact, but adds features that increase code reliability. These features are type annotations and other type-related features that make writing JavaScript more fun thanks to the addition of specialized tools like static profilers and other tools to the refactoring process. Also, the addition of types improves the interface between the different components of your application.

Type diagnostics are supportive; you don’t have to write all types from the start. You can write code quickly and then add types to make your code more stable.

TypeScript also supports advanced types such as cross types, union types, type aliases, discernible unions, and type protection. You can check it out on the TypeScript website’s Advanced Types page.

JSX also supports React by adding the React type if you use React.

class Person { private name: string; private age: number; private salary: number; constructor(name: string, age: number, salary: number) { this.name = name; this.age = age; this.salary = salary; } toString(): string { return `${this.name} (${this.age}) (${this.salary})`; }}Copy the code

2. ClojureScript

Official website: Get Started with ClojureScript

ClojureScript is a compiler that converts the Clojure programming language into JavaScript. It is a general-purpose functional language that supports dynamic typing and immutable data structures.

It is the only programming language on this list that belongs to the Lisp family, and of course it has a lot of features. For example, code can be treated as data and supports a macro system, which makes metaprogramming techniques possible. Unlike other Lisps, Clojure supports immutable data structures, making it easier to manage side effects.

Its use of parentheses may seem scary to the novice, but it makes profound sense, and you’ll thank it in the long run. Syntactic parsimony and syntactic abstraction make Lisp a powerful tool for solving problems that require a high level of abstraction.

While Clojure is primarily a functional language, it’s not as pure as PureScript or Elm; Side effects can still occur, but other functional features remain.

ClojureScript uses Google Closure for code optimization and is compatible with existing JavaScript libraries.

(ns dom.test (:require [clojure.browser.event :as event] [clojure.browser.dom :as dom])) (defn log [& args] (.log js/console (apply pr-str args))) (defn log-obj [obj] (.log js/console obj)) (defn log-listener-count [] (log "listener count: " (event/total-listener-count))) (def source (dom/get-element "source")) (def destination (dom/get-element "destination")) (dom/append source (dom/element "Testing me ") (dom/element "out!" )) (def success-count (atom 0)) (log-listener-count) (event/listen source :click (fn [e] (let [i (swap!  success-count inc) e (dom/element :li {:id "testing" :class "test me out please"} "It worked! ")] (log-obj e) (log i) (dom/append destination e)))) (log-obj (dom/element "Text node")) (log-obj (dom/element :li)) (log-obj (dom/element :li {:class "foo"})) (log-obj (dom/element :li {:class "bar"} "text node")) (log-obj (dom/element [:ul [:li :li :li]])) (log-obj (dom/element :ul [:li :li :li])) (log-obj (dom/element :li {} [:ul {} [:li :li :li]])) (log-obj (dom/element [:li {:class "baz"} [:li {:class "quux"}]])) (log-obj source) (log-listener-count)Copy the code

3. Dart

Official website: Get Started with Dart

Dart is a typical object-oriented language where everything is an object and every object is an instance of a class (objects can also be represented as functions). Its special features are used to build applications for browsers, servers and mobile devices. It is maintained by Google and is used to drive the next generation of AdWords UI. The AdWords UI is an important part of Google’s monetization, which is a testament to its size.

The language can be compiled to JavaScript for use in the browser or interpreted directly through the Dart VM, which also allows you to build server-side applications. Mobile apps can be created using the Flutter SDK.

Complex applications also require a sophisticated set of libraries and language features designed specifically for the task, which Dart has. One popular library, for example, is AngularDart, a Dart version of Angular.

It allows you to write non-invasive type-safe code, but this is not necessary because they can automatically detect types. It allows you to prototype quickly without thinking too much about the details, and when you need it, you can add types to make it more robust.

As for concurrent programming in a VM,Dart uses what is known as blast and has its own heap memory, as opposed to shared memory threads (Dart is single-threaded), while communication is done by passing information. In browsers, the situation is a little different: instead of creating a new one, you create a new worker.

// Example extracted from dartlang.org import 'dart:async'; import 'dart:math' show Random; Main () async {print('Compute π using the Monte Carlo method. Igg (features) {print('π $estimate'); }} // Generates a stream of increasingly accurate estimates of π. Stream<double> computePi({int batch: 1000000}) async* { var total = 0; var count = 0; while (true) { var points = generateRandom().take(batch); var inside = points.where((p) => p.isInsideUnitCircle); total += batch; count += inside.length; var ratio = count / total; ⋅r², therefore π = a /r². // when given random points with x ∈ <0,1>, // y ∈ <0,1>, The ratio of those inside a unit circle // Should approach π / 4\. Therefore, the value of π // should be: yield ratio * 4; } } Iterable<Point> generateRandom([int seed]) sync* { final random = new Random(seed); while (true) { yield new Point(random.nextDouble(), random.nextDouble()); } } class Point { final double x, y; const Point(this.x, this.y); bool get isInsideUnitCircle => x * x + y * y <= 1; }Copy the code

4. Elm

Official website: Get Started with Elm

Elm is a purely functional programming language that can be compiled into JS, HTML, and JS. You can create an entire website using Elm alone, which makes it a great alternative to Javascript frameworks like React. Applications created through it automatically use the virtual DOM library, making it fast. A big plus is that the built-in structure lets you forget about data flow and focus on data declarations and logic.

In Elm, all functions are pure, which means they always return the same output for a given input. They can’t do anything else unless you tell them to. For example, to acquire a remote API you would create a command function to communicate with the outside world, and a Subscriptions function to listen for replies. Another pure point is that values are immutable, and when you need something, you create a new value instead of changing it.

ELm acceptance can be gentle; You can use ports to communicate with Javascript or other libraries. Although Elm has not yet reached version 1, it is already used in complex and large applications, making it a viable solution for complex applications.

One of the attractive features of ELm is a beginner-friendly compiler that generates information to help you fix your code, rather than information that is difficult to read. If you’re learning the language, the compiler itself is a big help.

module Main exposing (..) import Html exposing (..) -- MAIN main : Program Never Model Msg main = Html.program { init = init , update = update , view = view , subscriptions = subscriptions } -- INIT type alias Model = String init : ( Model, Cmd Msg ) init = ( "Hello World!" , Cmd.none ) -- UPDATE type Msg = DoNothing update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of DoNothing -> ( model, Cmd.none ) -- VIEW view : Model -> Html Msg view model = div [] [text model] -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.noneCopy the code

5. CoffeeScript

Official website: Get Started with CoffeeScript

CoffeeScript is a language designed to expose the best of JavaScript and provide a clean syntax with semantics preserved where appropriate. Although the language’s popularity has waned in recent years, it is changing direction and now has a new major release that supports ES2015+ features.

The code you write in CoffeeScript is translated directly into readable Javascript code and compatible with existing libraries. Starting with version 2, the compiler produces code that is compatible with the latest version of ECMAScript. For example, every time you use class, you get class in Javascript. And, if you use React, the good news is that JSX is CoffeeScript compliant.

This compiler features the ability to handle code written with literate style. Literate Style you need to write the comments at the beginning, as opposed to highlighting the code and adding the comments. The code only comes up occasionally. This way of writing code, recommended by Donald Knuth, makes a code file very much like a technical document.

In contrast to other languages, CoffeeScript code can be executed directly in a browser using a library. So if you want to write a quick test, you can write your code in a text/ coffeescriptScript tag and introduce a compiler that can easily convert your code to JavaScript.

# Assignment:
number   = 42
opposite = true

# Conditions:
number = -42 if opposite

# Functions:
square = (x) -> x * x

# Arrays:
list = [1, 2, 3, 4, 5]

# Objects:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x

# Splats:
race = (winner, runners...) ->
  print winner, runners

# Existence:
alert "I knew it!" if elvis?

# Array comprehensions:
cubes = (math.cube num for num in list)
Copy the code

6. PureScript

Official website: Get Started with PureScript

PureScript is a purely functional strongly typed programming language created by Phil Freeman. It is designed to provide strong compatibility to available JavaScript libraries, similar to Haskell in spirit, but keeping JavaScript at its core.

One of PureScript’s strengths is its minimalism. It does not include any libraries that are considered necessary functionality in other languages. For example, not that the compiler itself contains generators and Promises, but that you can use specific libraries to accomplish tasks. You can choose the implementation you want for the functionality you need to achieve an efficient and personalized experience with PureScript while keeping the generated code as small as possible.

Another distinguishing feature of its compiler is its ability to generate clean and readable code using libraries and tools while maintaining compatibility with JavaScript.

Like other languages, PureScript has its own build tool called Pulp, which can be compared to Gulp, but is used for projects written in this language.

Regarding the type system, unlike Elm, which is another ML-like language, PureScript supports higher-kinded Types and Type classes from Haskell, This allows complex abstractions to be created.

module Main where import Prelude import Data.Foldable (fold) import TryPureScript main = render $ fold [ h1 (text "Try PureScript!") , p (text "Try out the examples below, or create your own! ") , h2 (text "Examples") , list (map fromExample examples) ] where fromExample { title, gist } = link ("? gist=" <> gist) (text title) examples = [ { title: "Algebraic Data Types" , gist: "37c3c97f47a43f20c548" } , { title: "Loops" , gist: "cfdabdcd085d4ac3dc46" } , { title: "Operators" , gist: "3044550f29a7c5d3d0d0" } ]Copy the code

7. Scala.js

Official website: Get Started with Scala.js

Scala.js is a compiler that converts the Scala programming language into JavaScript. The goal of the Scala language is to merge object-oriented and functional programming into one language and create a powerful set of easy-to-use tools.

As a strongly typed language, you can reap the benefits of local type inference in a flexible type system. Its greatest value is that it can be inferred, but its function parameters still require type specification.

While many common object-oriented patterns are supported (for example, every value is an object and operations are method calls), you can also get functional features such as support for first-class functions and immutable data structures.

One of the special advantages of Scala.js is that you can start with the familiar object-oriented approach and move to a more functional approach at your own pace as needed without doing a lot of work. In addition, existing JavaScript code and libraries are compatible with your Scala code.

Novice Scala developers will find that the language is not that different from JavaScript. Compare the following equivalent code:

// JavaScript var xhr = new XMLHttpRequest(); XHR. Open (" GET ", "https://api.twitter.com/1.1/search/" + "tweets. Json? Q = % 23 scalajs"); xhr.onload = (e) => { if (xhr.status === 200) { var r = JSON.parse(xhr.responseText); $("#tweets").html(parseTweets(r)); }}; xhr.send();Copy the code
// Scala.js val xhr = new XMLHttpRequest() xhr.open("GET", "Https://api.twitter.com/1.1/search/" + "tweets. Json? Q = % 23 scalajs") XHR. Onload = {(e: Event) => if (xhr.status == 200) { val r = JSON.parse(xhr.responseText) $("#tweets").html(parseTweets(r)) } } xhr.send()Copy the code

8. Reason

Official website: Get Started with Reason

Reason is a language created and maintained by Facebook that provides a new syntax for the OCaml compiler and code that can be converted to JavaScript and native code.

As part of the ML family and itself a functional language, it inherently provides a powerful but flexible type system with type inference, algebraic data typing, and pattern matching. It also supports immutable data types and parameter polymorphism (also known as generics in other languages), but in OCaml, object-oriented programming is also supported.

Existing JavaScript libraries are available through bucklescript bindings. You can also mix in your JavaScript next to your Reason code. Inserted JavaScript code is not rigorously checked, but is good for quick fixes and causes.

If you are a React developer, binding is possible, and the language also supports JSX.

/* A type variant being pattern matched */

let possiblyNullValue1 = None;
let possiblyNullValue2 = Some "Hello@";

switch possiblyNullValue2 {
| None => print_endline "Nothing to see here."
| Some message => print_endline message
};

/* Parametrized types */

type universityStudent = {gpa: float};
type response 'studentType = {status: int, student: 'studentType};
let result: response universityStudent = fetchDataFromServer ();

/* A simple typed object */

type payload = Js.t {.
  name: string,
  age: int
};
let obj1: payload = {"name": "John", "age": 30};
Copy the code

conclusion

With so many languages that can be compiled into JavaScript, this is not to say that JavaScript should be abandoned. The mainstream front-end development is using TypeScript, and JavaScript is getting better and better, regardless of the language.