Functional Programming in JavaScript

Alex LaFroscia

@alexlafroscia

JavaScript ES5

Lambdas - Callbacks

var button = document.getElementById('my-button');

// Define function outside parameters

var onClick = function(event) {
  console.debug(event);
  alert('button was clicked');
}

button.on('click', onClick);



// Define function in parameters

button.on('click', function(event) {
  console.debug(event);
  alert('button was clicked');
});
  • Pass a function as an argument to another function
  • Really useful for reacting to events in the browser

Array.prototype.map

// Start with an array

var classes = [
  {
    name: '1699',
    professor: 'Bill Laboon'
  }, {
    name: '1501',
    professor: 'Nick Farnan'
  }
];


var professors = classes.map(function(item) {
  // Return the item that we want in the
  // resulting array
  return item.professor;
});


console.log(professors);
  // => ['Bill Laboon', 'Nick Farnan']
  • Iterate over an array
  • Do something with each element
  • Returns an array of the return values

Array.prototype.filter

// Start with an array

var array = [0, 1, 2, 3, 4, 5, 6, 7];

var lessThan4 = array.filter(function(item) {
  // Return true if we want the item in the
  // resulting array
  return item < 4;
});

console.log(lessThan4);
  // => [0, 1, 2, 3]
  • Iterate over an array
  • Do something with each element
  • Return true/false based on whether the item should be in the returned array 

Demo: Filtering Content in Ember.js

About Ember

  • Opinionated framework for building web apps

  • Allows two way binding between data and DOM

What we have

  • An array of Github repos in the controller

  • A view displaying the list of Github repos

  • An input that should filter the list, but doesn't

What we want

  • A filtered array of repos in the controller

  • A view displaying only the matching repos

  • Live updating as we type

Live coding time!

More Info

Functional Programming in JavaScript ES6

By Alex LaFroscia

Functional Programming in JavaScript ES6

New functional concepts in JavaScript ES6

  • 1,569