JavaScript-Functional programming

Source: Internet
Author: User
Tags mathematical functions

Programming paradigm

The programming paradigm is a framework that consists of thinking questions and the tools to realize the vision of the problem. Many modern languages are clustered paradigms (or multiple paradigms): They support many different programming paradigms, such as object-oriented, meta-programming, functional, process-oriented, and so on.

Functional Programming Paradigm

Functional programming is like a hydrogen-fueled car-the advanced futuristic, but it has not been widely popularized. In contrast to imperative programming, he consists of a series of statements used to update the global state at execution time. Functional programming evaluates the conversion as an expression. These expressions are all composed of pure mathematical functions, which are first-class (can be used and processed as general values) and have no side effects.

Functional programming attaches great importance to the following values:

function is a priority.

We should treat the function in the same way as other class objects in the programming language. In other words, you can store functions in variables, create functions dynamically, and return functions or pass functions to other functions. Let's look at an example ...

A string can be saved as a variable, and functions can, for example:

var SayHello = function () {return ' Hello '};

A string can be saved as an object field, and functions can, for example:

var person = {message: "Hello", Sayhello:function () {return "Hello"}};

A string can be created when it is used again, and functions can, for example:

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

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

function Hellloworld (Hello, world) {return Hello + world ()}

A string can be used as a function return value, and functions can, for example:

return "Hello"; return function () {return "Hello"};
Advanced case

If a function takes another function function as an input parameter or as a return value, it is called a higher order function. We have seen an example of a higher order function just now. Let's look at a more complicated situation.

Example 1:

[1, 2, 3].foreach (alert);//alert pop-up displays "1"//Alert pop-up window "2"//Alert Popup display "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

Most loved Pure Function

Pure functions do not have other side effects, so-called side-effects refer to the changes in the external state of the function generated by the function. Like what:

    • Modify a variable
    • modifying data structures
    • Set a field for a variable outside the environment
    • Throws an exception or pops up an error message

The simplest example is the mathematical function. The MATH.SQRT (4) function always returns 2. He will not use any other chilling information, such as status or setting parameters. Mathematical functions never cause any side effects.

Avoid modifying the state

Functional programming supports purely functional functions, which do not alter the data and are therefore mostly used to create immutable data. This way, you don't have to modify an existing data structure, and you can create a new one efficiently.

You might want to know if a purely function is allowed to produce an immutable return value by altering some local data. The answer is yes.
Very few data types in JavaScript are immutable by default. String is an example of a data type that cannot be changed:

var s = "HelloWorld";    S.touppercase ();    = "HELLOWORLD" s; = "HelloWorld"
The benefits of a non-changing state

• Avoid confusion and increase program accuracy: In complex systems, most incomprehensible bugs are caused by the State being modified by external client code in the program.
• Establish "Fast and concise" multithreaded programming: If multiple threads can modify the same shared value, you have to synchronize the fetch value. This is a tedious and error-prone programming challenge for experts.
The software transaction memory and Actor model provide direct thread-safe processing of modifications.

Using recursion instead of looping calls

Recursion is the most well-known functional programming technique. If you don't know it yet, you can understand that a recursive function is a function that can invoke itself.

The most classic way to replace repeated loops is to use recursion, that is, each time the function is completed, the next item in the collection is executed until the end condition is met. Recursive restitution is inherently compatible with certain algorithmic implementations, such as traversing a tree structure (each tree is a small one).

Recursion is an important functional programming method in any language. Many functional languages are even more demanding: only recursive traversal is supported, and explicit looping traversal is not supported. This requires that the language must be guaranteed to eliminate the end call, which is not supported by Javassrip.

Lazy evaluation is better than radical calculation

Mathematics defines a number of infinite sets, such as the natural number (all positive integers). They are all symbolic representations. Any given limited subset is evaluated when needed. We call it lazy evaluation (also called non-rigorous evaluation, or on-demand invocation, deferred execution). Early evaluation will force us to show all the infinite data, which is obviously impossible.

Many languages are lazy by default, and some provide lazy data structures to express infinite collections, and to accurately calculate them when needed.

It is obvious that a line of code result = COMPUTE () is the expression that assigns the return result of compute () to result. But how much of the value of result is only meaningful when it is used.

The choice of visible policies can greatly improve performance, especially when used in chain processing or array processing. These are the programming techniques that functional programmers love.

This opens up a number of possibilities, including concurrent execution, parallel technology, and compositing.

However, there is a problem that Javascrip does not evaluate itself lazily. That said, the library of functions in Javascript can effectively simulate lazy evaluation.

the full benefits of closures

All functional languages have closures, but the language features are often discussed in mysterious detail. A closure is a function that has an implicit binding to all variables that are referenced internally. In other words, the function encloses a context for the variable it references. Closures in JavaScript are functions that can access the parent scope, even if the parent function has already been called.

Function multiplier (factor) {return function (number) {return number * factor;   };    } var twiceof = multiplier (2); Console.log (twiceof (6));//=> 12
Declarative better than imperative programming

Functional programming is declarative, like mathematical operations, where attributes and relationships are defined. The runtime knows how to calculate the final result. The definition of the factorial function provides an example:

Factorial (n) = 1 if n = 1

n * Factorial (n-1) if n > 1

The definition associates the value of factorial (n) to factorial (n-1), which is a recursive definition. In special cases the factorial (1) terminates the 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 {            &nbsP; return n * factorial (n - 1);      }   }

From its implementation of factorial calculations, the declarative factorial may look like "imperative", but its structure is more declarative.

Imperative factorial uses variable values, loop counters, and results to accumulate the computed results. This method explicitly implements a specific algorithm. Unlike declarative versions, this approach has many variable steps, making it more difficult to understand and more difficult to 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 and so on.

Functional Programmer Toolkit

The map (), filter (), and reduce () functions form the core of the functional Programmer's toolkit. The pure higher order function becomes the main force of the functional method. In fact, they are typical of pure functions and higher-order functions that should be emulated. They use a function as input and return output with no side effects.

JavaScript-Functional programming

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.