Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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
Table of content icon View table of contents Preview book icon Preview Book

Mastering JavaScript Functional Programming

Thinking Functionally - A First Example

In chapter 1, Becoming Functional - Several Questions, we went over what FP is, mentioned some advantages of applying it, and listed some tools we'd be needing in JS... but let's now leave theory behind, and start out by considering a simple problem, and how to solve it in a functional way.

In this chapter, we will see:

  • A simple, common, e-commerce related problem
  • Several usual ways to solve it, with their associated defects
  • A way to solve the problem by looking at it functionally
  • A higher-order solution, which can be applied to other problems
  • How to do unit testing for the functional solutions

In future chapters, We'll be coming back to some of the topics listed here, so we won't be getting very much into details. We'll just show how FP can give a different outlook for our problem, and leave further details...

The problem - do something only once

Let's consider a simple, but common situation. You have developed an e-commerce site: the user can fill their shopping cart, and at the end, they must click on a BILL ME button, so their credit card will be charged. However, the user shouldn't click twice (or more) or they would be billed several times.

The HTML part of your application might have something like this, somewhere:

<button id="billButton" onclick="billTheUser(some, sales, data)">Bill me</button>

And, among the scripts you'd have something similar to this:

function billTheUser(some, sales, data) {
window.alert("Billing the user...");
// actually bill the user
}
Assigning the events handler directly in HTML, the way I did it, isn't recommended. Rather, in unobtrusive fashion, you should assign the handler through...

Some bad solutions

OK, how many ways can you think of, in order to solve our problem? Let's go over several solutions, and analyze their quality.

Solution #1 - hope for the best!

How can we solve the problem? The first solution may seem like a joke: do nothing, tell the user not to click twice, and hope for the best! Your page might look as Figure 2.1.

Figure 2.1. An actual screenshot of a page, just warning you against clicking more than once

This is a weasel way of avoiding the problem, but I've seen several websites that just warn the user about the risks of clicking more than once (see Figure 2.1) and actually do nothing to prevent the situation... the user got billed twice? we warned them... it's their...

A functional solution

Let's try to be more general: after all, requiring that some function or other be executed only once, isn't that outlandish, and may be required elsewhere! Let's lay down some principles:

  • The original function (the one that may be called only once) should do that thing, and no other
  • We don't want to modify the original function in any way
  • We need to have a new function that will call the original one only once
  • We want a general solution that we can apply to any number of original functions
The first principle listed previously is the single responsibility principle (the S in S.O.L.I.D.), which states that every function should be responsible over a single functionality. For more on S.O.L.I.D., check the article by Uncle Bob (Robert C. Martin, who wrote the five principles) at http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod.
...

Questions

2.1. No extra variables: Our functional implementation required using an extra variable, done, to mark whether the function had already been called. Not that it matters... but could you make do without using any extra variables? Note that we aren't telling you not to use any variables; it's just a matter of not adding any new ones, such as done, and only as an exercise!

2.2. Alternating functions: In the spirit of our onceAndAfter() function, could you write an alternator() higher-order function that gets two functions as arguments, and on each call, alternatively calls one and another? The expected behavior should be as in the following example:

     let sayA = () => console.log("A");
let sayB = () => console.log("B");

let alt = alternator(sayA, sayB);
alt(); // A
alt(); // B
alt(); // A
alt(); // B
alt...

Summary

In this chapter, we've seen a common, simple problem, based on a real-life situation, and after analyzing several usual ways of solving that, we went for a functional thinking solution. We saw how to apply FP to our problem, and we also found a more general higher-order way that we could apply to similar problems, with no further code changes. We saw how to write unit tests for our code, to round out the development job. Finally, we even produced an even better solution (from the point of view of the user experience) and saw how to code it and how to unit test it.

In the next chapter 3, Starting Out with Functions - A Core Concept, we'll be delving more deeply into functions, which are at the core of all FP.

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

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 icon Instant access to your Digital eBook purchase
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

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 177.97
JavaScript : Functional Programming for JavaScript Developers
$79.99
Learning JavaScript Data  Structures and Algorithms
$48.99
Mastering JavaScript Functional Programming
$48.99
Total $ 177.97 Stars icon

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

How do I buy and download an eBook? Chevron down icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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.