Mastering JavaScript Functional Programming

3.7 (3 reviews total)
By Federico Kereki
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Becoming Functional – Several Questions

About this book

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.

Publication date:
November 2017
Publisher
Packt
Pages
386
ISBN
9781787287440

 

Chapter 1. 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.

Note

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 long–lived language: COBOL, for business–oriented 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!

Note

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 FP–savvy 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, non–functional 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.

Note

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 first–class 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

Note

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. 

Note

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 first–class 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. 

Note

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 12, Building 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 Higher–Order 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)!

Note

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 9, Designing 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.

Note

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

Note

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.

Note

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);

Note

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.

Note

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.

Note

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

Note

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.

Note

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

We will also touch on testing, which is, after all, one of FP's main advantages. For that, we will be using Jasmine (https://jasmine.github.io/), though we could also opt for Mocha (http://mochajs.org/).

You can run Jasmine test suites with a runner such as Karma (https://karma-runner.github.io), but I opted for standalone tests; see https://github.com/jasmine/jasmine#installation for details.

 

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 2, Thinking 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.

 

About the Author

  • Federico Kereki

    Federico Kereki is a Uruguayan systems engineer, with a master's degree in education, and over 30 years' experience as a consultant, system developer, university professor, and writer. He is currently a subject matter expert at Globant, and he has taught CS courses at Universidad de la República, Universidad ORT Uruguay, and Universidad de la Empresa.

    He has written for the Linux Journal and the LinuxPro Magazine in the USA, Linux+ and Mundo Linux in Europe, and websites such as Linux [dot] com and IBM DeveloperWorks. He has also written booklets on computer security, and two books—Essential GWT, and Mastering JavaScript Functional Programming.

    Browse publications by this author

Latest Reviews

(3 reviews total)
Good book, with nice examples. Good for people who has previous experience with JS.
Don't know, email links never resolved to anything other than a 404 page.
Es un documento claro y completo

Recommended For You

Book Title
Access this book, plus 7,500 other titles for FREE
Access now