Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering JavaScript Functional Programming
Mastering JavaScript Functional Programming

Mastering JavaScript Functional Programming: In-depth guide for writing robust and maintainable JavaScript code in ES8 and beyond

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Mastering JavaScript Functional Programming

Becoming Functional - Several Questions

–Functional Programming (or FP, as it's usually shortened) has been around since the earliest times and is going through a sort of revival, due to its increased use with several frameworks and libraries, and most particularly in JavaScript. In this chapter, we shall:

  • Introduce some concepts of FP, to give a small taste of what it means
  • Show benefits (and problems) implied by the usage of FP
  • Start thinking about why JavaScript (JS) can be considered to be an appropriate language for FP
  • Go over the language features and tools that you should be aware of, to fully take advantage of everything in this book

So, let's get started by asking ourselves What is FP? and start working on that topic.

What is Functional Programming?

If you go back in computer history, you'll find that the second–oldest programming language still in use, LISP, has its bases in Functional Programming. Since then there have been many more functional languages, and FP has been applied more widely. But even so, if you ask around what FP is, you'll probably get two widely dissimilar answers.

Depending on whom you ask, you'll either learn that it's a modern, advanced, enlightened approach to programming that leaves every other paradigm behind, or you'll be told that it's mainly a theoretical thing, with more complications than benefits, practically impossible to implement in the real world. And, as usual, the real answer is not in the extremes, but somewhere within.

For Trivia buffs, the oldest language still in use is FORTRAN, which appeared in 1957, a year before LISP. Quite shortly after LISP came another longlived language: COBOL, for businessoriented programming.

Theory versus practice

In this book, we won't be going about FP in a theoretical way: our point is, rather, to show how some of its techniques and tenets can be successfully applied for common, everyday JavaScript programming. But, and this is important, we won't be going about this in a dogmatic fashion, but rather in a very practical way. We won't dismiss useful JS constructs, only because they don't happen to fulfill the academic expectations of FP. We won't avoid practical JS features just to fit the FP paradigm. In fact, we could almost say we'll be doing SFP—Sorta Functional Programming because our code will be a mixture of FP features and more classical imperative and Object Oriented Programming (OOP).

(This doesn't mean that we'll be leaving all the theory by the side. We'll be picky, and just touch the main theoretical points, give some vocabulary and definitions, and explain core FP concepts... but we'll always be keeping in sight the idea of helping to produce actual, useful, JS code, and not to try to achieve some mystical, dogmatic FP criteria.)

OOP has been a way to solve the inherent complexity of writing large programs and systems, and developing clean, extensible, scalable application architectures. However, because of the scale of today's web applications, the complexity of all codebases is continuously growing. Also, the newer features of JS make it possible to develop applications that wouldn't even have been possible just a few years ago; think of mobile (hybrid) apps done with Ionic, Apache Cordova, or React Native, or desktop apps done with Electron or NW.js, for example. JS has also migrated to the backend with Node.js, so today the scope of usage for the language has grown in a serious way, and dealing with all the added complexity taxes all designs.

A different way of thinking

FP implies a different way of writing programs, which can sometimes be difficult to learn. In most languages, programming is done in imperative fashion: a program is a sequence of statements, executed in a prescribed fashion, and the desired result is achieved by creating objects and doing manipulations on them, which usually modify the objects themselves. FP is based on producing the desired result by evaluating expressions, built out of functions composed together. In FP, it's usual to pass functions around (as parameters to other functions, or returned as the result of some calculation), to not use loops (opting for recursion instead), and to skip side effects (such as modifying objects or global variables).

Another way of saying this, is that FP focuses on what should be done, rather than on how. Instead of worrying about loops or arrays, you work at a higher level, considering what you need to be done. After getting accustomed to this style, you'll find that your code becomes simpler, shorter, more elegant, and can be easily tested and debugged. However, don't fall into the trap of considering FP as a goal! Think of FP only as a means towards an end, as with all software tools. Functional code isn't good just for being functional... and writing bad code is just as possible with FP as with any other techniques!

What Functional Programming is not

Since we have been saying some things about what FP is, let's also clear some common misconceptions, and consider some things that FP is not:

  • FP isn't just an academic ivory tower thing: It is true that the lambda calculus upon which it is based, was developed by Alonzo Church in 1936, as a tool in order to prove an important result in theoretical computer science. (This work preceded modern computer languages by more than 20 years!). However, FP languages are being used today for all kinds of systems.
  • FP isn't the opposite of object–oriented programming (OOP): Also, it isn't either a case of choosing declarative or imperative ways of programming. You can mix and match as it best suits you, and we'll be doing that sort of thing in this book, bringing together the best of all worlds. 
  • FP isn't overly complex to learn: Some of the FP languages are rather different from JS, but the differences are mostly syntactic. Once you learn the basic concepts, you'll see you can get the same results in JS as with FP languages.

It may also be relevant to mention that several modern frameworks, such as the React+Redux combination, include FP ideas. For example, in React it's said that the view (whatever the user gets to see at a given moment) is a function of the current state. You use a function to compute what HTML and CSS must be produced at each moment, thinking in black box fashion.

Similarly, in Redux you get the concept of actions that are processed by reducers. An action provides some data, and a reducer is a function that produces the new state for the application in a functional way out of the current state and the provided data. 

So, both because of theoretical advantages (we'll be getting to those in the following section) and of practical ones (such as getting to use the latest frameworks and libraries) it makes sense to consider FP coding; let's get on with it.

Why use Functional Programming?

Throughout the years, there have been many programming styles and fads. However, FP has proved quite resilient and is of great interest today. Why would you care to use FP? The question should rather first be, What do you want to get? and only then Does FP get you that?

What we need

We can certainly agree that the following list of concerns are universal. Our code should be:

  • Modular: The functionality of your program should be divided into independent modules, each of which contains what it needs to perform one aspect of the program functionality. Changes in a module or function shouldn't affect the rest of the code.
  • Understandable: a reader of your program should be able to discern its components, their functions, and understand their relationships without undue effort. This is highly correlated with maintainability: your code will have to be maintained at some time in the future, to change or add some new functionality.
  • Testable: unit tests try out small parts of your program, verifying their behavior with independence of the rest of the code. Your programming style should favor writing code that simplifies the job of writing unit tests. Also, unit tests are like documentation, insofar that they can help readers understand what the code is supposed to do.
  • Extensible: it's a fact that your program will someday require maintenance, possibly to add new functionality. Those changes should impact only minimally (if at all) the structure and data flow of the original code. Small changes shouldn't imply large, serious refactorings of your code.
  • Reusable: code reuse has the goal of saving resources, time, money, and reducing redundancy, by taking advantage of previously written code. There are some characteristics that help this goal, such as modularity (which we already mentioned), plus high cohesion (all the pieces in a module do belong together), low coupling (modules are independent of each other), separation of concerns (the parts of a program should overlap in functionality as little as possible), and information hiding (internal changes in a module shouldn't affect the rest of the system).

What we get

So, now, does FP get you these five characteristics?

  • In FP, the goal is writing separate independent functions, which are joined together to produce the final results.
  • Programs written in functional style usually tend to be cleaner, shorter, and easier to understand.
  • Functions can be tested on its own, and FP code has advantages for that.
  • You can reuse functions in other programs, because they stand on their own, not depending on the rest of the system. Most functional programs share common functions, several of which we'll be considering in this book.
  • Functional code is free from side effects, which means you can understand the objective of a function by studying it, without having to consider the rest of the program.

Finally, once you get used to FP ways, code becomes more understandable and easier to extend. So, it seems that all five characteristics can be ensured with FP!

For a well balanced look at reasons for FP, I'd suggest reading Why Functional Programming Matters, by John Hughes; it's available online at www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf. It's not geared towards JS, but the arguments are easily understandable, anyway.

Not all is gold...

However, let's strive for a bit of balance. Using FP isn't a silver bullet that will automagically make your code better. Some FP solutions are actually tricky — and there are developers who show much glee in writing code and then asking What does this do? If you aren't careful, your code may become write–only, practically impossible to maintain... and there go Understandable, Extensible, and Reusable out of the door!

Another disadvantage: you may find it harder to find FPsavvy developers. (Quick question: how many Functional Programmer Sought job ads have you ever seen?) The vast majority of today's JS code is written in imperative, nonfunctional ways, and most coders are used to that way of working. For some, having to switch gears and start writing programs in a different way, may prove an unpassable barrier. 

Finally, if you try to go fully functional, you may find yourself at odds with JS, and simple tasks may become hard to do. As we said at the beginning, we'll rather opt for Sorta FP, so we won't be drastically rejecting any JS features that aren't 100% functional. We want to use FP to simplify our coding, not to make it more complex!

So, while I'll strive to show you the advantages of going functional in your code, as with any change, there will always be some difficulties. However, I'm fully convinced that you'll be able to surmount them and that your organization will develop better code by applying FP. Dare to change!

Is JavaScript functional?

About this time, another important question that you should be asking: Is JS a functional language? Usually, when thinking about FP, the mentioned languages do not include JS, but do listless common options, such as Clojure, Erlang, Haskell, or Scala. However, there is no precise definition for FP languages or a precise set of features that such languages should include. The main point is that you can consider a language to be functional if it supports the common programming style associated with FP. 

JavaScript as a tool

What is JS? If you consider popularity indices such as the ones at www.tiobe.com/tiobe-index/ or  http://pypl.github.io/PYPL.html, you'll find that JS consistently is in the top ten of popularity. From a more academic point of view, the language is sort of a mixture, with features from several different languages. Several libraries helped the growth of the language, by providing features that weren't so easily available, as classes and inheritance (today's version of JS does support classes, but that was not the case not too long ago) that otherwise had to be simulated by doing some prototype tricks.

The name JavaScript was chosen to take advantage of the popularity of Java — just as a marketing ploy! Its first name was Mocha; then, LiveScript, and only then, JavaScript.

JS has grown to be incredibly powerful. But, as with all power tools, it gives you a way to produce great solutions, and also to do great harm. FP could be considered to be a way to reduce or leave aside some of the worst parts of the language and focus on working in a safer, better way. However, due to the immense amount of existing JS code, you cannot expect large reworkings of the language that would cause most sites to fail. You must learn to live on with the good and the bad, and simply avoid the latter parts.

In addition, JS has a broad variety of available libraries that complete or extend the language in many ways. In this book, we'll be focusing on using JS on its own, but we will make references to existing, available code.

If we ask if JS is actually functional, the answer will be, once again, sorta. JS can be considered to be functional, because of several features such as firstclass functions, anonymous functions, recursion, and closures -- we'll get back to this later. On the other hand, JS has plenty of non–FP aspects, such as side effects (impurity), mutable objects, and practical limits to recursion. So, when programming in a functional way, we'll be taking advantage of all the relevant JS language features, and we'll try to minimize the problems caused by the more conventional parts of the language. In this sense, JS will or won't be functional, depending on your programming style!

If you want to use FP, you should decide upon which language to use. However, opting for fully functional languages may not be so wise. Today, developing code isn't as simple as just using a language: you will surely require frameworks, libraries, and other sundry tools. If we can take advantage of all the provided tools, but at the same time introduce FP ways of working in our code, we'll be getting the best of both worlds — and never mind if JS is or isn't functional!

Going functional with JavaScript

JS has evolved through the years, and the version we'll be using is (informally) called JS8, and (formally) ECMAScript 2017, usually shortened to ES2017 or ES8; this version was finalized in June 2017. The previous versions were:

  • ECMAScript 1, June 1997
  • ECMAScript 2, June 1998, basically the same as the previous version
  • ECMAScript 3, December 1999, with several new functionalities
  • ECMAScript 5 appeared only in December 2009 (and no, there never was an ECMAScript 4, because it was abandoned)
  • ECMAScript 5.1 was out in June 2011
  • ECMAScript 6 (or ES6; later renamed ES2015) in June 2015
  • ECMAScript 7 (also ES7, or ES2016) was finalized in June 2016
  • ECMAScript 8 (ES8 or ES2017) was finalized in June 2017
ECMA originally stood for European Computer Manufacturers Association, but nowadays the name isn't considered an acronym anymore. The organization is responsible for more standards other than JS, including JSON, C#, Dart, and others. See its site at www.ecma-international.org/.

You can read the standard language specification at www.ecma-international.org/ecma-262/7.0/. Whenever we refer to JS in the text without further specification, ES8 (ES2017) is meant. However, in terms of the language features that are used in the book, if your were just to use ES2015, you'd have no problems with this book. 

No browsers fully implement ES8; most provide an older version, JavaScript 5 (from 2009), with a (always growing) smattering of ES6, ES7, and ES8 features. This will prove to be a problem, but fortunately, a solvable one; we'll get to this shortly, and we'll be using ES8 throughout the book. 

In fact, there are only a little differences between ES2016 and ES2015, such as the Array.prototype.includes method and the exponentiation operator **. There are more differences between ES2017 and ES2016 – such as async and await, some string padding functions, and more – but they won't impact our code.

Key features of JavaScript

JS isn't a functional language, but it has all the features we need to work as if it were. The main features of the language that we will be using are:

  • Functions as firstclass objects
  • Recursion
  • Arrow functions
  • Closures
  • Spread

Let's see some examples of each one, to explain why they will be useful to us.

Functions as First Class Objects

Saying that functions are first class objects (also: first class citizens) means that you can do everything with functions, that you can do with other objects. For example, you can store a function in a variable, you can pass it to a function, you can print it out, and so on. This is really the key to doing FP: we will often be passing functions as parameters (to other functions) or returning a function as the result of a function call. 

If you have been doing async Ajax calls, you have already been using this feature: a callback is a function that will be called after the Ajax call finishes and is passed as a parameter. Using jQuery, you could write something like:

$.get("some/url", someData, function(result, status) {
// check status, and do something
// with the result
});

The $.get() function receives a callback function as a parameter, and calls it after the result is obtained. 

This is better solved, in a more modern way, by using promises or async/await, but for, but for the sake of our example, the older way is enough. We'll be getting back to promises, though, in section Building Better Containers, of chapter 12Building Better Containers – Functional Data Types, when we discuss Monads; in particular, see section Unexpected Monads: Promises.

Since functions can be stored in variables, you could also write:

var doSomething = function(result, status) {
// check status, and do something
// with the result
};
$.get("some/url", someData, doSomething);

We'll be seeing more examples of this in Chapter 6, Producing Functions – Higher–Order Functions, when we consider HigherOrder Functions.

Recursion

This is a most potent tool for developing algorithms and a great aid for solving large classes of problems. The idea is that a function can at a certain point call itself, and when that call is done, continue working with whatever result it has received. This is usually quite helpful for certain classes of problems or definitions. The most often quoted example is the factorial function (the factorial of n is written n!) as defined for non-negative integer values:

  • If n is 0, then n!=1
  • If n is greater than 0, then n! = n * (n-1)!
The value of n! is the number of ways you can order n different elements in a row. For example, if you want to place five books in line, you can pick any of the five for the first place, and then order the other four in every possible way, so 5! = 5*4!. If you continue to work this example, you'll get that 5! = 5*4*3*2*1=120, so n! is the product of all numbers up to n.

This can be immediately turned into JS code:

function fact(n) {
if (n === 0) {
return 1;
} else {
return n * fact(n - 1);
}
}
console.log(fact(5)); // 120

Recursion will be a great aid for the design of algorithms. By using recursion you could do without any while or for loops -- not that we want to do that, but it's interesting that we can! We'll be devoting the complete chapter 9Designing Functions - Recursion, to designing algorithms and writing functions recursively.

Closures

Closures are a way to implement data hiding (with private variables), which leads to modules and other nice features. The key concept is that when you define a function, it can refer to not only its own local variables, but also to everything outside of the context of the function:

function newCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const nc = newCounter();
console.log(nc()); // 1
console.log(nc()); // 2
console.log(nc()); // 3

Even after newCounter exits, the inner function still has access to count, but that variable is not accessible to any other parts of your code.

This isn't a very good example of FP -- a function (nc(), in this case) isn't expected to return different results when called with the same parameters!

We'll find several uses for closures: among others, memoization (see chapter 4, Behaving Properly - Pure Functions, and chapter 6, Producing Functions - Higher-Order Functions) and the module pattern (see chapter 3, Starting Out with Functions - A Core Concept, and chapter 11, Implementing Design Patterns - The Functional Way).

Arrow functions

Arrow functions are just a shorter, more succinct way of creating an (unnamed) function. Arrow functions can be used almost everywhere a classical function can be used, except that they cannot be used as constructors. The syntax is either (parameter, anotherparameter, ...etc) => { statements } or (parameter, anotherparameter, ...etc) => expression. The first one allows you to write as much code as you want; the second is short for { return expression }. We could rewrite our earlier Ajax example as:

$.get("some/url", data, (result, status) => {
// check status, and do something
// with the result
});

A new version of the factorial code could be:

const fact2 = n => {
if (n === 0) {
return 1;
} else {
return n * fact2(n - 1);
}
};
console.log(fact2(5)); // also 120
Arrow functions are usually called anonymous functions, because of their lack of a name. If you need to refer to an arrow function, you'll have to assign it to a variable or object attribute, as we did here; otherwise, you won't be able to use it. We'll see more in section Arrow Functions of Chapter 3, Starting Out with Functions - A Core Concept.

You would probably write the latter as a one-liner -- can you see the equivalence?

const fact3 = n => (n === 0 ? 1 : n * fact3(n - 1));
console.log(fact3(5)); // again 120

With this shorter form, you don't have to write return -- it's implied. A short comment: when the arrow function has a single parameter, you can omit the parentheses around it. I usually prefer leaving them, but I've applied a JS beautifier, prettier, to the code, and it removes them. It's really up to you whether to include them or not! (For more on this tool, check out https://github.com/prettier/prettier.) By the way, my options for formatting were --print-width 75 --tab-width 4 --no-bracket-spacing.

In lambda calculus, a function as x => 2*x would be represented as λx.2*x  -- though there are syntactical differences, the definitions are analogous. Functions with more parameters are a bit more complicated: (x,y)=>x+y would be expressed as λx.λy.x+y. We'll see more about this in section Of Lambdas and functions, in Chapter 3, Starting Out with Functions - A Core Concept, and in section Currying, in Chapter 7, Transforming Functions - Currying and Partial Application.

Spread

The spread operator (see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator) lets you expand an expression in places where you would otherwise require multiple arguments, elements, or variables. For example, you can replace arguments in a function call:

const x = [1, 2, 3];
function sum3(a, b, c) {
return a + b + c;
}
const y = sum3(...x); // equivalent to sum3(1,2,3)
console.log(y); // 6

You can also create or join arrays:

const f = [1, 2, 3];
const g = [4, ...f, 5]; // [4,1,2,3,5]
const h = [...f, ...g]; // [1,2,3,4,1,2,3,5]

It works with objects too:

const p = { some: 3, data: 5 };
const q = { more: 8, ...p }; // { more:8, some:3, data:5 }

You can also use it to work with functions that expect separate parameters, instead of an array. Common examples of this would be Math.min() and Math.max():

const numbers = [2, 2, 9, 6, 0, 1, 2, 4, 5, 6];
const minA = Math.min(...numbers); // 0

const maxArray = arr => Math.max(...arr);
const maxA = maxArray(numbers); // 9

You can also write the following equation. The .apply() method requires an array of arguments, but .call() expects individual arguments:

someFn.apply(thisArg, someArray) === someFn.call(thisArg, ...someArray);
If you have problems remembering what arguments are required by .apply() and .call(), this mnemonic may help: A is for array, and C is for comma. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call for more information.

Using the spread operator helps write shorter, more concise code, and we will be taking advantage of it.

How do we work with JavaScript?

All this is quite well, but as we mentioned before, it so happens that the JS version available most everywhere isn't ES8, but rather the earlier JS5. An exception to this is Node.js: it is based on Chrome's V8 high-performance JS engine, which already has several ES8 features available. Nonetheless, as of today, ES8 coverage isn't 100% complete, and there are features that you will miss. (Check out https://nodejs.org/en/docs/es6/ for more on Node and V8.)

So, what can you do, if you want to code using the latest version, but the available one is an earlier, poorer one? Or, what happens if most of your users may be using older browsers, which don't support the fancy features you're keen on using? Let's see some solutions for that.

If you want to be sure before using any given new feature, check out the compatibility table at https://kangax.github.io/compat-table/es6/. (See Figure 1.1). For Node.js specifically, check out http://node.green/.
Figure 1.1. - The latest versions of JS aren't yet widely and fully supported, so you'll have to check before using any of their new features

Using transpilers

In order to get out of this availability and compatibility problem, there are a couple of transpilers that you can use. Transpilers take your original ES8 code, and transform it into equivalent JS5 code. (It's a source-to-source transformation, instead of a source-to-object code as in compilation.) You can code using advanced ES8 features, but the user's browsers will receive JS5 code. A transpiler will also let you keep up with upcoming versions of the language, despite the time needed by browsers to adopt new standards across desktop and mobile devices.

If you wonder where did the word transpiler come from, it is a portmanteau of translate and compiler. There are many such combinations in technological speak: email (electronic+mail), emoticon (emotion+icon), malware (malicious+software), or alphanumeric (alphabetic+numeric), and several more.

The most common transpilers for JS are Babel (at https://babeljs.io/) and Traceur (at https://github.com/google/traceur-compiler). With tools such as npm or Webpack, it's fairly easy to configure things so your code will get automatically transpiled and provided to end users. You can also try out transpilation online; see Figure 1.2 for an example using Babel's online environment:

Figure 1.2 - The Babel transpiler converts ES8 code into compatible JS5 code

If you prefer Traceur, use its tool at https://google.github.io/traceur-compiler/demo/repl.html# instead, but you'll have to open a developer console to see the results of your running code. (See Figure 1.3 for this.) Select the EXPERIMENTAL option, to fully enable ES8 support:

Figure 1.3 - The Traceur transpiler is an equally valid alternative for ES8-to-JS5 translation
Using transpilers is also a great way to learn the new JS features. Just type in some code at the left, and see the equivalent result at the right. Alternatively, use command line interface (CLI) tools to transpile a source file, and then inspect the produced output.

There's a final possibility you may want to consider: instead of JS, opt for Microsoft's TypeScript (at http://www.typescriptlang.org/), a superset of JS, compiled to JS5. The main advantage of TypeScript is adding (optional) static type checks to JS, which helps detect some programming errors at compile time. Beware: as with Babel or Traceur, not all of ES8 will be available.

You can also get type checks, without using TypeScript, by using Facebook's Flow (see https://flow.org/).

If you opt to go with TypeScript, you can also test it online at their playground; see http://www.typescriptlang.org/play/. You can set options to be more or less strict with data types checks, and you can also run your code on the spot. See figure 1.4:

Figure 1.4 - TypeScript adds type checking features, for safer JS programming

Working online

There are some more online tools that you can use to test out your JS code. Check out JSFiddle (at https://jsfiddle.net/), CodePen (at https://codepen.io/), or JSBin (at http://jsbin.com/), among others. You may have to specify whether to use Babel or Traceur; otherwise, newer JS features will be rejected. See an example of JSFiddle in Figure 1.5:

Figure 1.5 - JSFiddle lets you try out ES8 code (plus HTML and CSS) without requiring any further tools

Testing

Questions

1.1. Classes as first-class objects: We saw that functions are first class objects, but did you know classes also are? (Though, of course, speaking of classes as objects does sound weird...) Study this example and see what makes it tick! Be careful: there's some purposefully weird code in it:

      const makeSaluteClass = term =>
class {
constructor(x) {
this.x = x;
}

salute(y) {
console.log(`${this.x} says "${term}" to ${y}`);
}
};

const Spanish = makeSaluteClass("HOLA");
new Spanish("ALFA").salute("BETA");
// ALFA says "HOLA" to BETA

new (makeSaluteClass("HELLO"))("GAMMA").salute("DELTA");
// GAMMA says "HELLO" to DELTA

const fullSalute = (c, x, y) => new c(x).salute(y);
const French = makeSaluteClass("BON JOUR");
fullSalute(French, "EPSILON", "ZETA");
// EPSILON says "BON JOUR" to ZETA

1.2. Factorial errors: Factorials, as we defined them, should only be calculated for non-negative integers. However, the function we wrote doesn't verify if its argument is valid or not. Can you add the necessary checks? Try to avoid repeated, redundant tests!

1.3. Climbing factorial: Our implementation of factorial starts multiplying by n, then by n-1, then n-2, and so on., in what we could call a downward fashion. Can you write a new version of the factorial function, that will loop upwards?

Summary

In this chapter, we have seen the basics of functional programming, a bit of its history, its advantages (and also some possible disadvantages, to be fair), why we can apply it in JavaScript, which isn't usually considered a functional language, and what tools we'll need in order to take advantage of the rest of the book.

In chapter 2Thinking Functionally - A First Example, we'll go over an example of a simple problem, and look at it in common ways, to finally end by solving it in a functional manner and analyze the advantages of that way of working.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Become proficient and skilled with Functional Programming in JavaScript to solve real-world development problems
  • Successfully apply Functional Programming concepts and techniques to everyday JavaScript programming
  • Bring modularity, reusability, testability, and performance to your web apps

Description

Functional programming is a programming paradigm for developing software using functions. Learning to use functional programming is a good way to write more concise code, with greater concurrency and performance. The JavaScript language is particularly suited to functional programming. This book provides comprehensive coverage of the major topics in functional programming with JavaScript to produce shorter, clearer, and testable programs. You’ll delve into functional programming; including writing and testing pure functions, reducing side-effects, and other features to make your applications functional in nature. Specifically, we’ll explore techniques to simplify coding, apply recursion for loopless coding, learn ways to achieve immutability, implement design patterns, and work with data types. By the end of this book, you’ll have developed the JavaScript skills you need to program functional applications with confidence.

Who is this book for?

If you are a JavaScript developer and want to apply functional programming techniques, then this book is for you. Only a basic knowledge of the concepts of functional programming is required for this book.

What you will learn

  • Create more reliable code with closures and immutable data
  • Convert existing methods into pure functions, and loops into recursive methods
  • Develop more powerful applications with currying and function composition
  • Separate the logic of your system from implementation details
  • Implement composition and chaining techniques to simplify coding
  • Use functional programming techniques where it makes the most sense
Estimated delivery fee Deliver to Switzerland

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 29, 2017
Length: 386 pages
Edition : 1st
Language : English
ISBN-13 : 9781787287440
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Switzerland

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

Product Details

Publication date : Nov 29, 2017
Length: 386 pages
Edition : 1st
Language : English
ISBN-13 : 9781787287440
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 133.97
JavaScript : Functional Programming for JavaScript Developers
€59.99
Learning JavaScript Data  Structures and Algorithms
€36.99
Mastering JavaScript Functional Programming
€36.99
Total 133.97 Stars icon
Banner background image

Table of Contents

14 Chapters
Becoming Functional - Several Questions Chevron down icon Chevron up icon
Thinking Functionally - A First Example Chevron down icon Chevron up icon
Starting Out with Functions - A Core Concept Chevron down icon Chevron up icon
Behaving Properly - Pure Functions Chevron down icon Chevron up icon
Programming Declaratively - A Better Style Chevron down icon Chevron up icon
Producing Functions - Higher-Order Functions Chevron down icon Chevron up icon
Transforming Functions - Currying and Partial Application Chevron down icon Chevron up icon
Connecting Functions - Pipelining and Composition Chevron down icon Chevron up icon
Designing Functions - Recursion Chevron down icon Chevron up icon
Ensuring Purity - Immutability Chevron down icon Chevron up icon
Implementing Design Patterns - The Functional Way Chevron down icon Chevron up icon
Building Better Containers - Functional Data Types Chevron down icon Chevron up icon
Bibliography Chevron down icon Chevron up icon
Answers to Questions Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(7 Ratings)
5 star 71.4%
4 star 14.3%
3 star 14.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Jacob Jul 07, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I'm a professional developer with more than 15 years of experience. So I'm not really a kid excited by a "cool" line of code or a new technology that will get old in the next few years or so.This book is about a particular approach to programming which is why I like it.
Amazon Verified review Amazon
Cheung Wai Lok Oct 10, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
i would recommend it to those who want to learn FP in javascript
Amazon Verified review Amazon
Amazon Customer Jun 13, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book
Amazon Verified review Amazon
Rene Mar 11, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Ich bin absolut begeistert von dem Buch, viele gute Beispiele die immer wieder aufgegriffen werden und durchweg klasse erklärt. Die Taschenbuchfassung ist jedoch das letzte was mir je untergekommen ist. Haufenweise lose Seiten die herausfallen, teilweise üble Druckfehler. Hoffe aber das war eine schlimme Ausnahme.
Amazon Verified review Amazon
Adrian Perez Feb 07, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I enjoyed the practical approach, and the decision as to not use libraries which are common source of confusion and rather fragmented in the JS ecosystem (e.g you use ramda but you need sanctuary or folktale, etc). As someone who has been learning Clojure and Haskell over the past year and wishing I could just straight up use those at work, this book provided a sign of relief in showing how to get some of their features in Javascript. It goes a long way into functional thinking and its explanation of recursion it’s one of the most enjoyable I’ve seen.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela