Functional Programming with JavaScript

Sharing is Caring

JavaScript is really suitable for function programming because of functions being first class. Functions being first class means that JavaScript treats them as a type of object. In JavaScript you can do everything that you could do to a regular object to a function. They can be passed into other functions, assigned as variables and even passed out.

Functional programming is a programming paradigm that focuses on two core concepts. These two core concepts are:
1. avoiding mutating state and side effects
2. using functions as the central building block of programs

There are a lot of other programming paradigms that exist, for example, Procedural Programming, Object Oriented Programming and Meta Programming.

Functional programming focus what’s known as a declarative pattern which means it focuses on what the result should be not necessarily how to achieve the result.

Side effects are things like saving a record into a database, logging to the console, adding or removing something from the screen.

JavaScript, Haskell, Clojure, and Scala are examples of other potential functional programming languages.

Pure Functions

Pure functions allow us to avoid a lot of complexity because we can only deal with the set of inputs which means we should always have the exact same output.

For example, Math.max is a perfect example of a pure function, it takes in any number of values and always returns the largest number.

console.log(Math.max(0,1,2,3,4))

In the above example, 4 will always be printed to the console regardless of how many times we call it because there’s no side effects.

Avoiding Mutating State (Immutability)

In functional programming, avoiding mutating state is one of the core concepts. This can be really hard to grasp without writing a lot of code to understand why it’s a benefit.

In the ES6 dialect of JavaScript, functional programming becomes pretty easy to do.

Fat Arrows / Arrow Functions

As part of the ES6 release of JavaScript, arrow functions were added to JavaScript. Most modern browsers now support the use of arrow functions.

Arrow functions function fairly similar to regular function expressions although they utilize a new token “=>” known as the arrow. Arrow functions are anonymous and change the way that “this” binds in functions.

Arrow functions have two benefits: the code becomes more concise, variable scoping and the this keyword can become a lot more clear. Arrow functions remind me of the lambda functions of C#.

I love using the map function on an array with the fat arrow function. Something like this:

'use strict'

const users = [{
  id: 1,
  firstName: 'Brian',
  lastName: 'Cline'
}, {
  id: 2,
  firstName: 'Tommy',
  lastName: 'Baker'
}, {
  id: 3,
  firstName: 'Jimmy',
  lastName: 'Holmes'
}]

// get user's ids... [ 1, 2, 3 ]
const userIds = users.map(u => u.id)
console.dir(userIds)

As you can see that would get all of the user’s ids, so we could query the database or do some other operation.

Replacing Statements with Expressions

Statements and expressions are pretty important terms in JavaScript. A unit of code that can be evaluated to a value is an expression. A statement is an instruction to perform a action, for example a loop or creating a variable. When we write JavaScript we are typically creating a sequence of statements.

Function expressions are very useful in functional programming. A function expression is normally used to assign a function to a variable, you might also know these as immediately invoked function expressions or a self invoking function.

Currying

Function delegates encapsulate a method allowing functions to be composed or passed as data.

Higher Order Functions

A higher order function is a function that accepts another function as a parameter, or returns another function.

A well designed higher order function will use the vocabulary of the domain or problem being solved. In JavaScript, functions are regular values so this is really easy to do. Higher order functions are really useful when doing data processing like filtering arrays.

The array method reduce is a perfect example of a higher order function in use because it repeatedly takes a single element from the array and combines it with the current value.

For example, if we needed to sum a range of numbers we would abstract away the loops and counting in small little functions.

// without any higher order functions
let total = 0
let count = 1

while (count <= 10) {
  total += count
  count ++
}

Higher Order functions become really useful when we need to compose operations or combine operations together. They allow us to write better code which should reduce the number of bugs and be easier to read and understand.

Arrays

Arrows natively now include a lot of great functions that make it so much easier to do functional programming.

[].every(fn)
Checks if all elements in an array pass a test.

[].some(fn)
Checks if any of the elements in an array pass a test.

[].find(fn)
Returns the value of the first element in the array that passes a test.

[].filter(fn)
Creates an array filled with only the array elements that pass a test.

[].map(fn)
Creates a new array with the results of a function applied to every element in the array.

In my blog post, Ten JavaScript Array Methods Every Developer Should Know I’ve covered how to use a lot of these methods in a lot more detail.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.