Exploring the fun of JavaScript functional programming _ javascript skills

Source: Internet
Author: User
This is the first article in the functional programming series. Here I will briefly introduce the programming paradigm, and then directly introduce the concept of using Javascript for functional programming. For more information, see Programming Paradigm

The programming paradigm is a framework composed of tools for thinking about problems and realizing the vision of problems. Many modern languages use clustering paradigms (or multiple paradigms): they support many different programming paradigms, such as object-oriented, metaprogramming, functional, process-oriented, and so on.

Functional Programming Paradigm

Functional programming is like a hydrogen-driven vehicle-the advanced futuristic technology, but it has not yet been widely promoted. Unlike imperative programming, it is composed of a series of statements used to update the global status during execution. Function programming converts computing into expressions for evaluation. These expressions are all composed of pure mathematical functions. These mathematical functions are class-notch (can be used and processed as common values) without side effects.

Function programming attaches great importance to the following values:
Function is a top priority

We should treat functions like other class objects in programming languages. In other words, you can store functions in variables, dynamically create functions, return functions, or pass functions to other functions. Let's look at an example...

A string can be saved as a variable, or a function, for example:

The Code is as follows:

Var sayHello = function () {return "Hello "};


A string can be saved as an object field, or a function, for example:

The Code is as follows:

Var person = {message: "Hello", sayHello: function () {return "Hello "}};


A string can be created only when it can be used. The function can also be used, for example:

The Code is as follows:

"Hello" + (function () {return "World"}) (); // => Hello World


If a string can be passed to the function as an input parameter, the function can also:

The Code is as follows:

Function hellloWorld (hello, world) {return hello + world ()}


A string can be returned as a function, or a function, for example:

return “Hello”;return function() { return “Hello”};

Advanced Cases

If a function uses another function as an input parameter or as a return value, it is called a higher-order function. We have seen an example of a High-Order Function just now. Next, let's take a look at the more complex situation.
Example 1:

[1, 2, 3]. forEach (alert); // The alert pop-up window shows "1" // The alert pop-up window shows "2" // The alert pop-up window shows "3"

Example 2:

function splat(fun) {  return function(array) {    return fun.apply(null, array);  };}var addArrayElements = splat(function(x, y) { return x + y });addArrayElements([1, 2]);//=> 3

Pure Functions

Pure functions do not have any other side effects. The so-called side effects refer to the changes made by the function to the external state of the function. For example:

  • Modify a variable
  • Modify Data Structure
  • Set a field for a variable
  • Throw an exception or pop-up error message

The simplest example is a mathematical function. The Math. sqrt (4) function always returns 2. It does not use any other cold information, such as status or set parameters. Mathematical functions never have any side effects.

Avoid modifying the status


Function programming supports pure functions. Such functions cannot change data, so most of them are used to create unchangeable data. In this way, you do not need to modify an existing data structure, and you can efficiently create a new one.
You may want to know if a pure function can generate an unchangeable return value by changing some local data? The answer is yes.
In JavaScript, very few data types are unchangeable by default. String is an example of a data type that cannot be changed:

  var s = "HelloWorld";  s.toUpperCase();  //=> "HELLOWORLD"  s;  //=> "HelloWorld"

Benefits of unchangeable status

• Avoid confusion and increase program accuracy: in a complex system, most bugs that are hard to understand are caused by modifications to the state of the external client code in the program. Bytes
• Establish fast and concise multi-threaded programming: if multiple threads can modify the same shared value, you have to get the value synchronously. This is a tedious and error-prone programming challenge for experts. Bytes
The software transaction memory and Actor Model provide direct processing and modification in thread-safe mode.

Use recursion instead of loop call

Recursion is the most famous functional programming technology. If you do not know it, you can understand it as a recursive function that can call your own function.
The most typical method to replace repeated loops is to use recursion, that is, after each function body operation is completed, the next item in the set is executed until the end condition is met. Recursion is also inherent in some algorithm implementations, such as traversing the tree structure (each tree is a small tree ).
Recursion is an important functional programming method in any language. Many function languages even require stricter requirements: only recursive traversal is supported, but explicit loop traversal is not supported. This requires the language to ensure that end calls are eliminated, which is not supported by ipvsrip.

