• Social

Functional programming basics before you learn react and redux – the how – part 2

This is a two part series on the functional programming basics you should know before learning React and Redux. If you missed it, click here for part 1.


 

In the previous article you learned about functional programming and its benefits. The second article in the series is about how you write functional programmes. Before we continue, lets walk through the functional programming concepts again.

Functional programming tells us we should avoid a few things…

  • Avoid mutations
  • Avoid side effects
  • Avoid sharing state

These three are about not mutating our data aka aiming for immutability. We can achieve this by,

  • Writing pure functions

Writing pure functions is the first tool you will learn. How else do we write functional programs?

  • Write declarative code

This is about writing concise, readable code. This is a key concept in functional programming too.

  • Be thoughtful about function composition.

This is about writing small functions which we can combine into bigger functions un till we have a full application. There a list of tools which we can use to compose our software, which have a broader term called higher order functions. We will go into detail on these as they are crucial tools in the functional programmers tool bet.

You will notice repetition of the above points are repeated through out the article to help drive them home. Let’s get into it… How do we write functional JavaScript?

Write pure functions

If we were to lend someone a book, we would rather that they didn’t make notes in it, and instead bought a new book and made notes in that instead. Pure functions have this idea at their heart. Pure functions returns the same value given the same input and do not mutate our data. When writing functions, you should try to follow these rules to ensure they are pure.

  1. The function should take at least one argument (the original state)
  2. The function should return a value or another function (the new state).
  3. The function should not change or mutate any of it’s arguments (it should copy them and edit that using the spread operator).

This helps ensure our applications state is immutable, and allows for helpful features such as easier debugging and more specifically features such as undo / redo, time travel via the redux devTool chrome extension.

In React, the UI is expressed with pure functions as you can see in the following code snippet. It does not cause side effects and is up to another part of the application to use that element to change the DOM (which will also not cause harmful side effects).

[pastacode lang=”javascript” manual=”const%20Header%20%3D%20props%20%3D%3E%20%3Ch1%3E%7Bprops.title%7D%3C%2Fh1%3E” message=”” highlight=”” provider=”manual”/]

Spread operator (…)

The spread operator is an essential tool in writing pure functions and helps us ensure our application is immutable. See the below pure function. As you can see it’s copying the original array into a new one.

[pastacode lang=”javascript” manual=”let%20colorList%20%3D%20%5B%0A%20%20%20%20%7Bcolor%3A%20’Red’%7D%2C%0A%20%20%20%20%7Bcolor%3A%20’Green’%7D%2C%0A%20%20%20%20%7Bcolor%3A%20’Blue’%7D%0A%5D%0A%0A%2F%2F%20The%20wrong%20way%20-%20aka%20colorList%20is%20mutated%20because%20we%20have%20pushed%20%0A%2F%2F%20something%20into%20the%20existing%20array.%20It’s%20also%20not%20declarative.%0A%0Avar%20addColor%20%3D%20function(color%2C%20colorList)%20%7B%0A%20%20%20%20colorList.push(%7Bcolor%20%3A%20color%20%7D)%0A%20%20%20%20return%20colorList%3B%0A%7D%0A%0A%2F%2F%20The%20right%20way%20-%20aka%20colorList%20is%20immutable%20%2F%2F%20and%20is%20declarative%20code.%0A%0Aconst%20addColor%20%3D%20(color%2C%20colorList)%20%3D%3E%20%5B…colorList%2C%20%7Bcolor%7D%5D%3B” message=”” highlight=”” provider=”manual”/]

We have pushed our data into a new array which is good!

Let’s look at another example, whereby we need to pull the last element from an array. Notice we are using ES6 destructuring to create our variables.

