JavaScript's Functional Programming Basics Guide _ Basics

Source: Internet
Author: User
Tags abs closure function definition

Introduction

JavaScript is a powerful, but misunderstood programming language. Some people like to say that it is an object-oriented programming language, or it is a functional programming language. Others like to say that it is not an object-oriented programming language, or that it is not a functional programming language. Others argue that it has both object-oriented and functional languages, or that it is neither object-oriented nor functional, so let's put aside those arguments first.

Let's assume that we share a mission to write programs as much as possible using the principles of functional programming within the confines of the JavaScript language.

First, we need to clean up the misconceptions about functional programming in our minds.

Functional programming with a (heavy) misunderstanding in the JS world

There are obviously a number of developers who use JavaScript in a functional paradigm all the way. I would say there are a lot more JavaScript developers who don't really understand the true meaning of the paradox.

I'm sure that this is because many of the Web development languages used for the server are derived from the C language, and C is clearly not a functional programming language.

There seems to be two levels of confusion, the first level of chaos we use the following examples that are often used in jquery:

$ (". Signup"). Click (Function (event) {
  $ ("#signupModal"). Show ();
  Event.preventdefault ();
});

Hey, look closely. I pass an anonymous function as an argument, which is known as the "CallBack" (callback) function in the JavaScript world.

Does anyone really think this is functional programming? Not at all!

This example shows a key feature of a functional language: a function as a parameter. On the other hand, the example of this 3-line code violates almost all other functional programming paradigms.

The second level of confusion is a bit tricky. Read here, some of the pursuit of the trend of JS developers secretly think.

All right, nonsense! But I already know all about functional programming knowledge and skills. I use underscore.js on all my projects.

Underscore.js is a popular JavaScript library that is used everywhere. For example, I have a set of words, I need to get a set, each element in a collection is the first two letters of each word. Using Underscore.js to achieve this is fairly straightforward:

