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
₹799.99 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781787287440
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 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
₹4500 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 ₹400 each
Feature tick icon Exclusive print discounts
₹5000 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 ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 13,258.97
JavaScript : Functional Programming for JavaScript Developers
₹5958.99
Learning JavaScript Data  Structures and Algorithms
₹3649.99
Mastering JavaScript Functional Programming
₹3649.99
Total 13,258.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.