[pastacode lang=”javascript” manual=”const%20numbersArray%20%3D%20%5B1%2C2%2C3%2C4%2C5%2C6%5D%0A%0Aconst%20%5BlastNumberInArray%5D%20%3D%20%5B…numbersArray%5D.reverse()%0A%2F%2F%206%0A%0A%2F%2F%20We%20have%20created%20a%20new%20numbers%20array%20using%20the%20spread%20operator.%20%0A%2F%2F%20We%20then%20reversed%20it%20so%20we%20can%20pull%20out%20what%20was%20the%20last%20number%20in%20the%20array.%0A%2F%2F%20It%20would%20be%20the%20same%20as%20writing%20the%20below%20less%20declarative%20way.%0A%0Aconst%20lastNumberInArray%20%3D%20%5B…numbersArray%5D.reverse()%5B0%5D%0A” message=”” highlight=”” provider=”manual”/]

The spread operator is crucial in helping us not mutate our state. What’s next?

Write declarative code

Writing code declaratively essentially means writing the least amount of code you can. If you’ve heard of 10x engineers, then they’ll be writing their code like this. The simplest way of understanding this is to take a look at the below example where we use the native JavaScript map function to achieve our goal in one line rather than three.

[pastacode lang=”javascript” manual=”%2F%2F%20imperative%0Aconst%20makes%20%3D%20%5B%5D%3B%0Afor%20(let%20i%20%3D%200%3B%20i%20%3C%20cars.length%3B%20i%20%2B%3D%201)%20%7B%0A%20%20makes.push(cars%5Bi%5D.make)%3B%0A%7D%0A%0A%2F%2F%20declarative%0Aconst%20makes%20%3D%20cars.map(car%20%3D%3E%20car.make)%3B” message=”” highlight=”” provider=”manual”/]

An example of the declarative nature of React is it’s render method. The below code renders a welcome message into the browser. It is a clean, simple way of writing something that would be very convoluted in without the help of the render function.

[pastacode lang=”javascript” manual=”const%20%7B%20render%20%7D%20%3D%20ReactDom%0A%0Aconst%20Welcome%20%3D%20()%20%3D%3E%20(%0A%20%20%3Cdiv%20id%3D%22welcome%22%3E%0A%20%20%20%20%3Ch2%3EHello!%3C%2Fh2%3E%0A%20%20%3C%2Fdiv%3E%0A)%0A%0Arender(%0A%20%20%3CWelcome%20%2F%3E%2C%0A%20%20document.getElementById(‘target’)%0A)” message=”” highlight=”” provider=”manual”/]

Declarative code is about writing code as concisely as possible and describing what should happen rather than how it should happen.

Thoughtful function composition

When you learn about functional programming you will read about the idea of composition. It involves ‘abstracting’ the logic as much as possible into small functions that focus on a specific task. These can then be composed into bigger functions un till you have a working application. Thoughtful composition will help keep our application more readable, maintainable and reusable. Below are the list of tools to help us compose our functions, starting with an explanation of a broader term for the group of tools, higher order functions.

Higher Order Functions

These are functions that are defined by their behaviour. Higher order functions either have another function passed in as an argument, or, return another function. This helps us achieve those desirable affects we noted in the first part of the series, e.g. easier debugging, more readable software etc. Think of higher order functions as Batmans utility belt which has a number of useful tools to help us write functional software. Those tools include,

  • Map – native to JS
  • Filter – native to JS
  • Reduce – native to JS
  • Recursive functions – we write our own
  • Currying functions – we write our own

Note that map, filter and reduce return a new array and so are part of the tools that help us achieve immutability.

Map

Map applies a function to each element in an array and returns the array of updated values. The below example of the map function takes a list of colours, edits an existing colour, and returns a new list. Notice it’s achieves this in one line of code aka it’s declarative.

[pastacode lang=”javascript” manual=”let%20colorList%20%3D%20%5B%0A%20%20%20%20%7Bcolor%3A%20’Red’%7D%2C%0A%20%20%20%20%7Bcolor%3A%20’Green’%7D%2C%0A%20%20%20%20%7Bcolor%3A%20’Blue’%7D%0A%5D%0A%0Aconst%20editColor%20%3D%20(oldColor%2C%20newColor%2C%20colorList)%20%3D%3E%20colorList.map(item%20%3D%3E%20(item.color%20%3D%3D%3D%20oldColor)%20%3F%20(%7B…item%2C%20color%3A%20newColor%7D)%20%3A%20item)%0A%0Aconst%20newColorList%20%3D%20editColor(‘Blue’%2C%20’Dark%20Blue’%2C%20colorList)%3B%0A%0Aconsole.log(newColorList)%3B%0A%0A%2F%2F%20%5B%20%7Bcolor%3A%20’Red’%7D%2C%20%7Bcolor%3A%20’Green’%7D%2C%20%7Bcolor%3A%20’Dark%20Blue’%7D%20%5D” message=”” highlight=”” provider=”manual”/]

