Book Image

Mastering JavaScript Functional Programming

By : Federico Kereki
Book Image

Mastering JavaScript Functional Programming

By: Federico Kereki

Overview of 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.
Table of Contents (22 chapters)
Dedication
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
8
Connecting Functions - Pipelining and Composition
Bibliography
Answers to Questions

Preface

In computer programming, paradigms abound: Some examples are imperative programming, structured (go to less) programming, object-oriented programming, aspect-oriented programming, and declarative programming. Lately, there has been renewed interest in a particular paradigm that can arguably be considered to be older than most (if not all) of the cited ones--functional programming. Functional Programming (FP) emphasizes writing functions, and connecting them in simple ways to produce more understandable and more easily tested code. Thus, given the increased complexity of today's web applications, it's logical that a safer, cleaner way of programming would be of interest.

This interest in FP comes hand-in-hand with the evolution of JavaScript. Despite its somewhat hasty creation (reportedly managed in only 10 days, in 1995, by Brendan Eich at Netscape), today it's a standardized and quickly growing language, with features more advanced than most other similarly popular languages. The ubiquity of the language, which can now be found in browsers, servers, mobile phones, and whatnot, has also impelled interest in better development strategies. Also, even if JavaScript wasn't conceived as a functional language by itself, the fact is that it provides all the features you'd require to work in that fashion, which is another plus.

It must also be said that FP hasn't been generally applied in industry, possibly because it has a certain aura of difficulty, and is thought to be theoretical rather than practical, even mathematical, and possibly uses vocabulary and concepts that are foreign to developers--Functors? Monads? Folding? Category theory? While learning all this theory will certainly be of help, it can also be argued that even with zero knowledge of the previous terms, you can understand the tenets of FP, and see how to apply it in your programming.

FP is not something you have to do on your own, without any help. There are many libraries and frameworks that incorporate, in greater or lesser degrees, the concepts of FP. Starting with jQuery (which does include some FP concepts), passing through Underscore and its close relative LoDash, or other libraries such as Ramda, and getting to more complete web development tools such as React and Redux, Angular, or Elm (a 100% functional language, which compiles into JavaScript), the list of functional aids for your coding is ever growing.

Learning how to use FP can be a worthwhile investment, and even though you may not get to use all of its methods and techniques, just starting to apply some of them will pay dividends in better code. You need not try to apply all of FP from the start, and you need not try to abandon every non-functional feature in the language either. JavaScript assuredly has some bad features, but it also has several very good and powerful ones. The idea is not to throw everything you learned and use and adopt a 100% functional way; rather, the guiding idea is evolution, not revolution. In that sense, it can be said that what we'll be doing is not FP, but rather Sorta Functional Programming (SFP), aiming for a fusion of paradigms.

A final comment about the style of the code in this book--it is quite true that there are several very good libraries that provide you with functional programming tools: Underscore, LoDash, Ramda, and more are counted among them. However, I preferred to eschew their usage, because I wanted to show how things really work. It's easy to apply a given function from some package or other, but by coding everything out (a vanilla FP, if you wish), it's my belief that you get to understand things more deeply. Also, as I will comment in some places, because of the power and clarity of arrow functions and other features, the pure JS versions can be even simpler to understand!

What this book covers

In this book, we'll cover Functional Programming (FP) in a practical way, though at times we will mention some theoretical points:

Chapter 1, Becoming Functional - Several Questions, discusses FP, gives reasons for its usage, and lists the tools that you'll need to take advantage of the rest of the book.

Chapter 2, Thinking Functionally - A First Example, will provide the first example of FP by considering a common web-related problem and going over several solutions, to finally center on a functional way.

Chapter 3, Starting Out with Functions - A Core Concept, will go over the central concept of FP: functions, and the different options available in JavaScript.

Chapter 4, Behaving Properly - Pure Functions, will consider the concept of purity and pure functions, and show how it leads to simpler coding and easier testing.

Chapter 5, Programming Declaratively - A Better Style, will use simple data structures to show how to produce results working not in an imperative way, but in a declarative fashion.

Chapter 6, Producing Functions - Higher-Order Functions, will deal with higher-order functions, which receive other functions as parameters and produce new functions as results.

Chapter 7, Transforming Functions - Currying and Partial Application, will show some methods for producing new and specialized functions from earlier ones.

Chapter 8, Connecting Functions - Pipelining and Composition, will show the key concepts regarding how to build new functions by joining previously defined ones.

Chapter 9, Designing Functions - Recursion, will show how a key concept in FP, recursion, can be applied to designing algorithms and functions.

Chapter 10, Ensuring Purity - Immutability, will show some tools that can help you work in a pure fashion by providing immutable objects and data structures.

Chapter 11, Implementing Design Patterns - The Functional Way, will show how several popular OOP design patterns are implemented (or not needed!) when you program in FP ways.

Chapter 12, Building Better Containers - Functional Data Types, will show some more high-level functional patterns, introducing types, containers, functors, monads, and several other more advanced FP concepts.

I tried to keep examples simple and down-to-earth, because I wanted to focus on functional aspects and not on the intricacies of this or that problem. Some programming texts are geared toward learning, say, a given framework, and then work on a given problem, seeing how to fully work it out with the chosen tools. (Also, in fact, at the very beginning of planning for this book, I entertained the idea of developing an application that would use all the FP things I had in mind, but there was no way to fit all of that within a single project. Exaggerating a bit, I felt like an MD trying to find a patient on whom to apply all of his medical knowledge and treatments!) So, I opted to show plenty of individual techniques, which can be used in multiple situations. Rather than building a house, I want to show you how to put bricks together, how to wire things up, and so on, so that you will be able to apply whatever you need, as it may fit.

What you need for this book

To understand the concepts and code in this book, you don't need much more than a JavaScript environment and a text editor. To be honest, I even developed some of the examples working fully online, with tools such as JSFiddle (at https://jsfiddle.net/) or the like, with absolutely nothing else.

However, you will need some experience with the latest version of JavaScript, because it includes several features that help writing more concise and compact code. We will frequently include pointers to online documentation, such as the documentation available on the MDN (Mozilla Development Network at https://developer.mozilla.org/) to help you get more in-depth knowledge.

Who this book is for

This book is geared toward programmers with a good working knowledge of JavaScript, working either on the client-side (browsers) or the server side (Node.JS), who are interested in applying techniques to be able to write better, testable, understandable, and maintainable code. Some background in Computer Science (including, for example, data structures) and good programming practices will also come in handy.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Just assign the names of the layers you want to activate to the VK_INSTANCE_LAYERS environment variable".

A block of code is set as follows:

{
 if( (result != VK_SUCCESS) || 
    (extensions_count == 0) ) { 
  std::cout << "Could not enumerate device extensions." << std::endl; 
  return false;
} 

Any command-line input or output is written as follows:

setx VK_INSTANCE_LAYERS VK_LAYER_LUNARG_api_dump;VK_LAYER_LUNARG_core_validation

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Select System info from the Administration panel."

Note

Warnings or important notes appear in a box like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-JavaScript-Functional-Programming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/ . Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.