SoFunction
Updated on 2025-03-03

A brief introduction to Javascript functional programming

Functional programming has been a favorite of computer science fanatics for decades, and due to the purity and mysterious nature of mathematics, it is buried in computer laboratories, used only by data scientists and those who are promising to earn a Ph.D. But now, it's undergoing a revival, thanks to modern languages ​​like Python, Julia, Ruby, Clojure and — but not the last one — Javascript.

You mean Javascript? This WEB scripting language? That's right!

Javascript has proven to be an important technology that has not disappeared for a long time. This is mainly due to some frameworks and libraries it extends to make it reborn, such as jQuery, Dojo, etc. This is directly related to the true identity of the Javascript functional programming language. An understanding of Javascript functional programming is important and will be useful for programmers of all levels for quite some time.

Why? Functional programming is very powerful, robust and elegant. It is very useful and efficient for large data structures. As a client scripting language, Javascript functionally operates DOM, organizes API responses, and completes some other tasks when dealing with increasingly complex websites.

In this book, you will learn everything you need to know when using Javascript for functional programming: how to build your Javascript web application with functional programming, how to unlock the hidden power of Javascript, how to write more powerful code, and because the program is smaller, the code is easier to maintain, can be downloaded faster, and costs less. You will also learn the core concepts of functional programming, how to apply them to Javascript, and how to avoid some problems when using Javascript as a functional language, and how to mix functional programming and object-oriented programming in Javascript.

But before we start, let's do an experiment.

example

Perhaps a quick example is to introduce the best way to Javascript functional programming. We will use Javascript to complete some tasks - one using traditional, native methods and the other using functional programming. Then we will compare the two methods.

Application—An e-commerce website

In order to pursue a sense of reality, we will build an e-commerce website, a company that mail-order coffee beans. This website sells several types of coffee, with different quality and of course different prices.

Imperative method

First, we start writing the program. To make this example down-to-earth, we need to create some objects to save the data. If necessary, we can get the value from the database. But now we assume that they are statically defined:

 // create some objects to store the data.
var columbian = {
 name: 'columbian',
 basePrice: 5
};
var frenchRoast = {
 name: 'french roast',
 basePrice: 8
};
var decaf = {
 name: 'decaf',
 basePrice: 6
};
// We will use helper functions to calculate the price// Print to a HTML list according to sizefunction printPrice(coffee, size) {
 if (size == 'small') {
  var price =  + 2;
 }
 else if (size == 'medium') {
  var price =  + 4;
 }
 else {
  var price =  + 6;
 }
 // create the new html list item
 var node = ("li");
 var label =  + ' ' + size;
 var textnode = (label+' price: $'+price);
 (textnode);
 ('products').appendChild(node);
}
// Now we just need to call the printPrice function based on the various price and size of the coffeeprintPrice(columbian, 'small');
printPrice(columbian, 'medium');
printPrice(columbian, 'large');
printPrice(frenchRoast, 'small');
printPrice(frenchRoast, 'medium');
printPrice(frenchRoast, 'large');
printPrice(decaf, 'small');
printPrice(decaf, 'medium');
printPrice(decaf, 'large');

As you can see, this code is very basic. What if there are more types of coffee now than just these three? What if there were 20, or even 50? What if there are more sizes? What if there is a difference between organic and inorganic? This will quickly make the code volume huge!

With this approach, we let the machine print every coffee type and every size. This is the basic problem with adopting this imperative approach.

Functional programming

Imperative code tells the computer step by step what needs to be done to solve the problem. On the contrary, functional programming pursues mathematical description of the problem, and the rest is left to the computer.

In a more functional way, the same application can be written like this:

