Functional-JavaScript-Talk



Functional-JavaScript-Talk

1 2


Functional-JavaScript-Talk

JavaScript is a functional language; let's be functional.

On Github CWDG / Functional-JavaScript-Talk

An Introduction to Functional JavaScript

This talk is NOT about

  • The DOM
  • jQuery
  • Inheritance

This talk IS about

  • Types
  • Syntax
  • Functional programming (mostly this)

Let's Jump into it

Types & Truthiness

Objects

They are everywhere

Pick the objects

true
false
undefined
null
"Hello World"
1
new Integer(1)
new Object()
{}
new Array()
[]
function (x) { return x; }

Classfree

Comparisons and Truthiness

undefined == null // → true
undefined === null // → false
0 == false // → true
1 == true // → true
'0' == false // → true
'1' == true // → true
'' == false // → true
'hello world' == false // → false
'hello world' == true // → false

if conditions are like != false

Syntax

if-else

C-style syntax

if (x == y) {
   // do something
} else {
   // do something else
}

switch-case

var returnValue;
switch(val) {
  case 2:
    returnValue = 'A'
    break;
  case 6:
    returnValue = 'B'
    break;
  case 9:
    returnValue = 'B'
    break;
  default:
    returnValue = null;
}
return returnValue;

switch-case

beware of breaks

while

while (condition) {
  // do something that eventually
  // manipulates condition
}

Classic for

for (var i = 0; i < arr.length; i++) {
  // Do something arr.length times
}

for (each)

for (var index in obj) {
  // what do you think index is?
}

;

var

var x;
x // → undefined
var y = 10;

typeof

typeof x // → "undefined"
x // throws a reference error
var x;

Why should I use var?

Scope

Where does it end?

with functions

Do I need scope?

  • It's a tool, not a restriction
  • closures are cool

DETOUR TO CLOSURES →

Functions

Pssh, I already know that

Shut up

First class

Functions can be assigned, passed in, returned and stored in data structures like other objects.

- Ryan McGowan

Quick Example

// Assignment
var coolFunc1 = function () { return "Sooo coool"; };
// Pass in as argument(s)
var coolFunc2 = function (func) {
  // do some stuff and then finally …
  func();
};

What the func?!

var foo = function (bar) {
  return function (baz) {
    return function (derp) {
      return bar.callback(baz, derp, bar.value);
    }:
  };
};
var data = {
  callback: function (x, y, z) { return [x, y, z].join(' '); },
  value: 'func?!'
};
foo(data)("What")("the"); // → "What the func?!"

Closures

What's that?

Example

Implementation Detail Extravaganza

  • Reference To Function
  • Referencing Environment
    • Table of references to free variables

Underscore.js

http://underscorejs.org/

map

Clojure
(map (parital + 1) [1 2 3])
JavaScript
_.map([1, 2, 3], function (num) {
  return num + 1;
});

reduce

Clojure
(reduce * [2 3 4])
JavaScript
_.reduce([2, 3, 4], function (product, num) {
  return product * num;
});

chain

Clojure
(->>
  [1 2 3]
  (map (partial + 1))
  (reduce *))
JavaScript
_.chain([2, 3, 4]).map(function (num) {
  return num + 1;
}).reduce(function (product, num) {
  return product * num;
}).value();

It's your turn

Let's make lambda.js

Replacing partial

Partials are cool

(def plus-six (partial + 6))
(plus-six 10) ; → 16

Partials are cool

(defn all-less-than-ten-lame [coll]
  (every? (fn [item] (< item 10)) coll))
; Cooler
(def all-less-than-ten (partial every? (partial > 10)))

(all-less-than-ten [1 2 3 4 5 8 2 2 7]) ; → true
(all-less-than-ten [1 2 3 4 5 8 11])    ; → false

Rember this?

(defn two-numbers [x]
  (partial + (* 10 x)))

((two-numbers 6) 1) ; → 61
((two-numbers 10) ((two-numbers 1) 6) 4) ; → 120

Challenge Time

Replace if-else

Use an Object, true, false and function(s)

Original

if (a == 'blarg') {
    console.log('Hello');
} else {
    console.log('Goodbye');
}

Answer

console.log({
  true: 'Hello',
  false: 'Goodbye'
}[a == 'blarg']);

Original

var x, y;
if (a == 'blarg') {
   x = 2;
   y = [z * 5];
} else {
   y = 3;
   x = [z / 2];
}

Answer

{
  true: function () {
    x = 2;
    y = [z * 5];
  },
  false: function () {
    y = 3;
    x = [z / 2];
  }
}[a == 'blarg']();

Replace switch-case

What do you need?

Original

var returnValue;
switch(val) {
  case 2:
    returnValue = 'A'
    break;
  case 6:
    returnValue = 'B'
    break;
  case 9:
    returnValue = 'B'
    break;
  default:
    returnValue = null;
}
return returnValue;

Answer

{2: 'A', 6: 'B', 9: 'C'}[val]

Well, almost...

Function definition crap

var y = function () { ... };
// What's the difference?
function y() { ... }

Answer

Hoisting.

foo(); // TypeError "foo is not a function"
bar(); // valid
baz(); // TypeError "baz is not a function"
spam(); // ReferenceError "spam is not defined"

var foo = function () {}; // anonymous function expression ('foo' gets hoisted)
function bar() {}; // function declaration ('bar' and the function body get hoisted)
var baz = function spam() {}; // named function expression (only 'baz' gets hoisted)

foo(); // valid
bar(); // valid
baz(); // valid
spam(); // ReferenceError "spam is not defined"

That's All Folks

Books/References

Me

Twitter: Ryan_VM

Github: RyanMcG