JavaScript functional Programming Simple introduction of _JAVASCRIPT skills

Source: Internet
Author: User

For decades, functional programming has been a favorite of computer science enthusiasts, because of the purity of mathematics and the nature of mysteries, which are buried in computer labs, only for data scientists and people who want to get a PhD. But now it is undergoing a revival, thanks to some 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 proven to be an important technology that has not disappeared for a long time. This is mainly due to the expansion of some of the frameworks and libraries to enable them to have the ability to regenerate, such as backbone.js,jquery,dojo,underscore.js and so on. This is directly related to the true identity of JavaScript functional programming languages. The understanding of JavaScript functional programming is important and is useful for a variety of levels of programmers over a long period of time.

Why, then? Functional programming is powerful, robust, and elegant. It is very useful and efficient for large data structures. JavaScript, as a client-side scripting language, can be very useful when dealing with increasingly complex web sites by manipulating the DOM, organizing API responses, and accomplishing some other tasks.

In this book, you'll learn everything you need to know about functional programming with javascript: 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, Makes the code easier to maintain, can be downloaded faster, and costs less. You'll also learn the core concepts of functional programming, how to apply them to JavaScript, and how to avoid problems when JavaScript is used as a functional language, and how to mix functional programming with object-oriented programming in JavaScript.

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

Example

Perhaps a quick example is the best way to introduce JavaScript functional programming. We'll do some tasks with JavaScript--one that uses traditional, native methods, and another that uses functional programming. Then we'll compare the two methods.

Application--An ecommerce website

To pursue a sense of reality, we'll do an ecommerce website, a mail order coffee company. This site will sell several types of coffee, have different quality, of course, there are different prices.

Imperative method

First, we start writing programs. To get this example grounded, we need to create some objects to hold the data. We can take a value from the database if we need to. 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 the auxiliary function to calculate the price///To print to a list of HTML according to size function Printprice (coffee, size) {if (size = = ' small ') {var = coffee.b
 Aseprice + 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 simply call the Printprice function Printprice (Columbian, ' small ') based on the combination of the various prices and size of the 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 now rather than just the three changes? What if there are 20 or even 50? What if there's more size? What if there are organic and inorganic points? This will quickly make the amount of code incredibly huge!

In this way, we have the machine to print each type of coffee and each size. This is the basic question of adopting this imperative approach.

Functional programming

The imperative code step-by-step tells the computer what needs to be done to solve the problem, instead, functional programming pursues a mathematical way of describing the problem, and the rest is given to the computer.

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

Decompose data and logical var Printprice = function (price, label) {var node = document.createelement ("Li") from the interface;
 var textnode = document.createTextNode (label+ ' Price: $ ' +price);
 Node.appendchild (Textnode);
document.getElementById (' Products 2 '). appendchild (node);
 //Create function object for each coffee var Columbian = functions () {this.name = ' Columbian ';
This.baseprice = 5;
};
 var frenchroast = function () {this.name = ' French roast ';
This.baseprice = 8;
};
 var decaf = function () {this.name = ' decaf ';
This.baseprice = 6;
};  Create object for each size by literal var small = {Getprice:function () {return this.baseprice + 2}, Getlabel:function () {return this.name
+ ' small '};
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 into the array var coffeetypes = [Columbian, frenchroast, decaf];
var coffeesizes = [small, medium, large]; Created by the topThe new objects of the surface content and put them into a new array var coffees = coffeetypes.reduce (function (Previous, current) {var newcoffee = Coffeesizes.map (fu
  Nction (mixin) {//' plusmix ' is a functional minxin, see 7th chapter var newcoffeeobj = Plusmixin (current, mixin);
 return new Newcoffeeobj ();
 });
Return Previous.concat (Newcoffee);
},[]); Now that we have defined how to get the price of all coffee types and size combinations, you can now print them directly coffees.foreach (function (coffee) {Printprice (Coffee.getprice ()),
Coffee.getlabel ());
 });

The first thing to be clear is that the code is more modular. Now add a size or a letter add a kind of coffee is as simple as the following code:

var Peruvian = function () {
 this.name = ' Peruvian ';
 This.baseprice = one;
};
var extralarge = {
 getprice:function () {return this.baseprice + ten},
 getlabel:function () {return this.name + ' ext RA large '}
};
Coffeetypes.push (Peruvian);
Coffeesizes.push (Extralarge);

The array of coffee objects is mixed with the array of size objects (mix), where their methods and member variables are grouped together-through a custom function called "Plusminxin" (see chap. Seventh). These types of 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 works through a map operation, where each member of the array executes a pure function and returns a new function, and the returned functions are manipulated in a reduce function, and reduce is also a higher order function. It's a bit like a map, but reduce combines all the elements in an array into one thing. Eventually, the new array contains a combination of all possible types and size, which is traversed by the Foreach method, and foreach is also a high-order function, which allows each object in the array to perform a callback function as a parameter. In this case, the callback function is an anonymous function that gets these objects and then invokes the Printprice function as an argument with the return value of the object's GetPrice () and Getlabel () two methods.

In fact, we can make this example more functional: Remove the coffees variable and string the function into a chained call, which is also a trick for functional programming.

Coffeetypes.reduce (function (Previous, current) {
 var newcoffee = Coffeesizes.map (function (mixin) {
  // Plusmixin ' function for functional mixins, the 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 in the same order as the imperative code. In functional programming, the map function and other High-order functions replace the for and while loops, and only a few key codes are executed sequentially. This makes it difficult for new contacts to read code such as this paradigm, but once you can appreciate it, you'll find it's not difficult at all, and it looks better.

This example is just beginning to show what functional programming in JavaScript can do. Through this book, you will see more examples of how powerful functional implementations can be.

Summarize

First, the advantages of using functional style are clear. Second, don't be afraid of functional programming. Indeed, it is often considered a purely logical form of programming language, but we do not need to understand that lambda calculus can also be applied in everyday tasks. In fact, by splitting our programs into smaller pieces, they become easier to understand, maintain, and be more reliable. The map and reduce functions are not known as built-in functions in JavaScript, but we will focus on them.

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

Are you interested in

? All right, here we go!

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.