Functional Programming in JavaScript? Yes Please.

One of the hot topics right now in the web development world is functional programming in the language of the web, JavaScript.

Functional programming encompasses a whole host of mathematical properties and phenomena that is beyond this post, but what I am going to address here is how to write a a few functions with nominal functional programming.

This is going to be a series. I am currently researching these topics as I go along and what I find excites me. I will be digging into these topics, each array method bit by bit. You can find some more of this on Steve Smith’s blog Funky Javascript.

Important Concept: Higher Order Functions

One of the best and worst parts about JavaScript is that you can pass functions into other functions. This can lead to beautifully expressive code and sometimes bugs.

Why can we do this? Because, like in most functional programming languages 1, functions are values just like any other value in JavaScript.

Take this code:

// Named function or
// function declaration
function double(x) {
  return x * 2;

// Anonymous function or
// Function expression
let double = function(x) {
  return x * 2;

let cat = double;
// Function call

// returns 120, obviously

Here we have named function called double. It takes an argument, x and when you call it, it returns whatever the value of x is that you specify in the function call and returns it.

What’s different about JavaScript is that you can pass it into a variable and call the function from that variable. This is because, well, functions are values.

Higher order functions are good for composition to take smaller functions and make them into bigger functions. More on this in a minute.

Enter .filter()

The .filter() function is an array function that takes a callback that it uses to create a new filtered version of an array.

Take this array of objects:

let animals = [
  { name: ‘Catticus Finch’, species: ‘cat’ },
  { name: ‘Peaches’ species: ‘fish’ },
  { name: ‘Bobby’, species: ‘dog’ },
  { name: ‘Lucifer’, species: ‘cat’ },
  { name: ‘Beatrix’, species: ‘rabbit’ },
  { name: ‘Cerulean’ species: ‘fish’ }

Say I wanted to filter out all this cats in this array. We could use the trusty for loop:

let cats = []

for (let i = 0; i < animals.length; i++) {
  if (animals[i].species === ‘cat’) {

We are essentially just looping through the array and for every cat the for loop finds, it pushes it into the empty cat array.

Now, we can filter.

Filter accepts a callback and loops through each item in the array and passes it back to the callback function. .filter() expects a boolean and then returns the filtered array.

In ES5:

let cats = animals.filter(function(animal) {
  return animal.species === ‘cat’;

In ES6

let cats = animals.filter(animal => animal.species === ‘cat’);

Here, if the value of the species property in the animals array is a cat it will return the names of those cats in a filtered array.

We could also write an anonymous function and add a filter function inside of it, much like this:

let isCat = function(animal){
  return animal.species === ‘cats’;

let cats = animals.filter(isCat);

How Cool is This?

Writing small functions allows composition which we can reuse. In the for loop, we are pushing cats into the array but filter handles this natively.

Filter and the callback are composed as they are meshed into each other. Not only is it syntactically pleasing, but it is less lines of code which is always a good thing.

Next Up

Next I want to tackle the .map() function and get back to my Chrome DevTools series.

  1. Though JavaScript isn’t a purely functional programming language. 

JavaScript, JavaScript, JavaScript


Free Code Camp, love. I really am in love with this site. I guess it’s kind of disingenuous– Free Code Camp outsources its JavaScript course (for beginners) to Codecademy. But I’ve built some pretty interesting games, felt the frustration of debugging (missing curly brackets search for 30 minutes. Seriously), and the rewarding feeling of building something small. I’ve taken lots of notes in Quiver, the notes app that can mix code, markdown, text, and LaTEX in one note (excellent resource). I plan on using Quiver as my main notes app for computer science classes.

Anyway, I stumbled a bit on functions because of the way they looked. Here is the first part of a function:

var orangeCost = function (price) {

You set up a variable called orangeCost and that is also the name of the function. I was stuck on var orangeCost being just a variable and not a function. I finally got it down with practice. What helped was understanding parameters.

I had some difficulty with this function:

var orangeCost = function (price) {
var quantity = 5;
console.log(quantity * price);

The problem? This:

\”You are a creature of habit. Every week you buy 5 oranges. But orange prices keep changing!

You want to declare a function that calculates the cost of buying 5 oranges (So you could name the variable orangeCost and assign the function price since you are looking for the price of the 5 oranges).
You then want to calculate the cost of the 5 all together (quantity).
Write a function that does this called orangeCost().
It should take a parameter that is the cost of an orange, and multiply it by 5.
(the parameter is in between the parentheses in the function. This is where you’d put price. The price changes each time.)

It should log the result of the multiplication to the console.
Call the function where oranges each cost 5 dollars.
What is the one bit of input that changes each time? It would be the price. So give your parameter the name price. And when you call your function, put in a number for the price to see how much 5 oranges cost!\”

I was trying to make the math a function. I wasn’t thinking in algorithms and not breaking the problem down into smaller chunks. I was still not exactly clear on the concepts of functions so this made it difficult. But I knocked it out of the park with subsequent exercises.

Here is my Rock, Paper, Scissors game. I am thinking about improving it, as suggested by Codecademy, but I was so frustrated by the debugging I just wanted to get it over with.

What else? Well, I mentioned debugging with the missing curly brackets. It’s because of the nesting with the If, Else if, and Else, loop/function (am not certain which these are currently though I am leaning towards a loop). There was so much code there and so many loops that I just didn’t remember to put the curly brackets to close the loop.

Here iit is, the Rock, Paper, Scissors game, the debugging job from hell:

var userChoice = prompt(“Do you choose rock, paper or scissors?”);
var computerChoice = Math.random();
if (computerChoice &lt; 0.34) {
computerChoice = “rock”;
} else if(computerChoice &lt;= 0.67) {
computerChoice = “paper”;
} else {
computerChoice = “scissors”;
} console.log(“Computer: ” + computerChoice);

var compare = function(choice1, choice2) {
if (choice1 === choice2) {
return “The result is a tie!”;
else if (choice1 === “rock”) {
if (choice2 === “scissors”) {
return “rock wins”;
} else {
return “paper wins”;
else if (choice1 === “paper”) {
if (choice2 === “rock”) {
return “paper wins”;
} else {
return “scissors wins”;
compare(userChoice, computerChoice);

See what I mean? Ha.

Great week of learning so far. Back at it tonight.



I found that I need to actually write out math problems by hand to figure out how to write them in code. This may seem counterintuitive but is a must for me– in all my math classes I\’ve used my iPad and Noteability to figure out problems and equations. So this makes sense for me.