Another useful method to be aware of is the commonly required technique of transforming an object into an array, e.g. when we need to pull data from an external source we can use the map function. The example below shows how we can transform an object of book titles and their author into a more useful array.

[pastacode lang=”javascript” manual=”const%20booksObject%20%3D%20%7B%0A%20%20%20%20%22Clean%20Architecture%22%3A%20%22Robert%20C%20Martin%22%2C%0A%20%20%20%20%22JavaScript%20Patterns%22%3A%20%22Stoyan%20Stefanov%22%0A%7D%0A%0Aconst%20booksArray%20%3D%20Object.keys(booksObject).map(key%20%3D%3E%20(%7BbookTitle%3A%20key%2C%20author%3AbooksObject%5Bkey%5D%7D))%3B%0A%0Aconsole.dir(booksArray)%3B%0A%0A%2F%2F%20%5B%0A%2F%2F%20%20%20%20%7BbookTitle%3A%20%22Clean%20Architecture%22%2C%20author%3A%20%22Robert%20C%20Martin%22%7D%2C%20%0A%2F%2F%20%20%20%20%7BbookTitle%3A%20%22JavaScript%20Patterns%22%2C%20author%3A%20%22Stoyan%20Stefanov%22%7D%0A%2F%2F%20%5D” message=”” highlight=”” provider=”manual”/]

Filter

The below example of the filter function takes a list of members, creates a new list and removes the desired member so we have an up to date members list. If the function you pass in returns true, the current item will be added to the returned array and thus you have filtered your array. Also, note the reject function, which works inversely to filter.

[pastacode lang=”javascript” manual=”const%20userList%20%3D%20%5B%0A%20%20%20%20%7Bname%3A%20’Bob’%2C%20member%3A%20true%7D%2C%0A%20%20%20%20%7Bname%3A%20’Fred’%2C%20member%3A%20true%7D%2C%0A%20%20%20%20%7Bname%3A%20’Keith’%2C%20member%3A%20false%7D%0A%5D%0A%0Aconst%20isMember%20%3D%20user%20%3D%3E%20user.member%20%3D%3D%3D%20true%0Aconst%20members%20%3D%20userList.filter(isMember)%3B%0A%0Aconsole.log(members)%3B%0A%0A%2F%2F%20%5B%7Bname%3A%20’Bob’%2C%20member%3A%20true%7D%2C%7Bname%3A%20’Fred’%2C%20member%3A%20true%7D%5D%0A%0A%2F%2F%20Notice%20how%20we%20have%20separated%20out%20isMember%20to%20its%20own%20function.%20This%20is%20declarative%20code%20and%0A%2F%2F%20means%20we%20can%20reuse%20the%20function%20in%20the%20following%20way.%20%0A%2F%2F%20Also%2C%20reject%20is%20just%20the%20opposite%20of%20filter.%0A%0Aconst%20nonMembers%20%3D%20userList.reject(isMember)%0A%0Aconsole.log(nonMembers)%0A%0A%2F%2F%20%5B%7Bname%3A%20’Keith’%2C%20member%3A%20false%7D%5D%0A” message=”” highlight=”” provider=”manual”/]

Reduce

The third method is the reduce function. This is the ‘multitool’ and provides a more general function for when map and filter aren’t appropriate. The important thing to notice about reduce is that is requires a few more parameters than the others. The first parameter is the callback function (which also takes parameters) and the second parameter is the starting point of your iteration. It’s quite confusing at first but with a bit of practice and study you will begin to understand. Take a look at the below example.

