jacobworrel / js-vs-elm

A side by side syntax comparison between JavaScript and Elm

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

js-vs-elm

Side-by-side mappings comparing JavaScript and Elm.

This is intended to elaborate on the official Elm documentation From JavaScript? page so make sure you check that out first if you haven't already.

Table of Contents

JavaScript vs. Elm

Operators

JavaScript Elm
=== ==
!== \=
< <
<= <=
> >
>= >=

Functions

JavaScript Elm
const add = (a, b) => a + b add a b = a + b
add(1, add(1,2) add 1 (add 1 2)

Arrays / Lists

Concatenation

JavaScript
const a = [1,2];
const b = [3,4];

const c = a.concat(b);

// or

const c = [...a , ...b];
Elm
a = [1,2]
b = [3,4]

c = a ++ b

Comments

JavaScript Elm
// single line comment -- single line comment
/* multi line comment */ {- multi line comment -}

Packages / Modules

JavaScript Elm
npm install elm install
package.json elm.json

Destructuring / Pattern Matching

JavaScript Elm
let {name, age} = user; {name, age} = user
({prop}) => prop \{prop} -> prop

If/Else

JavaScript
if (true) {
  return "foo"
} else {
  return "bar";
}
Elm
if True then "foo" else "bar"

-- or

if True then \
 "foo"
else \
 "bar"

Redux vs. Elm

Architecture

Redux Elm
action msg
reducer update
state Model

State Updater Functions

Redux Reducer
function reducer(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;    
  }
}
Elm Update
-- MODEL

type alias Model = Int

model : Model
model = 0

-- UPDATE

type Msg = Increment | Decrement

update : Msg -> Model -> Model
update msg model =
  case msg of
    Increment ->
      model + 1
      
    Decrement ->
      model - 1

React vs. Elm

Components / View Functions

React
const HelloWorld = (props) => (
  <div style={{ color: 'hotpink' }}>Hello world!</div>
);
Elm
helloWorld model =
  div [style "color" "hotpink"] [text "Hello world!"]

Setting State

React
this.setState({ counter: 0 });
Elm
{ model | counter = 0 }

About

A side by side syntax comparison between JavaScript and Elm

License:MIT License