The value of inertia is better than that of radical calculation.

Mathematics defines many infinite sets, such as natural numbers (all positive integers ). They are all symbolic representations. Any specific finite subset is evaluated as needed. We call it an inert evaluate (also called a non-strict evaluate, or call as needed, delayed execution ). Early Evaluation forces us to express all infinite data, which is obviously impossible.
Many languages are inert by default, and some also provide an inert data structure to express infinite sets, and perform precise calculations on themselves as needed.
Obviously, a line of code result = compute () expresses the value of the returned result of compute () to result. However, the value of result is meaningful only when it is used.
Visible Policy Selection will greatly improve the performance, especially when used in chain processing or array processing. These are the programming technologies that function programmers love.
This creates many possibilities, including concurrent execution, parallel technology, and synthesis.
However, there is a problem that commit Crip does not evaluate its inertia. Even so, the function library in Javascript can effectively simulate the value of inertia.
All the benefits of closures

All functional languages have closures, but this feature is often discussed mysteriously. A closure is a function that has an implicit binding to all variables referenced internally. In other words, the function closes a context for the variables it references. Closure in JavaScript is a function that can access the parent-level scope, even if the parent-level function has been called.

  function multiplier(factor) {   return function(number) {     return number * factor;   };  } var twiceOf = multiplier(2);  console.log(twiceOf(6));//=> 12

Declarative Programming is better than imperative Programming

Functional programming is declarative, just like mathematical operations. attributes and relationships are well defined. The runtime knows how to calculate the final result. The factorial function provides an example:
Factorial (n) = 1 if n = 1
N * factorial (n-1) if n> 1
This definition associates the value of factorial (n) with factorial (n-1), which is a recursive definition. In special cases, factorial (1) terminates recursion.

var imperativeFactorial = function(n) {  if(n == 1) {    return 1  } else {    product = 1;    for(i = 1; i <= n; i++) {       product *= i;    }    return product;   }}var declarativeFactorial = function(n) {    if(n == 1) {       return 1    } else {       return n * factorial(n - 1);   } }

From its implementation of factorial calculation, declarative factorial may look like a "imperative", but its structure is more like declarative.
The numerator factorial uses variable values, cyclic counters, and results to accumulate the calculated results. This method explicitly implements specific algorithms. Unlike declarative versions, this method has many Variable Steps, making it harder to understand and avoid bugs.

Functional JavaScript Library

There are many functional libraries: underscore. js, lodash, Fantasy Land, Functional. js, Bilby. js, fn. js, Wu. js, Lazy. js, Bacon. js, sloth. js, stream. js, Sugar, Folktale, RxJs, etc.
Function programmer Toolkit

Map (), filter (), and reduce () functions constitute the core of the function programmer toolkit. Pure high-order functions have become the main force of functional methods. In fact, they are typical examples of pure functions and higher-order functions. They use a function as the input and return outputs without any side effects.
These JavaScript Functions are crucial to every functional program. They can remove loops and statements to make the code more clean. These are the standards for implementing ECMAScript5.1 browsers. They only process arrays. Each call creates and returns a new array. The existing array is not modified. But wait a moment. This is not the case... They also use functions as input parameters, usually as Callback anonymous functions. They will traverse the entire array and apply the callback function to each item!
MyArray = [1, 2, 4];
NewArray = myArray. map (function (x) {return x * 2 });
Console. log (myArray); // Output: [1, 2, 4]
Console. log (newArray); // Output: [2, 4, 6, 8]
In addition to these three functions, many functions can be incorporated into almost every functional application:
ForEach (), concat (), reverse (), sort (), every () and some ().
JavaScript aggregation paradigm

JavaScript is not a strictly functional programming language, which also promotes the use of other paradigms:
Imperative programming: Detailed operation-based programming
Prototype-Based Object-Oriented Programming: Programming Based on prototype objects and their instances
Metaprogramming: the programming method for manipulating the JavsScript execution model. A good definition of metaprogramming is described as "programming occurs when you write code to do something, however, metaprogramming occurs when you write code and the interpretation of something changes.

The above is how to use JavaScript functional programming. I hope it will be helpful for your learning.

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.