Skip to content
comerc edited this page Dec 3, 2018 · 9 revisions

Named Functions

Javascript

function hello() { console.log("Hello World") }

Elixir

defmodule HelloWorld do 
  def hello do
    IO.puts "Hello World"
  end
end

Anonymous Functions

Javascript

These are now called arrow Functions in Javascript. Example with Array.Map

let numbers = [1 , 2, 3]
let double = numbers.map( number => number * 2 )
console.log(double)

Elixir

numbers = [1, 2, 3]
double = Enum.map( numbers , fn(number) -> number * 2 end )
IO.inspect double

## Another way to write Anonymous Functions
numbers = [1, 2, 3]
double = Enum.map( numbers , &(&1 * 2 ))
IO.inspect double

Pattern Matching

Elixir has pretty powerful pattern matching and can be used in Function Signatures and Case Statements. Javascript has something similarish with ES6, Object Destructuring

Javascript

const { id: userId } = { id: 'xxxx-xxxxx', name: 'John Doe' };

[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

// Following Elixirs patter we can write a Recursive function by Destructuring using [head , ...tail]
[head, ...tail ] = [10, 20, 30, 40, 50];

Elxir

user = %{name: "Tom", age: 23}
%{name: username} = user

[head | tail] = [1, 2, 3]

Javascript Objects and Elixir Maps

Javascript Object

customer = { name: 'John Doe',
  address: '255 Wellington Street West',
  city: 'Toronto',
  hobbies: [ 'cooking', 'fishing', 'photography' ] }

// Destructuring in JS
{name: customer_name} = customer
// Shorthand Syntax
{name} = customer

//Access
console.log(customer.name)

Elixir Map

customer = %{ name: "John Doe"
  address: "255 Wellington Street West",
  city: "Toronto",
  hobbies: ["cooking", "fishing", "photography"]
}
# Pattern Match - map
%{ name: customer_name } = customer

#Access
IO.puts customer[:address]
IO.puts customer.address
 

Keyword Lists in Elixir

Iterating a List

Javascript

for( let value of my_list ){
console.log(value*value)
}
//4
//16
//36

Elixir

my_list = [2, 4, 6]
#[2, 4, 6]
for value <- my_list, do: value * value
#[4, 16, 36]