[pastacode lang=”javascript” manual=”var%20orders%20%3D%20%5B%0A%20%20%20%20%7Bamount%3A%20230%7D%2C%0A%20%20%20%20%7Bamount%3A%20230%7D%2C%0A%20%20%20%20%7Bamount%3A%20100%7D%2C%0A%20%20%20%20%7Bamount%3A%20400%7D%2C%0A%5D%0A%0A%0Aconst%20sumOfOrders%20%3D%20orders.reduce((sum%2C%20order)%20%3D%3E%20sum%20%2B%20order.amount%2C%200)%0A%0A%2F%2F%20960.” message=”” highlight=”” provider=”manual”/]

The 0 argument we gave as the second parameter of reduce() is passed into the first parameter of callback function, aka sum. The order parameter is the iterable, aka the order value.

It may also help to use the following parameter names to simplify your reduce functions, “result”, “item” and “index”. “result’ is the result you’re building up to in your reduce function, “item” is the current item you’re iterating over, and “index” is the index.

The above is a very simple example and doesn’t demonstrate the real utility of reduce. Another more complex version of reduce shows how we can create a new object out of an array of data. The below function creates a new array of users that are older than 18.

[pastacode lang=”javascript” manual=”const%20users%20%3D%20%5B%0A%20%20%7B%20name%3A%20’Keith’%2C%20age%3A%2018%20%7D%2C%0A%20%20%7B%20name%3A%20’Bob’%2C%20age%3A%2021%20%7D%2C%0A%20%20%7B%20name%3A%20’Fred’%2C%20age%3A%2017%20%7D%2C%0A%20%20%7B%20name%3A%20’George’%2C%20age%3A%2028%20%7D%2C%0A%5D%3B%0A%0Aconst%20usersOlderThan21%20%3D%20users.reduce((result%2C%20item)%3D%3E%7B%0A%20%20%20%20item.age%20%3E%3D%2018%20%3F%20result%5Bitem.name%5D%20%3D%20item.age%20%3A%20null%0A%20%20%20%20return%20result%0A%7D%2C%20%7B%7D)%0A%0A%2F%2F%20%7BKeith%3A%2018%2C%20Bob%3A%2021%2C%20George%3A%2028%7D” message=”” highlight=”” provider=”manual”/]

In most cases, any time you want to transform data into something else, you can use the reduce function.

Currying functions

Currying is a function that holds onto a function which you can reuse at a later point in time. This allows us to break our functions down into there smallest possible responsibility which helps with reusability. Take a look at the below add function. It allows us to add two numbers together which is fine. But then, we realise that most of the time, we are adding 1 to our numbers, so we can use a curried ‘add’ function that can be used to create more specialised add functions such as add1 or add2. This helps with reusability and helps neaten your code.

[pastacode lang=”javascript” manual=”const%20add%20%3D%20(a%2C%20b)%20%3D%3E%20a%20%2B%20b%0A%0Aconst%20a%20%3D%20add(0%2C1)%20%2F%2F%201%0Aconst%20b%20%3D%20add(10%2C%201)%20%2F%2F%2011%0Aconst%20c%20%3D%20add(20%2C%201)%20%2F%2F%2021%0A%0A%2F%2F%20We%20can%20see%20we%20are%20adding%20one%20alot%2C%20so%20much%20%0A%2F%2Fwe%20should%20abstract%20this%20further%20and%20make%20a%20curried%20function.%0A%0Aconst%20curriedAdd%20%3D%20(a)%20%3D%3E%20(b)%20%3D%3E%20a%20%2B%20b%0A%0Aconst%20add1%20%3D%20curriedAdd(1)%3B%0A%0Aconst%20d%20%3D%20add1(0)%20%2F%2F%201%0Aconst%20e%20%3D%20add1(10)%20%2F%2F%2011%0Aconst%20f%20%3D%20add1(20)%20%2F%2F%2021%0A%0A%2F%2F%20maybe%20we%20also%20want%20to%20have%20an%20add2%20function%3F%0A%0Aconst%20add2%20%3D%20curriedAdd(2)%3B%0A%0Aconst%20g%20%3D%20add2(0)%20%2F%2F%202%0Aconst%20h%20%3D%20add2(10)%20%2F%2F%2012%0Aconst%20i%20%3D%20add2(20)%20%2F%2F%2022%0A%0A%2F%2F%20as%20you%20can%20see%20we%20have%20a%20reuseable%20add%20function%20%0A%2F%2F%20that%20we%20can%20apply%20as%20and%20where%20we%20need%20it.” message=”” highlight=”” provider=”manual”/]

