A Brief Introduction to Javascript functional programming and a brief introduction to javascript

Source: Internet
Author: User

A Brief Introduction to Javascript functional programming and a brief introduction to javascript

For decades, functional programming has always been a hot topic in Computer Science. Due to the purity of mathematics and the mysterious nature, it has been buried in computer laboratories, it is only used by data scientists and people who wish to earn a doctorate. But now it is experiencing a renaissance, thanks to modern languages such as Python, Julia, Ruby, Clojure, and -- but not the last -- Javascript.

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

Javascript has been proven to be an important technology that has not been removed for a long time. This is mainly because of some of its extended frameworks and libraries that have the ability to be reborn, such as backbone. js, jQuery, Dojo, underscore. js, and so on. This is directly related to the real identity of Javascript functional programming languages. Understanding of Javascript functional programming is very important and will be useful to programmers of various levels for a long period of time.

Why? Functional programming is very powerful, robust, and elegant. It is very useful and efficient for large data structures. Javascript, as a client scripting language, functions-based DOM operations, organizing API responses, and other tasks in response to increasingly complex websites are very beneficial.

In this book, you will learn everything you need to know when using Javascript for functional programming: How to Use functional programming to build your Javascript web application, how to unlock the hidden power of Javascript, how to write more powerful code, and because the program is smaller, it makes the code easier to maintain, can be downloaded faster, and spend 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, how to mix functional programming and object-oriented programming in Javascript.

But before we start, we should first create an experiment.

Example

Perhaps a quick example is the best way to introduce 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 the sense of realism, we will be an e-commerce website, a company that buys coffee beans by mail. This website will sell several types of coffee with different quality and prices.

Imperative Method

First, we start to write programs. To make this example grounded, we need to create some objects to store data. If needed, we can take values from the database. But now we assume they are statically defined:

// Create some objects to store the data. var columbian = {partition name: 'columbian ', basePrice: 5}; var frenchRoast = {name: 'French roast', basePrice: 8}; var decaf = {name: 'decaf ', basePrice: 6}; // we will use the auxiliary function to calculate the price // print the price to a list of HTML functions printPrice (coffee, size) based on the size) {if (size = 'small') {var price = coffee. basePrice + 2;} else if (size = 'medium ') {var price = coffee. basePrice + 4;} else {var price = coffee. basePrice + 6;} // create the new html list item var node = document. createElement ("li"); var label = coffee. name + ''+ size; var textnode = document. createTextNode (label + 'price: $ '+ price); node. appendChild (textnode); document. getElementById ('products '). appendChild (node);} // now we only need to call the printPrice function printPrice (columbian, 'small') based on the combination of the price and size of coffee; 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 than the three changes? If there are 20 or even 50? What if there is more size? What if there are organic and inorganic points? This will quickly increase the amount of code!

In this way, we asked the machine to print each type of coffee and each size. This is the basic problem of adopting this imperative method.

Functional Programming

The imperative code step by step tells the computer what it needs to do to solve the problem. On the contrary, functional programming is pursuing the use of mathematical methods to describe the problem, and the rest are handed over to the computer for it.

In a more functional way, the same application can write as follows:

// Break down data and logic from the interface var printPrice = function (price, label) {var node = document. createElement ("li"); var textnode = document. createTextNode (label + 'price: $ '+ price); node. appendChild (textnode); document. getElementById ('products 2 '). appendChild (node);} // create a function object for each type of coffee var columbian = function () {this. name = 'columbian '; this. basePrice = 5 ;}; var frenchRoast = function () {this. name = 'French roast '; this. basePrice = 8 ;}; var decaf = function () {this. name = 'defaf'; this. basePrice = 6 ;}; // create an object var small = {getPrice: function () {return this for each size. basePrice + 2}, getLabel: function () {return this. name + 'small' }}; callback var medium = {getPrice: function () {return this. basePrice + 4}, getLabel: function () {return this. name + 'medium '}}; var large = {getPrice: function () {return this. basePrice + 6}, getLabel: function () {return this. name + 'large'}; // put all types and size of coffee in the array var coffeeTypes = [columbian, frenchRoast, decaf]; var coffeeSizes = [small, medium, large]; // create new objects composed of the above content and put them in a new array var coffees = coffeeTypes. reduce (function (previous, current) {var newCoffee = coffeeSizes. map (function (mixin) {// 'plusmix' is a functional minxin. For details, see chapter 7th var newCoffeeObj = plusMixin (current, mixin); return new newCoffeeObj ();}); return previous. concat (newCoffee) ;}, []; // now we have defined how to get prices for all types of coffee and the size combination, and now we can print them directly. forEach (function (coffee) {printPrice (coffee. getPrice (), coffee. getLabel ());});

The first thing to note is that the Code is more modular. The following code adds a new size or believes that a new coffee type is as simple as the following code:

var peruvian = function(){ this.name = 'peruvian'; this.basePrice = 11;};var extraLarge = { getPrice: function(){return this.basePrice + 10}, getLabel: function(){return this.name + ' extra large'}};coffeeTypes.push(Peruvian);coffeeSizes.push(extraLarge);

The arrays of coffee objects and the arrays of size objects are combined (mix, that is, their methods and member variables are combined to use a custom function called "plusMinxin" (see chapter 7 ). These coffee classes (columbian, frenchRoast, decaf) contain member variables, and these size objects (small, medium, large) contain methods for obtaining names and calculating prices. The "minxing" action takes effect through a map operation, that is, it executes a pure function for each member in the array and returns a new function, then these returned functions are put into a reduce function and operated. reduce is also a high-level function, which is similar to map, only reduce combines all the elements in the array into one thing. In the end, the new array contains a combination of all possible types and sizes. The array is traversed through the forEach method, and forEach is also a high-level function, it performs a callback function for each object in the array as a parameter. In this example, the callback function is an anonymous function. After obtaining these objects, it calls the printPrice function using the return values of the getPrice () and getLabel () Methods of the object as parameters.

In fact, we can make this example more functional: remove the coffees variable and concatenate functions for chained calls. This is also a small skill in functional programming.

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

In this way, the control flow is not sequential from start to end like the imperative code. In functional programming, map functions and other high-level functions Replace the for and while loops. Only a small amount of key code is executed in sequence. This makes it difficult for new contacts to read the code of this paradigm, but once you can appreciate it, you will find that it is not difficult at all, and such writing looks better.

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

Summary

First, the advantages of using the functional style have been clarified. Second, do not be afraid of functional programming. Indeed, it is often regarded as a pure logical form of programming languages, but we do not need to understand lambda calculus and 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 unknown built-in functions in Javascript, but we will pay attention to them.

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

Interested? Okay, let's get started!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.