Saturday, September 26, 2015

JavaScript through the Lenses of Functional Programming


One of the main challenges of large-scale application development, especially with JavaScript,  is keeping track of the state of the system at any point in time. We create lots of objects and pass them around to functions that are free to mutate them as they please and, most often, this makes it incredibly difficult to find and hunt down bugs.

For this reason, functional programming is on the rise, as evidenced by the recent adoption of hybrid OO/FP languages like Scala, F#, and JavaScript. It favors object immutability and elimination of side effects in your code, compared to procedural an object-oriented  programming that are based on mutations and side effects. However, immutability is hard to grok for most people. Can you imagine not being able to modify objects once they've been created?

Actually, yes. If you think of the way mathematical systems work, they can carry out the most complex algorithms without ever mutating values. In other words, if you pass x to a Math.square function, you would never expect the original variable x to change, would you? This same reasoning that we apply to numbers and maths, we can also apply it to programs, but for this we need to be a bit more disciplined. JavaScript's primitive types are already immutable, but this is not the case for user-defined types, like Person:

To this object, I can modify all of its data and behavior. To make this object immutable, JavaScript has an Object.freeze function, which augments its internal properties (Writable and Configurable) so that user code can't mess with the object's internal state. You can also encapsulate state under functions with Immediately Invoked Function Expressions (IIFE). Consider this simple type Money:

You can safely pass Money objects around without having to worry about its internal state being altered unexpectedly. Money has Value Object semantics that hide its internal state behind an object literal. These are some of hoops we can jump through to ensure your state is preserved as you expect it to be, which will make your code easier to trace and debug. 

However, the need to set or modify an object's properties after it's been created is very strong and occurs very frequently. What can we do? 

Immutability with getters and setters

Applying functional programming to your application is not restricting all mutation, but eliminating observable changes outside of your function scope; so that executing a function leaves the system in exactly the same state as it found it. Hence, functional programs are stateless. This statement has large implications, but in the context of object creation and modification, we need to ensure that setting an object's properties does not alter it. One way of doing it is by returning new copies of the object, as so:

But because you're responsible for keeping and sharing that state, this opens the door to writing very tedious code. Lenses automate this for us, so that you can modify the state of any object in an immutable fashion. Using JavaScript's functional library Ramda.js, I can write the following code:

At first glance, this might not seem like a big deal, but fact is that the call to R.set(), which is used to modify one of the object's properties, actually copies the state of the original object and returns a brand new object olivia with the modified property, keeping the original intact. Ramda does this by first performing a deep copy of the object using R.clone.

Composition with Lenses

Because Ramda's implementation of lens functions are curried, they can be easily used in compositions. As shown in the following example: 

Another main cause of bugs resulting from mutations is when a developers forgets about JavaScript's pass-by-reference. In this scheme, a function has complete control over the contents of an array argument:

This code causes a side effect on the provided array reference, since running the function effectively changes the content of the array declared outside of its scope. If you want to avoid this inadvertent side effect, you can use lenses: 

Wrap up

With lenses any operation on objects or arrays is immutable! This means you can be sure to pass any object wrapped in a lens into a function, and the original will never inadvertently change; thus, obeying the central principles of functional: total elimination of externally observable mutations and side effects!

For more detailed information on this topic, you can buy my book. 




Wednesday, July 1, 2015

Thorough Introduction to Functional JavaScript Programming


The rapid pace of web platforms, the evolution of browsers, and, most importantly, the demand of your end users has had a profound effect in the way we design web applications today. Users demand web applications feel more like a native desktop or mobile app so that they can interact with rich and responsive widgets, which forces JavaScript developers to think more broadly about the solution domain push for adequate programming paradigms.

With the advent of Single Page Architecture (SPA) applications, JavaScript developers began jumping into object-oriented design. Then, we realized embedding business logic into the client side is synonymous with very complex JavaScript applications, which can get messy and unwieldy very quickly if not done with proper design and techniques. As a result, you easily accumulate lots of entropy in your code, which in turn makes your application harder write, test, and maintain. Enter Functional Programming.

