Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> Functional Programming> Mastering JavaScript Functional Programming
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

Arrow left icon
Profile Icon Federico Kereki
Arrow right icon
€26.98€29.99
Full star iconFull star iconFull star iconFull star iconHalf star icon4.6(7 Ratings)
eBookNov 2017386 pages1st Edition
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview book icon Preview Book

Mastering JavaScript Functional Programming

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 doingSFP—Sorta Functional Programming because our code will be a mixture of FP features and more classical imperative andObject 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 onwhat should be done, rather than onhow. 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 isnot:

  • 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 inblack box fashion.

Similarly, in Redux you get the concept ofactions that are processed byreducers. 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 thenDoes 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 withmaintainability: 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 asmodularity (which we already mentioned), plushigh 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), andinformation 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!

Not all is gold...

However, let's strive for a bit of balance. Using FP isn't asilver bullet that willautomagically make your code better. Some FP solutions are actually tricky — and there are developers who show much glee in writing code and then askingWhat does this do? If you aren't careful, your code may becomewrite–only, practically impossible to maintain... and there goUnderstandable,Extensible, andReusable out of the door!

Another disadvantage: you may find it harder to find FPsavvy developers. (Quick question: how manyFunctional 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 gofully 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 forSorta 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 considerpopularity indices such as the ones atwww.tiobe.com/tiobe-index/ or  http://pypl.github.io/PYPL.html, you'll find that JS consistently is in thetop 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 someprototype tricks.

The nameJavaScript was chosen to take advantage of the popularity of Java — just as a marketing ploy! Its first name wasMocha; 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 ofnon–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 onyour 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

You can read the standard language specification atwww.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 andawait, 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 arefirst class objects (also:first classcitizens) 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: acallback 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. 

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 inChapter 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 callitself, and whenthat 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 ofn is writtenn!) as defined for non-negative integer values:

  • Ifn is 0, thenn!=1
  • Ifn is greater than 0, thenn! = n * (n-1)!
The value ofn! 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, so5! = 5*4!. If you continue to work this example, you'll get that5! = 5*4*3*2*1=120, son! is the product of all numbers up ton.

This can be immediately turned into JS code:

functionfact(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 anywhile orfor loops -- not that wewant to do that, but it's interesting that wecan! We'll be devoting the completechapter 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 afternewCounter exits, the inner function still has access tocount, 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 (seechapter 4,Behaving Properly - Pure Functions, andchapter 6,Producing Functions - Higher-Order Functions) and themodule pattern (seechapter 3,Starting Out with Functions - A Core Concept, andchapter 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{ returnexpression }. 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:

constfact2 = n => {
if (n === 0) {
return 1;
} else {
return n * fact2(n - 1);
}
};
console.log(fact2(5)); //also 120

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 writereturn -- 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 asx => 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, inChapter 3,Starting Out with Functions - A Core Concept, and in sectionCurrying, inChapter 7,Transforming Functions - Currying and Partial Application.

Spread

The spread operator (seehttps://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 beMath.min() andMath.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 followingequation. 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 oftranspilers 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 wordtranspiler come from, it is a portmanteau oftranslate andcompiler. There are many such combinations in technological speak:email (electronic+mail),emoticon (emotion+icon),malware (malicious+software), oralphanumeric (alphabetic+numeric), and several more.

The most common transpilers for JS areBabel (at https://babeljs.io/) andTraceur (at https://github.com/google/traceur-compiler). With tools such asnpm orWebpack, 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 theEXPERIMENTAL 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, usecommand 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 (athttp://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 theirplayground; 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 outJSFiddle (at https://jsfiddle.net/),CodePen (at https://codepen.io/), orJSBin (athttp://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 knowclasses also are? (Though, of course, speaking of classes asobjects 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 byn, then byn-1, thenn-2, and so on., in what we could call a downward fashion. Can you write a new version of the factorial function, that will loopupwards?

Left arrow icon

Page1 of 7

Right arrow icon
Download code iconDownload 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

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 :9781787289734
Category :
Languages :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

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

Packt Subscriptions

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

Frequently bought together


Mastering JavaScript Functional Programming
Mastering JavaScript Functional Programming
Read more
Nov 2017386 pages
Full star icon4.6 (7)
eBook
eBook
€26.98€29.99
€36.99
Learning JavaScript Data  Structures and Algorithms
Learning JavaScript Data Structures and Algorithms
Read more
Apr 2018426 pages
Full star icon3.1 (9)
eBook
eBook
€26.98€29.99
€36.99
Functional Programming in JavaScript
Functional Programming in JavaScript
Read more
Mar 2015172 pages
eBook
eBook
€66.99€74.99
€93.99
€59.99
Stars icon
Total133.97
Mastering JavaScript Functional Programming
€36.99
Learning JavaScript Data  Structures and Algorithms
€36.99
Functional Programming in JavaScript
€59.99
Total133.97Stars icon

Table of Contents

14 Chapters
Becoming Functional - Several QuestionsChevron down iconChevron up icon
Becoming Functional - Several Questions
What is Functional Programming?
Why use Functional Programming?
Is JavaScript functional?
How do we work with JavaScript?
Questions
Summary
Thinking Functionally - A First ExampleChevron down iconChevron up icon
Thinking Functionally - A First Example
The problem - do something only once
Some bad solutions
A functional solution
Questions
Summary
Starting Out with Functions - A Core ConceptChevron down iconChevron up icon
Starting Out with Functions - A Core Concept
All about functions
Using functions in FP ways
Questions
Summary
Behaving Properly - Pure FunctionsChevron down iconChevron up icon
Behaving Properly - Pure Functions
Pure functions
Impure functions
Testing - pure versus impure
Questions
Summary
Programming Declaratively - A Better StyleChevron down iconChevron up icon
Programming Declaratively - A Better Style
Transformations
Logical higher-order functions
Questions
Summary
Producing Functions - Higher-Order FunctionsChevron down iconChevron up icon
Producing Functions - Higher-Order Functions
Wrapping functions
Altering functions
Other higher-order functions
Questions
Summary
Transforming Functions - Currying and Partial ApplicationChevron down iconChevron up icon
Transforming Functions - Currying and Partial Application
A bit of theory
Currying
Partial application
Partial currying
Final thoughts
Questions
Summary
Connecting Functions - Pipelining and CompositionChevron down iconChevron up icon
Connecting Functions - Pipelining and Composition
Pipelining
Composing
Questions
Summary
Designing Functions - RecursionChevron down iconChevron up icon
Designing Functions - Recursion
Using recursion
Recursion techniques
Questions
Summary
Ensuring Purity - ImmutabilityChevron down iconChevron up icon
Ensuring Purity - Immutability
The straightforward JS way
Persistent data structures
Questions
Summary
Implementing Design Patterns - The Functional WayChevron down iconChevron up icon
Implementing Design Patterns - The Functional Way
What are Design Patterns?
Object-oriented design patterns
Functional design patterns
Questions
Summary
Building Better Containers - Functional Data TypesChevron down iconChevron up icon
Building Better Containers - Functional Data Types
Data types
Containers
Functions as data structures
Questions
Summary
BibliographyChevron down iconChevron up icon
Bibliography
Answers to QuestionsChevron down iconChevron up icon
Answers to Questions

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
eBook
eBook
€20.99€23.99
€29.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
€20.99€23.99
€29.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
€26.98€29.99
€37.99
€37.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
€22.99€25.99
€31.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024504 pages
Full star icon4.7 (12)
eBook
eBook
€26.98€29.99
€37.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon5 (1)
eBook
eBook
€20.99€23.99
€29.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Nov 202457hrs 40mins
Video
Video
€56.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (21)
eBook
eBook
€28.99€32.99
€41.99
Right arrow icon

Customer reviews

Top Reviews
Rating distribution
Full star iconFull star iconFull star iconFull star iconHalf star icon4.6
(7 Ratings)
5 star71.4%
4 star14.3%
3 star14.3%
2 star0%
1 star0%
Filter icon Filter
Top Reviews

Filter reviews by




JacobJul 07, 2019
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
Cheung Wai LokOct 10, 2018
Full star iconFull star iconFull star iconFull star iconFull star icon5
i would recommend it to those who want to learn FP in javascript
Amazon Verified reviewAmazon
Amazon CustomerJun 13, 2018
Full star iconFull star iconFull star iconFull star iconFull star icon5
Great book
Amazon Verified reviewAmazon
ReneMar 11, 2018
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
Adrian PerezFeb 07, 2018
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
  • Arrow left icon Previous
  • 1
  • 2
  • Arrow right icon Next

People who bought this also bought

Left arrow icon
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
€26.98€29.99
€37.99
€37.99
Event-Driven Architecture in Golang
Event-Driven Architecture in Golang
Read more
Nov 2022384 pages
Full star icon4.9 (11)
eBook
eBook
€26.98€29.99
€37.99
The Python Workshop Second Edition
The Python Workshop Second Edition
Read more
Nov 2022600 pages
Full star icon4.6 (22)
eBook
eBook
€27.99€31.99
€38.99
Template Metaprogramming with C++
Template Metaprogramming with C++
Read more
Aug 2022480 pages
Full star icon4.6 (14)
eBook
eBook
€25.99€28.99
€35.99
Domain-Driven Design with Golang
Domain-Driven Design with Golang
Read more
Dec 2022204 pages
Full star icon4.4 (19)
eBook
eBook
€23.99€26.99
€33.99
Right arrow icon

About the author

Profile icon Federico Kereki
Federico Kereki
LinkedIn iconGithub icon
Federico Kereki is a Uruguayan Systems Engineer, with a Master's degree in Education, and over 30 years of experience as a consultant, system developer, and writer. Currently a Subject Matter Expert at Globant, he has taught at Universidad de la República, Universidad ORT Uruguay, and Universidad de la Empresa. He has written articles and booklets on programming, web development, security, and open source topics for blogs, magazines, and websites. He has also written several books, including Modern JavaScript Web Development Cookbook and the upcoming Data Structures and Algorithms in JavaScript. He resides, works, and teaches in Uruguay, but he wrote the first edition of this book while working in India, and the second edition during a sojourn in Mexico.
Read more
See other products by Federico Kereki
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.


[8]ページ先頭

©2009-2025 Movatter.jp