Take a look at some of the other examples of where we can use currying. We can create a curried version of map, which allows us to create functions that can be run on an array, for example a doubleAll function.

[pastacode lang=”javascript” manual=”%2F%2F%20we%20can%20create%20a%20curried%20version%20of%20map%20which%20takes%20a%20function%0A%2F%2F%20and%20maps%20across%20over%20it%20and%20returns%20a%20new%20function%20which%0A%2F%2F%20will%20run%20our%20original%20function%20multiple%20times.%0A%0Aconst%20arr%20%3D%20%5B1%2C%202%2C%203%2C%204%5D%3B%0A%0Aconst%20curriedMap%20%3D%20fn%20%3D%3E%20mappable%20%3D%3E%20mappable.map(fn)%3B%0Aconst%20double%20%3D%20n%20%3D%3E%20n%20*%202%3B%0A%0Aconst%20doubleAll%20%3D%20curriedMap(double)%3B%0A%0AdoubleAll(arr)%0A%0A%2F%2F%20%5B2%2C4%2C6%2C8%5D%0A” message=”” highlight=”” provider=”manual”/]

Recursive functions

A recursive function is a function that calls itself, un till it doesn’t! It’s as simple as that. If it sounds like a for loop, then you’d be correct. You may choose a for loop when you only had one or two levels of recursion. The issue is when you have lots of levels of recursion, the for loop suddenly begins to become very unwieldy. The benefit of a recursive function, is that you can simply make a function call itself again and again till your rule is met. A recursive function can do what a for loop can, but in a much conciser way. In most cases you should use recursion over looping whenever possible. The example below shows how a recursive function can be used to count to 10.

[pastacode lang=”javascript” manual=”%2F%2F%20For%20loop%0A%0Afor%20(i%20%3D%200%3B%20i%20%3C%2011%3B%20i%2B%2B)%20%7B%0A%20%20%20%20console.log(i)%3B%0A%7D%0A%2F%2F%200%2C%201%2C%202%2C%203%20…%0A%0A%2F%2F%20Recursive%20function%0A%0Alet%20countToTen%20%3D%20(num)%20%3D%3E%20%7B%0A%20%20%20%20if%20(num%20%3D%3D%3D%2011)%20return%0A%20%20%20%20console.log(num)%0A%20%20%20%20countToTen(num%20%2B%201)%0A%7D%0A%0AcountToTen(0)%0A%2F%2F%200%2C%201%2C%202%2C%203%20…” message=”” highlight=”” provider=”manual”/]

In this case, it may actually be more worth while simply using the for loop, as it is less code. If we consider a more complex loop you will see the real benefits of recursion.

Imagine we have an object which contains lots of data and we will need to access it’s values numerous times in our software. It would help if we had a function that could ‘pick’ the required data from whatever object we passed into it. In the example below, we code a recursive function called pick to help us handle this. See the comments in the code for an explanation.