var firsttwoletters = function (words) {return
  _.map (words,function (word) {return
    _.first (word,2);
  });

See! Look at JavaScript witchcraft. I'm using these advanced functional application functions, like _.map and _.first. What else do you have to say, Leland (Leland)?

Although underscore and functions like _.map are very valuable functional paradigms, the method used to organize the code in this example looks like ... Long and too difficult for me to understand. Do we really need to do this?

If you start thinking with a little more "functional" thinking, maybe we can change the example above:

// ... A little magic
var firsttwoletters = map ((2));

Think about it in 1 lines of code that contains the same information as the above 5 lines of code. Words and Word are just parameters/placeholders. The core of this method is to combine the map function in a more obvious way, the function of the A, and the 2.

is JavaScript a functional programming language?

There is no magic formula to determine whether a language is a "functional" language. Some languages are clearly functional, as other languages are clearly not functional, but there is a large number of languages that are ambiguous in the centre.

So here are some common, important functional language "ingredients" (JavaScript can be implemented in bold)

    • function is "First Class citizen"
    • function can return functions
    • Lexical support for closures
    • function to "pure"
    • Reliable recursion
    • No mutation status.

This is by no means a list of rows, but we'll at least discuss one of the most important three features in JavaScript, which support the way we can write programs in a functional fashion.

Let's take a detailed look at the following:

function is "First Class citizen"

This may be the most obvious of all ingredients, and may be the most common in many modern programming languages.

The JavaScript local variables are defined by the VAR keyword.

var foo = "Bar";

It is very easy to define a function in JavaScript in terms of local variables.

var add = function (A, b) {return a + B;};
var even = function (a) {return a% 2 = 0;};

These are facts, variables: variable add and variable even are assigned by way of a reference relationship to a function definition that can be changed at any time if needed.

Capture the old version of the function
var old_even = even; 
 
Assign variable ' even ' to a new, different function
even = function (a) {return a & 1 = 0;};

Of course, there is nothing special about it. But being a "first class citizen" is an important feature that allows us to pass functions as arguments to another function. As an example:

var binarycall = function (f, a, B) {return F (A, b);};

This is a function, he accepts a two-dollar function f, and two parameter a,b, and then calls this two-function f, which is the two-dollar function f with a, b as input parameters.

Add (1,2) = = Binarycall (add, 1, 2); 
True

This may seem a bit clumsy, but when the next functional programming "ingredient" is taken into consideration, the bull's fork is obvious ...

Functions can return functions ("Higher order functions" in other words)

Things are getting really cool. Although it's easier to start with. The function eventually takes the new function as the return value. As an example:

var applyfirst = function (f, a) {return 
 function (b) {return F (A, b);};
};

This function (Applyfirst) takes a two-dollar function as one of the arguments, and the first argument (the two-dollar function) can be considered as a "partial operation" of the Applyfirst function, and then a unary (one-parameter) function is returned. The two function f (A, b) of the first parameter (f) of the external function is returned when the unary function is invoked. Returns a two-dollar function of two parameters.

Let's talk a few more functions, such as the mult (multiplication) function:

var mult = function (A, b) {return a * b;};

Following the logic of the mult (multiplication) function, we can write a new function double (the exponentiation):

var double = Applyfirst (mult, 2);
 
Double (a);
double (7.5); 
15

This is a partial function that is often used in FP. (FP full name is functional programming function programming)

We can, of course, define functions like Applyfirst:

var curry2 = function (f) {return
 function (a) {return
  function (b) {return
   F (A, b);
  };
 };
};

Now, I want a double (exponentiation) function, and we do it in a different way:

var double = Curry2 (mult) (2);

This approach is called "function of Gerty". Somewhat similar to partial application (partial function application), but a bit more powerful.

To be precise, functional programming is powerful, mostly because of this. Simple and easy to understand functions become the basic building blocks of our software. Functions can be combined and mixed together to express more complex behaviors when they have a high level of organizational capacity and less reusable logic.

Higher-order functions can get more fun. Let's take a look at two examples:

1. Flip two function parameter order

Flip the argument order of a function
var flip = function (f) {return
 function (A, b) {return F (b, a);};
};
 
Divide (5) = = Flip (divide) (5); 
True

2. Create a function that combines other functions

Return a function that ' s the composition of two functions
... Compose (f, G) (x)-> F (g (x))
var compose = function (f1, F2) {return
 function (x) {return
  F1 (F2 (x));
 };
};
 
ABS (x) = Sqrt (x^2)
var abs = Compose (Sqrt, square);
 
ABS ( -2); 
2

This example creates a useful function that we can use to record every function call.

var logwrapper = function (f) {return
 function (a) {
  console.log (' calling ' + F.name + ' "with argument ' + a); Return
  F (a);
 };

var app_init = function (config) {/ 
* ... */
 };
 
if (Debug) {
 
//log the Init function if in DEBUG mode
 app_init = Logwrapper (App_init);
}
 
Logs to the console if in debug mode
app_init ({/
 
* ... */
});

Lexical closures + scopes

I am convinced that understanding how to effectively use closures and scopes is key to becoming a great JavaScript developer.
So... What is a closure?

Simply put, closures are internal functions that always have access to the scope of the parent function, even if the parent function has returned. < 4>
You may need an example.

var createcounter = function () {
 var count = 0;
 return function () {return
  ++count;
 
};}; var counter1 = Createcounter ();
 
Counter1 (); 
1
counter1 (); 
2
 
var counter2 = Createcounter ();
 
Counter2 (); 
1
counter1 (); 
3

Once the Createcounter function is invoked, the variable count is assigned a new memory area. Then, return a function that holds a reference to the variable count and performs count plus 1 each time it is invoked.

Note that from the scope of the Createcounter function, we are not able to manipulate the value of count directly. The Counter1 and COUNTER2 functions can manipulate copies of their own count variables, but only in this non

It is supported to manipulate count (since 1) in a way that is often specific.

In JavaScript, scoping bounds are checked only when the function is declared. functions individually, and they have their respective scope tables, only one function at a A. (Note: This is no longer the case in ECMAScript 6 because of Let's introduction)

A few further examples to illustrate this argument:

Global scope
var scope = "global";
 
var foo = function () {
 
//inner scope 1
 var scope = "inner";
 var myscope = function () {
  
//inner scope 2 return
  scope;
 };
 return myscope;
};
 
Console.log (foo () ()); 
"Inner"
 
console.log (scope); 
"Global"

There are some important things to consider about scopes. For example, we need to create a function that accepts a number (0-9) and returns the corresponding English name for that number.

The simple point is that someone would write:

Global scope ...
var names = [' zero ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' nine '];
var digit_name1 = function (n) {return
 names[n];

However, the disadvantage is that names is defined in the global scope and may be accidentally modified, which may result in incorrect results returned by the DIGIT_NAME1 function.
So, write this:

var digit_name2 = function (n) {
 var names = [' zero ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' Nine '];
 return names[n];

This time, the names array is defined as a function digit_name2 local variable. This function is far from accidental risk but has a performance penalty, which is redefined and allocated space for names arrays each time the digit_name2 is invoked. In other words, if names is a very large array, or maybe the digit_name2 function is called multiple times in a loop, the performance impact will be obvious.

"An inner function enjoys which even after the parent functions have returned."
var Digit_name3 = (function () {
 var names = [' zero ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' Nine '];
 return function (n) {return
  names[n];
 };
}) ();

That's when we face a third choice. Here we implement the function expression called immediately, just instantiate the names variable once, and then return the Digit_name3 function, in Iife (immediately-invoked-function-expression execute expression immediately) The closure function holds a reference to the names variable.
This scheme combines the advantages of the first two and avoids the disadvantages. Get! This is a common pattern used to create a "private" state that cannot be modified by the external environment.


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.