Functional programming is a software methodology that emphasizes the evaluation of functions to create code that is clean, modular, testable, and succinct. The goal is to abstract operations on the data with functions in order to avoid side effects and reduce mutation of state in your application. However, thinking functionally is radically different from thinking in object-oriented terms. So, how do you become functional? How do you begin to think functionally? Functional programming is actually very intuitive once you’ve grasped its essence. Unlearning old habits is actually the hardest part as it can be a huge paradigm shift for most people that come from an object-oriented background. Let’s convert a simple imperative “Hello World” program written in JavaScript, to functional:



These smaller functions combine to implement a program that is easier to reason about as a whole. Why does the functional solution look this way? I like to think of it as basically parameterizing your code so that you can easily change it in a non-invasive manner. This is due to functional programming’s inherent declarative mode of development. Imperative programming tells the computer, in great detail, how to perform a certain task.             

Declarative programming, on the other hand, separates program description from evaluation. It focuses on the use of expressions to describe what the logic of a program is without necessarily specifying its control flow or state changes.

This programming style is possible in JavaScript because of its support for first-class, high-order functions, which is a simple way of defining a function that accepts other functions as parameters or whose return value is a function.

While adopting a declarative style can be beneficial, sometimes you might find that functional code can be a bit harder write; this is a natural first impression before unlearning old methods and habits, as well as becoming comfortable with a higher level of abstraction or expressiveness. So why do it? The remarkable quality of declarative programs is that you wind up writing fewer lines of code and, simultaneously, get more work done. Consider this example: Write a short program to find the longest name in a collection of names. Your first approach is to write something like:

This imperative approach manually iterates over the array from start to finish and keeps track of the longest state name as I iterate. Functional programming takes a different approach by raising the level of abstraction in your code and yielding most of the work to the most robust and optimized artifact in your application, your language runtime, without having to loop at all using recursion. Let’s use it to refactor the same program:

Why go through so much effort to eradicate loops from our code? Loops imply code that is constantly changing or mutating in response to new iterations. Functional programs aim for statelessness and immutability as much as possible so that after a section of code runs no existing variables are changed. To achieve this, functional programming makes use of functions that avoid side effects and changes of state—also known as pure functions.

Pure Functions

Functional programming is based on the premise that you will build immutable programs solely based on pure functions. A pure function has the following qualities:

  • Depends only on the input provided and not on any hidden or external state that may change as a function’s evaluation proceeds or between function calls.
  • Does not inflict changes beyond its scope, like modifying a global object or a parameter reference.

Pure functions can be very hard to use in a world full of dynamic behavior and mutation. But, practical functional programming doesn’t restrict absolutely all state changes; it just provides a framework to help you manage and reduce, while allowing you separate the pure from the impure. It’s more critical to ensure no externally visible side effects occur—immutability from the application’s point of view.