[pastacode lang=”javascript” manual=”let%20gus%20%3D%20%7B%0A%20%20%20%20animal%3A%20’dog’%2C%0A%20%20%20%20data%3A%20%7B%0A%20%20%20%20%20%20%20%20gender%3A%20’male’%2C%0A%20%20%20%20%20%20%20%20breed%3A%20’Bull%20Dog’%2C%0A%20%20%20%20%20%20%20%20info%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20color%3A%20’white%2C%20brown’%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20behaviour%3A%20’good’%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20mood%3A%20’lazy’%0A%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%7D%0A%0A%2F%2F%20Lets%20see%20our%20recursive%20at%20work%20first.%20We%20pass%20in%20our%20object%20and%20field%20we%20want%20%0A%2F%2F%20(using%20the%20standard%20javascript%20dot%20notation%20for%20%20picking%20values%20from%20objects)%0A%2F%2F%20and%20it%20returns%20the%20value!%0A%0Apick(‘animal’%2C%20gus)%20%2F%2F%20’dog’%0Apick(‘data.info.behaviour’%2C%20gus)%20%2F%2F%20’good’%0A%0A%2F%2F%20Now%20lets%20look%20at%20how%20we%20created%20our%20recursive%20pick%20function!%0A%0Aconst%20pick%20%3D%20(fields%2C%20object)%20%3D%3E%20%7B%0A%20%20%20%20%2F%2F%20We%20split%20our%20fields%20string%20by%20the%20.%20and%20assign%20them%20to%20a%20variable%20%0A%20%20%20%20%2F%2F%20using%20ES6%20destructuing.%20Notice%20we%20use%20the%20spread%20operator%20%0A%20%20%20%20%2F%2F%20because%20this%20doesn’t%20care%20how%20many%20arguments%20it%20recieves.%0A%20%20%20%20%2F%2F%20If%20we%20were%20to%20type%20…remaining%20without%20the%20dots%2C%20it%20would%0A%20%20%20%20%2F%2F%20return%20the%20second%20item%20in%20the%20fields%20array%2C%20which%20is%20no%20good%20for%20this%20function!%0A%0A%20%20%20%20const%20%5BfirstItem%2C%20…remaining%5D%20%3D%20fields.split(%22.%22)%3B%0A%20%20%20%20%0A%20%20%20%20%2F%2F%20we%20now%20have%20a%20variable%20called%20firstItem%2C%20which%20returns%20the%20%0A%20%20%20%20%2F%2F%20first%20word%20of%20the%20string%2C%20and%20a%20variable%20which%20is%20an%20array%0A%20%20%20%20%2F%2F%20that%20has%20the%20remaining%20words%20of%20the%20string%20in%20it.%0A%0A%20%20%20%20%2F%2F%20we%20can%20use%20a%20ternary%20statement%20to%20see%20if%20the%20remaining%20array%20has%20anything%20in%20it%0A%20%20%20%20%2F%2F%20if%20it%20does%20we%20can%20run%20the%20pick%20function%20again%0A%20%20%20%20%2F%2F%20if%20it%20doesn’t%20we%20can%20get%20the%20value%20we%20want.%0A%0A%20%20%20%20return%20remaining.length%20%3F%20%0A%20%20%20%20%20%20%20%20pick(remaining.join(‘.’)%2C%20object%5BfirstItem%5D)%20%3A%0A%20%20%20%20%20%20%20%20object%5BfirstItem%5D%0A%7D” message=”” highlight=”” provider=”manual”/]

Chaining functions

It’s worth remembering that functions can be chained together as well. This is another way that helps you to combine your smaller functions into larger ones. Typically for neatness, we drop the next function onto a new line as you will see in the below example, where we want to get all the even numbers from an array and double them.

[pastacode lang=”javascript” manual=”const%20numbers%20%3D%20%5B1%2C2%2C4%2C5%2C7%2C8%2C9%2C10%5D%3B%0Alet%20isEven%20%3D%20(num)%20%3D%3E%20num%20%25%202%20%3D%3D%200%0Alet%20double%20%3D%20(num)%20%3D%3E%20num%20*%202%0A%0Alet%20doubleAllEvenNumbers%20%3D%20numbers%0A%20%20%20%20.filter(isEven)%0A%20%20%20%20.map(double)” message=”” highlight=”” provider=”manual”/]

Compose

Similar in the way we can combine smaller functions by chaining them together, we can merge them through a function that is commonly named compose(). Compose is a non native function to JavaScript and you can create it yourself as you can see from the below example. This helps with readability and maintenance.

