Mastering JavaScript Functional Programming
eBook - ePub

Mastering JavaScript Functional Programming

Write clean, robust, and maintainable web and server code using functional JavaScript, 2nd Edition

Federico Kereki

Share book
  1. 470 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Mastering JavaScript Functional Programming

Write clean, robust, and maintainable web and server code using functional JavaScript, 2nd Edition

Federico Kereki

Book details
Book preview
Table of contents
Citations

About This Book

Explore the functional programming paradigm and the different techniques for developing better algorithms, writing more concise code, and performing seamless testing

Key Features

  • Explore this second edition updated to cover features like async functions and transducers, as well as functional reactive programming
  • Enhance your functional programming (FP) skills to build web and server apps using JavaScript
  • Use FP to enhance the modularity, reusability, and performance of apps

Book Description

Functional programming is a paradigm for developing software with better performance. It helps you write concise and testable code. To help you take your programming skills to the next level, this comprehensive book will assist you in harnessing the capabilities of functional programming with JavaScript and writing highly maintainable and testable web and server apps using functional JavaScript.

This second edition is updated and improved to cover features such as transducers, lenses, prisms and various other concepts to help you write efficient programs. By focusing on functional programming, you'll not only start to write but also to test pure functions, and reduce side effects. The book also specifically allows you to discover techniques for simplifying code and applying recursion for loopless coding. Gradually, you'll understand how to achieve immutability, implement design patterns, and work with data types for your application, before going on to learn functional reactive programming to handle complex events in your app. Finally, the book will take you through the design patterns that are relevant to functional programming.

By the end of this book, you'll have developed your JavaScript skills and have gained knowledge of the essential functional programming techniques to program effectively.

What you will learn

  • Simplify JavaScript coding using function composition, pipelining, chaining, and transducing
  • Use declarative coding as opposed to imperative coding to write clean JavaScript code
  • Create more reliable code with closures and immutable data
  • Apply practical solutions to complex programming problems using recursion
  • Improve your functional code using data types, type checking, and immutability
  • Understand advanced functional programming concepts such as lenses and prisms for data access

Who this book is for

This book is for JavaScript developers who want to enhance their programming skills and build efficient web applications. Frontend and backend developers who use various JavaScript frameworks and libraries like React, Angular, or Node.js will also find the book helpful. Working knowledge of ES2019 is required to grasp the concepts covered in the book easily.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Mastering JavaScript Functional Programming an online PDF/ePUB?
Yes, you can access Mastering JavaScript Functional Programming by Federico Kereki in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in JavaScript. We have over one million books available in our catalogue for you to explore.

Information

Year
2020
ISBN
9781839217425
Edition
2

Programming Declaratively - A Better Style

Up to now, we haven't really been able to appreciate the possibilities of Functional Programming (FP) as it pertains to working in a higher-level, declarative fashion. In this chapter, we will correct this, and start getting shorter, more concise, and easier to understand code, by using some higher-order functions (HOF); that is, functions that take functions as parameters, such as the following:
  • reduce() and reduceRight() to apply an operation to a whole array, reducing it to a single result
  • map() to transform one array into another by applying a function to each of its elements
  • flat() to make a single array out of an array of arrays
  • flatMap() to mix together mapping and flattening
  • forEach() to simplify writing loops by abstracting the necessary looping code
We'll also be able to perform searches and selections with the following:
  • filter() to pick some elements from an array
  • find() and findIndex() to search for elements that satisfy a condition
  • A pair of predicates, every() and some(), to check an array for a Boolean test
Using these functions lets you work more declaratively, and you'll see that your focus will shift to what you need to do and not so much how it's going to be done; the dirty details are hidden inside our functions. Instead of writing a series of possibly nested for loops, we'll focus on using functions as building blocks to specify our desired result.
We will also be using these functions to work with events in a declarative style, as we'll see in Chapter 11, Implementing Design Patterns – The Functional Way, when we use the observer pattern.
We will also be able to work in a fluent fashion, in which the output of a function becomes the input of the next one, a style we will look at later.

Transformations