Functions with side effects are, generally, bad design because they rely on data outside of the local scope of the function call, making it difficult to determine exactly what a function is supposed to do when they are run. Pure functions, on the other hand, have clear contracts as part of their signatures that describes clearly all of the function’s formal parameters, making them simpler to understand.
Consider the example of fetching for processing a payment for student given their SSN. Let’s model this with three side effect free functions.

    Composing all three functions makes up our processPayment function:

      Removing all practical side effects made our programs less brittle to changing external conditions. Making a function’s result consistent and predicable is a trait of pure functions called referential transparency.

      Referential transparency and substitutability

      Referential transparency is a more formal way of defining a pure function. Purity in this sense refers to the existence of a pure mapping between a function’s arguments and its return value. Hence, if a function consistently yields the same result on the same input, it is said to be referentially transparent. Here’s a quick example:

      This function always returns the same output when provided the same input. If this were not the case, it must mean that that the function’s return value is being influenced by some external factor. This quality of referential transparency is inherited from mathematical functions, which state that a function is a pure relation between inputs and outputs with the property that each input yields exactly one output.

      Let’s tackle a more complex example: adding a new grade to a list and compute its average. I will create two functions append and average:

      Putting it all together:

      This function yields a consistent result based only on the provided input and does not cause any side effects to the grades list after returning. Referential transparency is a very important quality of pure functions as it allows functional languages to optimize function calls, as you’ll see later in this post.

      Furthermore, a corollary of referential transparency is the principle of substitutability. Because the result of a referentially transparent functions consistently depends only on the values of the arguments provided to it, we say that a function’s return value can be directly replaced into an expression without changing its meaning. Math operators behave this way: adding 2 + 3 can be substituted with 5 into any equation and the result of the equation will forever remain the same. The following statements are all equivalent:

      (2 + 3) * 8 === (5) * 8 === 40

      The same expectations we hold for mathematical operators should also apply to pure functions as well. Now that you’ve caught a glimpse at the fundamental principles behind functional programming, perhaps its definition is more tractable now. So what is functional programming?

      Functional programming refers to the declarative evaluation of pure functions to create immutable programs by avoiding externally observable side effects.

      Becoming functional
      In order to become functional, you must learn to think functionally and have the proper tools to develop your functional awareness—the instinct of looking at problems as a combination of simple functions that together provide a whole solution. Functional programming is a software paradigm that, while based on very foundational concepts, will completely shift the way you think about a problem.

      Modularizing your code
      At a high level, functional programming is effectively the interplay between decomposition (breaking programs into small pieces) and composition (joining pieces to make programs). It is this duality that makes functional programs modular. As I mentioned previously, the unit of modularity, or “unit of work” is the function. Thinking functionally typically begins with decomposition by learning to break up a particular task into logical subtasks (functions):

      If need be, these can be decomposed further until arriving at simple, pure functions, each of which is an independent unit of work. Modularization in functional programming is closely related to the singularity principle, which states that functions should have a single purpose, which is exactly what I was able to achieve.

      Functional composition can be understood simply as taking the output of one function and plugging it into the next. The result of composing two functions together is another function that gets called with the actual arguments. Remember this from school?

      f . g = f(g(x))

      Its back! It reads: “f composed of g,” which supposes a type-safe relationship between what g returns and f receives. As seen in our previous example:

      Behind the scenes, the new roster array returned from append will be passed into calcAverage:
      Given a class roster array with students Haskell, Rosser, and Church with grades 97, 82, 100, respectively, if Alan Turing’s grade in the class was a 75, the new average will be:

      The concept of pure functions transitively applies to computeAverageGrade. Because it was built from the composition of two pure functions, it is itself pure. Understanding compose is crucial for learning how to implementing modularity and reusability in functional applications, as it leads to code where the meaning of the entire expression can be understood from the meaning of its individual pieces, a quality that becomes very hard to achieve in other paradigms. Also, it raises the level of abstraction so that you can clearly outline all of the steps performed in this code without being exposed to any of its underlying details. Because the compose function accepts other functions as arguments, it is known as a high-order function, a artifact in functional languages.
      Functional programming not only makes your code more modular, but in some cases it can also speed up the evaluation of your functions.

      Optimizing your function calls
      Functional programming will not speed up the evaluation times of your individual functions; rather, its strategy is based on avoiding duplicated function calls, which can potentially speed up your application overall. This technique is called memoization, which originates from the premise of functions being referentially transparent. Recall that referentially transparent functions always return the same value on same inputs. Through memoization the set of input parameters are encoded as a string or number and used as the cache key to a function’s result, internally persisted and looked up when the function is invoked again on the same input.

      Consider a function that computes a secure hash based on a user’s password. Depending on the type of algorithm used, this function can be very expensive to call. Generally, with secure encryption the more intense the algorithm the stronger the hash will be. Caching these results can be a tremendous improvement.

      Calling generateSecureHash again on this same input bypasses the computation and returns the memoized result. The effectiveness of memoization is directly proportional to the level modularity in your code. As you decompose big tasks into a greater number of smaller, single-purpose functions, memoization can be used more efficiently to achieve a higher level of fine-grained caching and optimization.

      Memoization is not a native JavaScript feature, but one way to install it is with API code by augmenting JavaScript’s extensible Function object. You can also have it as a standalone call.

      The beauty of this level of caching in functional languages like JavaScript is that it can be implemented without adding any boilerplate code of placing cache checks and inserts all over your functions.

      While on the topic of writing boilerplate code, consider null checks. Handling errors and null values generally leads to an explosion of if-else conditions in your code. This excessive use of branching logic creates code that is hard to maintain and test. As an example, suppose I need to extract the country name of a student’s school address. I think we’ve all seen similar convoluted code before:

      This anti-pattern of clean design is addressed with functional data types called monads used for null-safe operations as well as high-level abstractions that will allow you to write more robust, extensible code while handling errors effectively.

      Handling errors fluently using Monads
      Functional programming places a clear distinction between pure error handling and exception handling. Our goal is to implement pure error handling as much as possible, and allow exceptions to fire in truly exceptional conditions, just as the ones described earlier.

      I will use a purely functional data type called monads to order to treat potentially hazardous state as safe, encapsulated values that use high-order functions to abstract out and consolidate error-handling logic and defensive null-checks. By returning consistent, predictable values, referential transparency is preserved across function calls and error-bearing expressions can easily be combined in a very fluent manner.

      This is possible using the Maybe monad. Maybe is a data type that implements a very intuitive concept: a value is maybe there, maybe not. When wrapping a potentially unsafe value, Maybe either returns an object containing the value or an object containing “nothing.” Instead of returning unsafe null values that then you’ll have to check for, let’s show getCountry based on Maybe.

      Building extensible code with function chains
      Let’s tackle a different problem. Suppose you are tasked to write a program that would compute the average grade of students that have enrolled in more than one class. Approaching this problem from a functional mindset, you can identify three major steps:
      •  Selecting the proper set of students (whose enrollment is greater than one)
      • Extracting their grades
      • Calculating their average grade

        So far you’ve seen how functional programming can help us create modular, testable, and extensible applications. So, how does all this fare when running in a browser environment?

        Streamline client-side development
        Client side events come in many flavors: mouse clicks, text field changes, focus changes, etc. Consider the scenario of handling value changes on a text field and using the value entered to update a welcome banner. Naturally, as any JavaScript developer would do, I resort to jQuery:

        Arguably, this code is not very modular, as I am required to implement the logic of dealing with user input and updating the banner into a single function. Rather, the functional approach to handling events is to subscribe to asynchronous streams and, in a similar fashion to traversing an infinite collection of items, be able to compose a series of functions onto any event instance in a way that is separated from the actual browser event handling logic. In addition, I want to be able to port the concepts of referential transparency and immutability. Client side developing in functional is done reactive with Functional Reactive Programming (FRP). 

        FRP is the combination of reactive programming, or programming with data streams, with a strong focus on composition. For this I can leverage a functional library called Bacon.js that enhances JQuery’s API to define the asEventStream function that works with asynchronous data streams. For example, to subscribe to all keyup events on an input field, I can write the following code:

          Here’s where the functional programming comes in. The onKeyUp function is like an event bus that can treat events as if they were elements in a collection, which means I can easily map functions onto it to immutably manipulate the target objects. I will create a function to extract and run logic on the value in the event stream. Calling the toProperty method on the stream creates a value accessor on any keyup events that occur on that HTML field, which I can listen for and handle within the onValue method. 
          Now, I pose to you the same questions with which we started the section: Is this program: Modular? Testable? Extensible? Readable? Maintainable? Functional programming is a paradigm shift that can drastically transform the way in which you tackle solutions to any programming challenges. So, is functional programming a replacement for the more popular object-oriented design? Fortunately, applying functional programming to your code is not an “all or nothing” approach.

          In fact, lots of applications can benefit from it when used alongside an object-oriented architecture. Due to rigid control for immutability and shared state, functional programming is also known for making multi-threaded programming more straightforward. Because JavaScript is a single-threaded platform, this is not something we’ll need to worry about or cover in this post.

          In sum, client-side applications are becoming more and more complex every day and, if done poorly, can become a nightmare for companies to maintain. Some companies actually enforce the use of certain paradigms and coding styles, others don’t and welcome the investment of time to learn new and better ways to accomplish certain tasks. Hybrid languages like JavaScript become really useful in these cases as they allow developers to experiment with a mix of styles. Whichever your situation is, I truly believe getting familiar with functional programming, even if you had no immediate plans to move into it, can truly enhance your skills and your ability to tackle complex problems in a way not possible using conventional methods.

          If you liked this article and topic and want to read about it more in-depth, please order my book.


            Saturday, June 13, 2015

            Currying everything in JavaScript


            In this post I will discuss the benefits and practical uses of currying, a functional programming technique typically found in pure functional languages, but can be easily ported to JavaScript. I will also make use of a functional library called Ramda.js. Let's dive in.

            Curried functions

            Currying is a technique that converts a multivariable function into a step-wise sequence of unary functions. In other words, a curried function is one that evaluates only when all arguments have been provided; otherwise, it returns a new function that waits for the next.
            Here’s the formal definition of a curry of three parameters:
            curry(f) :: (a,b,c) -> f(a) -> f(b) -> f(c)
            This formal notation suggests curry is a mapping from functions to functions that deconstructs the input tuple (a,b,c) into separate single-argument invocations. In pure functional programming languages, like Haskell, currying is a built-in feature and automatically part of all function definitions.

            In order to understand currying in JavaScript, first you must understand the difference between a curried and a regular (non-curried) function evaluation. A non-curried function call, as all JavaScript functions are, is permitted to execute with missing arguments. In other words, if I define a function f(a,b,c) and call it with just a, the evaluation proceeds where b and c are set to undefined by the runtime engine.

            This is unfortunate and most likely the reason why curry (and later partial) is not a built-in features of the language. As you can imagine, not declaring any arguments at all and relying on the arguments object within functions exacerbates this issue. On the other hand, a curried function is one where all arguments have been explicitly defined so that, when called with a subset of the arguments, it returns a new function that waits for the rest of the parameters to be supplied before running. Visually this looks like this:

            JavaScript does not automatically curry functions, so we need to write some supporting code. Before we go into auto-currying, let’s start out with a simple scenario of manually currying two arguments:

            function curry2(fn) {
                 return function(firstArg) {              
                      return function(secondArg) {        
                          return fn(firstArg, secondArg); 

            As you can see in the code above, currying is just another case of a lexical scope (closure) where the returned functions are nothing more than trivial nested function wrappers to capture the arguments for later use. Let’s see curry2 in action; I can use currying to implement a function to check types. It is based on Ramda’s type check function

                // checkType :: Type => Type => Type | TypeError
                var checkType = curry2(function(typeDef, actualType) {
                    if(, actualType)) {
                        return actualType;
                    else {
                        throw new TypeError('Type mismatch. Expected [' + typeDef + '] but found [' + typeof actualType + ']');
                checkType(String)('Curry');  //-> String
                checkType(Number)(3);        //-> Number
                checkType(Date)(new Date()); //-> Date
                checkType(Object)({});       //-> Object
                checkType(String)(42);       //-> Throws TypeError

            For very simple tasks, curry2 is adequate, but as we start building more complex functionality we’ll certainly need to handle any number of arguments automatically. Normally, I would show you the function’s polyfill, but curry is a particularly long and convoluted function to explain with co-recursive calls, so I’ll spare you the headache and move into a more useful discussion.

            I will use Ramda’s version of R.curry to simulate automatic currying present in pure functional languages that works on any number of arguments. You can imagine automatic currying as simply artificially creating nested function scopes corresponding to the number of arguments a function declares. Visually, currying takes a function like doWork:
            // doWork :: (a,b,c,...) -> z
            var doWork = function (a, b, c, ... ) {

            Which operates on multiple arguments, and transform it (conceptually) into a function of the form:
            // doWork :: a -> b -> c ->... -> z
            var doWork = 
               function (a) {
               return function (b)  {
                       return function (c) {

            Curries have many useful applications. For our discussion we will focus on:
            1. Implementing reusable function templates
            2. Building step-wise functions
            3. Destructuring function arguments

            Implementing reusable function templates

            Curries are useful for creating function templates, which are reusable ways of evaluating a family of functions. Suppose I need to configure different families of logging functions to handle different conditions like: errors, warnings, etc. For this example, I will use the popular library Log4js. Most developers implement logging using default parameters:
            var logger = new Log4js.getLogger('StudentConsole');
  'Student added successfully!');

            But with Log4js you can do so much more. Suppose you need instead to display messages on the screen as a popup. You can configure an appender to do so:

            logger.addAppender(new Log4js.JSAlertAppender());

            And you can also change the layout so that it outputs messages in JSON format with a layout:

            appender.setLayout(new Log4js.JSONLayout());

            There are many settings you can configure as needed and copy and pasting this code into each file causes lots of duplicated code. Instead, let’s use currying to define a reusable function template, which will give you the utmost flexibility and reuse, as shown below:

              var logger = function(appender, layout, name, level, message) {
                    var appenders = {                                   
                        'alert': new Log4js.JSAlertAppender(),
                        'console': new Log4js.BrowserConsoleAppender()
                    var layouts = {        
                        'basic': new Log4js.BasicLayout(),
                        'json': new Log4js.JSONLayout(),
                        'xml' : new Log4js.XMLLayout()
                    var appender = appenders[appender];                 
                    var logger = new Log4js.getLogger(name);
                    logger.log(level, message, null);                   

            Now, by currying the logger function I can centrally manage and reuse appropriate loggers for each occasion:
                var log = R.curry(logger)('alert', 'json', 'FJS');
                log('ERROR', 'Error condition detected!!');

            If you are implementing many error-handling conditions into one function or file, you also have the flexibility of partially defining all but the last parameter, as such:

                var logError = R.curry(logger)('console', 'basic', 'FJS', 'ERROR');
                logError('Error code 404 detected!!');
                logError('Error code 402 detected!!');

            Behind the scenes, subsequent calls to curry this function are being called, yielding a unary function. The fact that you are able to create new functions from existing ones and pass any number of parameters leads to easily building functions in steps, as argument become defined.

            Building step-wise functions

            Due its ability to partially create function objects, curried functions come handy in cases where you don’t have the values of all function arguments at your disposal, so that you may build functions in steps as the data becomes available. For example, here’s a refactored payment function:
            var sendPayment = R.curry(
            function (service, taxRate, currency, amount) {
                    var total = amount + (taxRate * amount);
                    var Money = Tuple(Number, String);
                    return service.submit(new Money(total, currency));

            This code shows a function of four parameters that could be applied all at once or as needed. I also took the liberty of removing some side effects by explicitly declaring a payment service parameter used to handle payment submissions; hence, providing sendPayment with all necessary data it needs to execute. Listing 4.8 shows how I can progressively build a function as data becomes available:
                function makePayment(student, amount) {
                    var payment = sendPayment(new PaymentService());            
                    var taxRate = getCurrentTaxRateFor(student.getAddress());
                    payment = payment(taxRate);                            
                    if(student.getAddress().getCountry() === 'USA') {
                        var pay = payment('USD');              
                    else {
                        pay = payment('Other');                                 
                    return pay(amount);                                         
                var student = new Student('Alonzo', 'Church', 'Princeton')
                    .setAddress('New Jersey', 'USA');
                makePayment(student, 100); //-> (107, 'USD');

            If instead of building functions piece by piece you’d rather apply all arguments at once, currying can be used to lift functions so that arrays can be overlaid over its arguments, also called destructuring assignment.

            Destructuring function arguments

            Destructuring data refers to the ability of a language to bind the constituents of a complex type, say a tuple or an array, to variables. In ES6 we can do the following:
            [a, b, c] = [1, 2, 3]

            Where a, b, and c will be assigned 1, 2, and 3, respectively. We can use currying to simulate a similar effect when it comes to a function’s arguments. For instance, calculating a student’s final grade for the class, I can use the following function:

               var computeFinalGrade = R.curry(function (hw1, hw2, midterm, final) {
                    return Math.round((hw1 + hw2 + midterm + final) / 4);

            But, suppose the grades data is stored in an array, how would you pass the array to this function? Certainly, you can index each individual grade value and plug it into each parameter, but then you’ll have to cases where a grade value is invalid (for missed tests) and other mundane concerns. Fortunately, we can use curry to create a function, spread, which will allow you apply a list of arguments of length N to any curried function of N-arity. Here’s how it works:

            spread(computeFinalGrade)([98, 99, 100, 87]); //-> 96

            Here’s an implementation of the spread function:

               var spread = R.curryN(2, function(cf, args) {
                    var fn = this;
                    return args.reduce(function(cf, nextArg) {    
                        return, nextArg)               
                    }, cf);

            Furthermore, I’ve also taken the opportunity to show you a very useful variant of currying available in Ramda called, curryN, which returns a curried function with a specified arity—only the first N parameters will be curried. By default if no length is specified, the function’s length property is used.

            Aside from gaining reusability, as I mentioned before, the principal motivation behind currying is to allow us to convert multi-argument functions into unary functions so that they can be easily composed as components of a function pipeline. An alternative to currying is partial function application or function binding, moderately supported by the JavaScript language, to produce functions of smaller arity that also work well when plugged into function pipelines.