[pastacode lang=”javascript” manual=”%2F%2F%20create%20our%20compose%20funciton%0A%0Aconst%20compose%20%3D%20(…fns)%20%3D%3E%20%7B%0A%20%20(arg)%20%3D%3E%20%7B%0A%20%20%20%20fns.reduce(composed%2C%20f)%20%3D%3E%20f(composed)%2C%20arg)%0A%20%20%7D%0A%7D%0A%0A%2F%2F%20create%20our%20single%20responsibility%20functions%0Avar%20sayLoudly%20%3D%20string%20%3D%3E%20%7B%0A%09return%20string.toUpperCase()%3B%0A%7D%0A%0Avar%20exclaim%20%3D%20string%20%3D%3E%20%7B%0A%09return%20string%20%2B%20′!!’%3B%0A%7D%0A%0A%2F%2F%20compose%20our%20single%20responsibility%20functions%20into%20a%20single%20one%0A%0Avar%20shout%20%3D%20compose(sayLoudly%2C%20exclaim)%3B%0A%0Aexclaim(‘crumbs’)%3B%0A%0A%2F%2F%20crumbs!!%0A%0Ashout(‘crumbs)%3B%0A%0A%2F%2F%20CRUMBS!!” message=”” highlight=”” provider=”manual”/]

Promises

JavaScript can only do one thing at a time as it is a single threaded programming language. If we needed to load some blog posts from an API we ideally wouldn’t want our whole page to have to wait for this information before loading. In the past, we used callback functions to handle but very quickly it landed us in ‘callback hell’, which was where you would have to nest numerous callbacks which ended up in very bloated code.

In recent years, ES6 has introduced Promises to deal with asynchronous behaviour. These are going to be integral to most software applications and so are required knowledge for the modern JavaScript engineer.

[pastacode lang=”javascript” manual=”const%20getBlogPosts%20%3D%20(endpoint)%20%3D%3E%20new%20Promise((resolves%2C%20rejects)%20%3D%3E%20%7B%0A%20%20const%20api%20%3D%20%60https%3A%2F%2Fjsonplaceholder.typicode.com%2F%24%7Bendpoint%7D%60%0A%20%20const%20request%20%3D%20new%20XMLHttpRequest()%0A%20%20request.open(‘GET’%2C%20api)%0A%20%20request.onload%20%3D%20()%20%3D%3E%0A%20%20%20%20%20%20(request.status%20%3D%3D%3D%20200)%20%3F%0A%20%20%20%20%20%20resolves(JSON.parse(request.response))%20%3A%0A%20%20%20%20%20%20reject(Error(request.statusText))%0A%20%20request.onerror%20%3D%20err%20%3D%3E%20rejects(err)%0A%20%20request.send()%0A%7D)%0A%0Aconst%20processBlogPosts%20%3D%20(postsJson)%20%3D%3E%20console.log(postsJson.title%2C%20postsJson.body)%0A%0AgetBlogPosts(‘posts%2F1’).then(%0A%20%20posts%20%3D%3E%20processBlogPosts(posts)%2C%0A%20%20error%20%3D%3E%20console.log(new%20Error(‘Cannot%20get%20posts’))%0A)” message=”” highlight=”” provider=”manual”/]

As you can see, the promise function ‘promises’ it will ‘resolve’ or ‘reject’ your asynchronous function which you can ‘then’ act on depending on a success (the first parameter passed into then) or error (the second parameter passed into then).

You can also chain your promises together, by returning a promise within your promise. This allows you to wait for the first function to finish, then run the second, then third, and so on. This helps prevent race conditions in your code and will provide the help solve any asynchronous requirement in your software.

See the below example whereby the first promise returns another promise, which we chain onto with then(), and return another promise un till we are finished. We have also chained on a catch function, to catch any errors in the process.