The first set of operations that we are going to consider work on an array and process it in the base of a function to produce some results. There are several possible results: a single value with the reduce() operation; a new array with map(); or just about any kind of result with forEach().
If you Google around, you will find some articles that declare that these functions are not efficient because a loop done by hand can be faster. This, while possibly true, is practically irrelevant. Unless your code really suffers from speed problems and you are able to measure that the slowness derives from the use of these higher-order functions, trying to avoid them using longer code, with a higher probability of bugs, simply doesn't make much sense.
Let's start by considering the preceding list of functions in order, starting with the most general of all, which, as we'll see, can even be used to emulate the rest of the transformations in this chapter!

Reducing an array to a value

Answer this question: how many times have you had to loop through an array, performing an operation (say, summing) to produce a single value (maybe the sum of all the array values) as a result? Probably many, many, many times. This kind of operation can usually be implemented functionally by applying reduce() and reduceRight(). Let's start with the former!
Time for some terminology! In usual FP parlance, we speak of folding operations: reduce() is foldl (for fold left) or just plain fold, and reduceRight() is correspondingly known as foldr. In category theory terms, both operations are catamorphisms: the reduction of all the values in a container down to a single result.
The inner workings of the reduce() function are illustrated in Figure 5.1. See how it traverses the array, applying a reducing function to each element and to the accumulated value:
Figure 5.1: The workings of the reduce operation
Why should you always try to use reduce() or reduceRight() instead of hand-coded loops? The following points might answer this question:
  • All the aspects of loop control are automatically taken care of, so you don't even have the possibility of, say, an off-by-one mistake.
  • The initialization and handling of the result values are also done implicitly.
  • Unless you work really hard at being impure and modifying the original array, your code will be side effect free.
Now that we can reduce() an array, let's see some of its practical use cases.

Summing an array

The most common example of the application of reduce(), usually seen in all textbooks and on all web pages, is the summing of all of the elements of an array. So, in order to keep with tradition, let's start with precisely this example!
Basically, to reduce an array, you must provide a dyadic function (that is, a function with two parameters; binary would be another name for that) and an initial value. In our case, the function will sum its two arguments. Initially, the function will be applied to the provided initial value and the first element of the array, so for us, the first result we have to provide is a zero, and the first result will be the first element itself. Then, the function will be applied again, this time to the result of the previous operation, and the second element of the array, and so the second result will be the sum of the first two elements of the array. Progressing in this fashion along the whole array, the final result will be the sum of all its elements:
const myArray = [22, 9, 60, 12, 4, 56];
const sum = (x, y) => x + y;
const mySum = myArray.reduce(sum, 0); // 163
You don't actually need the sum definition—you could have just written myArray.reduce((x,y) => x+y, 0)—however, when written in this fashion, the meaning of the code is clearer: you want to reduce the array to a single value by sum-ming all its elements. Instead of having to write out the loop, initializing a variable to hold the result of the calculations, and going through the array doing the sums, you just declare what operation should be performed. This is what I meant when I said that programming with functions such as those that we'll see in this chapter allows you to work more declaratively, focusing on what rather than how.
You can also even do this without providing the initial value: if you skip it, the first value of the array will be used, and the internal loop will start with the second element of the array; however, be careful if the array is empty, and if you skipped providing an initial value, as you'll get a runtime error! See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce for more details.
We can change the reducing function to see how it progresses through its calculations by just including a little bit of impurity!
const sumAndLog = (x, y) => {
console.log(`${x}+${y}=${x + y}`);
return x + y;
};

myArray.reduce(sumAndLog, 0);
The output would be as follows:
0+22=22
22+9=31
31+60=91
91+12=103
103+4=107
107+56=163
You can see how the first sum was done by adding the initial value (0) and the first element of the array, how that result was used in the second addition, and so on.
Part of the reason for the foldl name seen previously (at least, its ending l) should now be clear: the reducing operation proceeds from left to right, from the first element to the last. You may wonder, however, how it would have been named if it had been defined by a right-to-left language (such as Arabic, Hebrew, Farsi, or Urdu) speaker!
This example is common and well-known; let's now do something a bit more complicated. As we'll find out, reduce() will be quite useful for many different objectives!

Calculating an average

Let's work a bit more. How do you calculate the average of a list of numbers? If you we...

Table of contents