// Decompose data and logic from interfacevar printPrice = function(price, label) {
 var node = ("li");
 var textnode = (label+' price: $'+price);
 (textnode);
 ('products 2').appendChild(node);
}
// Create function objects for each coffeevar columbian = function(){
  = 'columbian';
  = 5;
};
var frenchRoast = function(){
  = 'french roast';
  = 8;
};
var decaf = function(){
  = 'decaf';
  = 6;
};
// Create objects through literals for each sizevar small = {
 getPrice: function(){return  + 2},
 getLabel: function(){return  + ' small'}
};
var medium = {
 getPrice: function(){return  + 4},
 getLabel: function(){return  + ' medium'}
};
var large = {
 getPrice: function(){return  + 6},
 getLabel: function(){return  + ' large'}
};
// Put all the types and sizes of coffee into the arrayvar coffeeTypes = [columbian, frenchRoast, decaf];
var coffeeSizes = [small, medium, large];
// Create new objects composed of the above content and put them in a new arrayvar coffees = (function(previous, current) {
 var newCoffee = (function(mixin) {
  // `plusmix` is a functional minxin, see Chapter 7  var newCoffeeObj = plusMixin(current, mixin);
  return new newCoffeeObj();
 });
 return (newCoffee);
},[]);
// Now that we have defined how to get the price of all coffee types and size combinations, we can now print them directly(function(coffee){
 printPrice((),());
});

First of all, it needs to be clear that this code is more modular. Now add a new size or new coffee type as simple as the following code:

var peruvian = function(){
  = 'peruvian';
  = 11;
};
var extraLarge = {
 getPrice: function(){return  + 10},
 getLabel: function(){return  + ' extra large'}
};
(Peruvian);
(extraLarge);

The array of coffee objects and the array of size objects are mixed together, that is, their methods and member variables are combined together - through a custom function called "plusMinxin" (see Chapter 7 for details). These coffee-type classes (columbian, FrenchRoast, decaf) contain member variables, and these size objects (small, medium, large) contain methods to get names and calculate prices. The "minxing" action works through a map operation, that is, perform a pure function on each member of the array and return a new function. Then the returned functions are placed in a reduce function and operated. Reduce is also a higher-order function, which is somewhat similar to map, but reduce processes all the elements in the array and combines them into one thing. Finally, the new array contains all possible combinations of types and sizes. This array is traversed by the forEach method. ForEach is also a higher-order function. It will allow each object in the array to execute the callback function as a parameter. In this example, this callback function is an anonymous function. After obtaining these objects, the printPrice function is called as parameters using the return values ​​of the two methods of the object, getPrice() and getLabel().

In fact, we can make this example more functional: remove the coffees variable and string the functions together to call them in chains. This is also a small trick in functional programming.

(function(previous, current) {
 var newCoffee = (function(mixin) {
  // `plusMixin` function for functional mixins, see Ch.7
  var newCoffeeObj = plusMixin(current, mixin);
  return new newCoffeeObj();
 });
 return (newCoffee);
},[]).forEach(function(coffee) {
 printPrice((),());
});

In this way, the control flow does not proceed from beginning to end in the order like the imperative code. In functional programming, map functions and other higher-order functions replace for and while loops, and only a small amount of critical code is executed sequentially. This makes it a bit difficult for newcomers to read code in such a paradigm, but once you can appreciate it, you will find that it is nothing difficult at all, and writing this way looks better.

This example is just the beginning of revealing what functional programming can do in Javascript. Through this book, you will see more powerful examples of functional implementations.

Summarize

First of all, the advantages of adopting a functional style have been clarified. Secondly, don't be afraid of functional programming. Indeed, it is often considered a purely logical form of programming languages, but we do not need to understand that lambda calculus can also apply it in daily tasks. In fact, by splitting our programs into small fragments, they become easier to understand, maintain, and more reliable. Map and reduce functions are not well-known built-in functions in Javascript, but we are going to pay attention to them.

Javascript is a scripting language that is interactive, easy to use, and does not require compilation. We don't even need to download any development software, your favorite browser can serve as an interpreter for the development environment.

Interested? OK, let's start!