You can mix and match, it's fine to mix FP with OOP.
JavaScript is Functional: Functions are First Class
Functions in JavaScript are First Class Values
Can be stored in variables, and passed into other functions
function hello(talker) {
talker("Hello world");
}
function talk(text) {
output(text);
}
function shout(text) {
output(text.toUpperCase());
}
hello(talk);
hello(shout);
JavaScript is Functional: Anonymous Functions
Not every functions deserves a name
Anonymous functions can be created on the spot and used right away
function hello(talker) {
talker("Hello world");
}
hello(function (text) {
output('I am an anonymous function and I say: ' + text);
});
JavaScript is Functional: Functions are Closures
A JavaScript function is also a closure
If you define a function inside another function you
can access variables defined in the outer function from
the inner one.
function counter() {
var count = 0;
return function () {
return count++
};
}
var a = counter(), b = counter();
output('a()=', a());
output('a()=', a());
output('b()=', b());
Underscore.JS
A very useful library of utilities
None are very complicated, but it's nice to have a
single version of each.
This is what Functional Programming is really good for, abstracting out little pieces of functionality: Re-use in the small.
Map
var animals = ['llama','alpaca','lemming']
function makeSentence(a) {
return a[0].toUpperCase() + a.slice(1) + ' is a type of animal';
}
Imperative:
var results = [];
for(var i = 0; i < animals.length; i++) {
var animal = animals[i];
results.push(makeSentence(animal));
}
Functional:
var results = _.map(animals, makeSentence);
output('Map results: ',results);
Filter
var animals = ['llama','alpaca','lemming']
function startsWithL(a) {
return a[0] === 'l';
}
Imperative:
var results = [];
for(var i = 0; i < animals.length; i++) {
var animal = animals[i];
if (startsWithL(animal)) {
results.push(animal);
}
}