[pastacode lang=”javascript” manual=”new%20Promise((resolve%2C%20reject)%20%3D%3E%7B%0A%0A%20%20setTimeout(()%20%3D%3E%20resolve(1)%2C%201000)%3B%0A%0A%7D).then(result%20%3D%3E%7B%0A%0A%20%20console.log(result)%3B%20%2F%2F%201%0A%0A%20%20return%20new%20Promise((resolve%2C%20reject)%20%3D%3E%20%7B%20%0A%20%20%20%20setTimeout(()%20%3D%3E%20resolve(result%20*%202)%2C%201000)%3B%0A%20%20%7D)%3B%0A%0A%7D).then(result%20%3D%3E%20%7B%0A%20%20console.log(result)%3B%20%2F%2F%202%0A%0A%20%20return%20new%20Promise((resolve%2C%20reject)%20%3D%3E%20%7B%0A%20%20%20%20%0A%20%20%20%20setTimeout(()%20%3D%3E%20resolve(result%20*%202)%2C%202000)%3B%0A%20%20%20%20%0A%20%20%7D)%3B%0A%0A%7D).then(result%20%3D%3E%20%7B%0A%0A%20%20console.log(result)%3B%20%2F%2F%204%0A%0A%7D).catch(error%20%3D%3E%20%7B%0A%20%20%20%20console.error(There’s%20been%20an%20error’%2C%20error)%0A%7D)” message=”” highlight=”” provider=”manual”/]

We can make the Promise function even more declarative using the async / await functions. Lets convert our blog posts function to see how promises can become even more readable. Look at the example below where we have created a function called get  getBlogPosts which returns a promise. We than then create an async function which can then await for the promise to be returned. We can use try to handle a successful response and catch to handle a failed response.

[pastacode lang=”javascript” manual=”const%20getBlogPosts%20%3D%20(endpoint)%20%3D%3E%20%7B%0A%20%20return%20new%20Promise((resolves%2C%20reject)%20%3D%3E%20%7B%0A%20%20%20%20const%20api%20%3D%20%60https%3A%2F%2Fjsonplaceholder.typicode.com%2F%24%7Bendpoint%7D%60%0A%20%20%20%20const%20request%20%3D%20new%20XMLHttpRequest()%0A%20%20%20%20request.open(‘GET’%2C%20api)%0A%20%20%20%20request.onload%20%3D%20()%20%3D%3E%0A%20%20%20%20%20%20%20%20(request.status%20%3D%3D%3D%20200)%20%3F%0A%20%20%20%20%20%20%20%20resolves(JSON.parse(request.response))%20%3A%0A%20%20%20%20%20%20%20%20reject(Error(request.statusText))%0A%20%20%20%20request.onerror%20%3D%20err%20%3D%3E%20rejects(err)%0A%20%20%20%20request.send()%0A%20%20%7D)%0A%7D%0A%0Aconst%20processBlogPosts%20%3D%20async%20(apiEndPoint)%20%3D%3E%20%7B%0A%20%20%0A%20%20try%20%7B%0A%20%20%20%20const%20blogPosts%20%3D%20await%20getBlogPosts(apiEndPoint)%3B%0A%20%20%20%20console.log(‘Success’%2C%20blogPosts)%0A%20%20%7D%0A%20%20catch%20%7B%0A%20%20%20%20console.error(‘Could%20not%20get%20blog%20posts’)%0A%20%20%20%7D%0A%0A%7D%0A%0AprocessBlogPosts(‘posts%2F1’)%0A%0A%2F%2FSuccess%20%0A%2F%2F%20%7Btitle%3A%20%22Blog%20Post%20title%22%2C%20content%3A%20%22The%20content%20of%20the%20blog%20post%22%7D” message=”” highlight=”” provider=”manual”/]

This method is more declarative and thus works well in our functional JavaScript applications.

Conclusion

Functional programming is a very useful style of writing code and has been used by React and Redux for good reason. If you know it well, it will make your life as an engineer much easier. Remember that it’s very easy to slip away from functional programming while writing JavaScript so you need to stay focused. The following few simple rules will help you stay on target.

  1. Keep data immutable.
  2. Keep functions pure (functions should take at least one arguments and return data or a function).
  3. Keep your code as concise as possible.
  4. Use recursion over looping (will help solve complex issues in a neater way).

That brings our series to a close. Hopefully you have learned what functional programming is and how it can be used to build better applications. If you are interested how Node (the server) and Mongo (the database) can be used with React and Redux to build out full applications, you can stay up to date by following me on the links below.

Happy engineering!

 


 

Make sure to follow me on twitter or dev.to for more tutorials to help with your journey into software engineering.