Functional Programming in JavaScript — Few data structures, many operations

Few data structures, many operations

This chapter covers:

  • Understanding program control and flow
  • Reasoning efficiently about code and data
  • Unlocking the power of map, reduce and filter
  • Discovering the Lodash.js library and function chains
  • Thinking recursively

In this chapter, I’ll introduce you to a few useful and practical operations like map, reduce and filter that allow you to traverse and transform data structures in a sequential manner. These operations are so important that virtually all functional programs use them in one way or another. They also facilitate removing manual loops from your code, because most loops are just specific cases handled by these functions.

You’ll also learn to use a functional JavaScript library called Lodash.js. It lets you process and understand not only the structure of your application, but also the structure of your data. In addition, I’ll discuss the important role recursion plays in functional programming and the advantages of being able to think recursively. Building on these concepts, you’ll learn to write concise, extensible and declarative programs that clearly separate control flow from the main logic of your code.

Understanding your application’s control flow

The path a program takes to arrive at a solution is known as its control flow. An imperative program describes its flow on path in great detail by exposing all the necessary steps needed to fulfill its task. These steps usually involves lots of loops and branches, as well as variables that change with each statement. At a high level, you can depict a simple imperative program like this:

var loop = optC()
while (loop) {
  var condition = optA()
  if (condition) {
  else {
  loop = optC()

Figure 3.1 shows a simple flowchart of this program.


On the other hand, declarative programs, specifically functional ones, raise the level of abstraction by using a minimally structured flow made up of independent black-box operations that connect in a simple topology. These connected operations are nothing more than higher-order functions that move state from one operation to the next, as shown in figure 3.2. Working functionally with data structures such as arrays lends itself to this style of development and treats data and control flow as simple connections between high-level components.


This produces code more or less like the following:

optA().optB().optC().optD() // Connecting via dots suggests the presence of a shared object that contains these methods.

Chaining operation in this manner leads to concise, fluent, expressive programs that let you separate a program’s control flow from its computational logic. Thus, you can reason about your code and your data more effectively.

Read More »

Functional Programming in JavaScript — Higher Order JavaScript

Higher Order JavaScript

This chapter covers

  • Why JavaScript is a suitable functional language
  • JavaScript as a language that enables multi paradigm development
  • Immutability and policies for change
  • Understanding higher-order and first-class functions
  • Exploring the concepts of closures and scopes
  • Practical sue of closures

As applications get bigger, so does their complexity. No matter how good you think you are, turmoil is unavoidable if you don’t have the proper programming model in place.In chapter 1, I explained the reasons functional progrmaming is a compelling paradigm to adopt. But paradigms by themselves are just programming modes that need the right host language to come to life.

In this chapter, I take you on a fast-pass tour of a hybrid langue that mixes both object-oriented as well as functional programming: JavaScript. Of course, this is by no means an extensive study of the language; rather, I’ll focus on what allows JavaScript to be used functionally as well as where it falls short. One example of this is the lack of support for immutability. In addition, this chapter covers higher-order functions and closures, which totogethaer from the backbone that allows yo to write JavaScript in a function style. Without further ado, let’s dive in.

Why JavaScript?

I began by answering the question, ” Why functional?” Another question that comes to mind is, “Why JavaScript?” The answer to this question is simple: omnipresence. JavaScript is a dynamically typed, object-oriented, general-purpose language with an immensely expressive syntax. It’s one of the most ubiquitous languages ever created and can be seen in the development of mobile applications, se sites, web severs, desktop and embedded applications, and even databases. Given its extraordinary adoption as the language of the web, it begs to reasons the JavaScript is by far the most widely used FP language ever created.

Despite its C-like syntax, JavaScript draws lots of inspiration from functional languages like Lisp and Scheme. The commonalities lie in their support for higher-older functions, closures, array literals, and other features that make JavaScript a superb platform for applying FP techniques. In fact, functions re the main units of work in JavaScript, which means they’re used not only to drive the behavior off our applications, but also to define objects, create modules, and handle events.

JavaScript is actively evolving and improving. Backed by the ECMAScript (ES) standard, its next major release, ES6, adds many more features to the language: arrow functions, constants, iterators, promise, and other features that suit functional programming very well.

Despite the fact that it has lots of powerful functional features, it’s important to know that javaScript is as objet-oriented as it is functional. Unfortunately, the latter is rarely seen; most developers use mutable operations, imperative control structures, and instance state changes on objects, which are all virtually eliminated when adopting a functional style. Nevertheless, I feel it’s important to spend some time talking about JavaScript as an object-oriented language first so that you can better appreciate the key differences between the two paradigms. This will allow you to leap into functional programming more easily.

Read More »

Functional Programming in JavaScript — Becoming functional

What is functional programming?

In simple terms, functional programming is a software development style that places a major emphasis on the use of functions.

What better text to print than the good ol “Hello World”:

document.querySelector('#msg').innerHTML = '<h1>Hello world</h1>'

This program is simple, but because everything is hardcoded, you can’t use it to display messages dynamically. Say you wanted to change the formatting, the content, or perhaps the target element; you’d need to rewrite the entire expression. Maybe you decide to wrap this code with a function and make the change points parameters, so you can write it once and use it with any configuration:

function printMessage(elementId, format, message) {
  document.querySelector('#{elementId').innerHTML = `<${format}>${message}</$Pformat}>`
printMessage('msg', 'h1', 'Hello World')

An improvement, indeed, but still not a complete reusable piece of code. Suppose you want to write to a file instead of an HTML page. You need to take the simple thought process of creating parameterized functions to a different level, where parameters aren’t just scalar values but can also be functions themselves that provide additional functionality. Functional programming is a bit like using functions on steroids, because you sole objective is to evaluate and combine lots of functions with others to achieve greater behavior.

// Listing 1.1 Functional `printMessage`
var printMessage = run(addToDom('msg'), h1, echo)
printMessage('Hello World')

Without a doubt, this looks a radically different than the original. For starters, h1 isn’t a scalar anymore; it’s a function just like addToDom and echo. Visually, it feels as though you’re creating a function from smaller functions.

Read More »