Functional programming can be complicated and tedious, but in order to understand React and Redux, it’s hard to learn them well without a theoretical grounding in them.

Functional programming in JS is a more abstract concept, we may have heard of functional programming in the past, but there may be no system to understand them.

Functional programming, like object-oriented programming, is a set of programming paradigms, and you can design this process for your code according to the theory of functional programming. But functional programming is a little bit more demanding

Why learn functional programming

Functional programming is actually a very old concept relative to the history of computers, even the birth of the first computer. His calculus was not designed to be performed on a computer, but rather a formal system introduced in the 1930s to study function definitions, function applications and recursion.

In other words, functional programming is an old concept, so why should we learn it? In fact, functional programming has nothing to do with the front end, and it is not popular. It’s only because React and Redux made it popular. With higher-order functions, then higher-order functions are part of functional programming, which is why functional programming is popular.

Functional programming is mainly used to study the definition of functions, the application of functions and recursion and such a form of the system.

Note that functional programming is not about programming with functions, nor is it traditional procedural programming. The main idea is to compound complex functions into simple functions, and try to write the operations as a series of nested function calls. Notice the difference between functional programming and functional programming.

React’s higher-order component uses higher-order functions, which are a feature of functional programming, as we’ll learn later. React isn’t purely functional, although it uses some functional programming features.

The React ecosystem, such as Redux, uses some of the ideas of functional programming, so if we want to learn react and Redux better, we need to understand functional programming.

We all know that Vue3 is a big refactoring of VUe2, and it is becoming more and more functional. We can feel it when we use some VUe3 apis, and there is a lot of high order functions in the source code of VUe2. These popular frameworks tend to be functional programming, and we can even say that you don’t need to learn these frameworks. But you can’t help but know functional programming. Because those are the things that never change.

Many students before learning js may have known object-oriented language, such as Java, C# and C++ and so on, so in learning js, we also start from object-oriented learning, we will learn through learning prototype, prototype chain and simulation implementation inheritance mechanism to achieve some object-oriented features. We’re going to run into all kinds of problems with this, and if we’re going to use functional programming, we can get rid of this.

There are many benefits to functional programming, such as better tree-shaking at package time to filter out useless code.

Using functional programming can also facilitate testing and parallel processing, which are determined by the nature of functional programming.

There are also many libraries that help us with functional development, such as Lodash, underscore, and Ramda.

That’s why you learn functional programming.

The concept of functional programming

Functional programming is the mathematical branch of category wheel, a very complex mathematics, which holds that all the conceptual systems in the world can be abstracted into a category. Categories can be understood as the concept of groups, such as classmates in a class, can be understood as a category.

As long as there is some kind of relationship between each other concepts, things, objects and so on, all constitute categories, and anything can be defined by finding the relationship between them. For example, the people in the classroom may not know each other, but their relationship is classmates, so it is a category.

Relations are usually represented by arrows and are formally known as morphisms. The category wheel holds that all members of the same category are transformations of different states. One member can be morphed into another by morphism. In simple terms, each member is related to each other.

Functional Programming is called FP. Functional programming is a programming paradigm, we can think of him as a programming style, he and object oriented is parallel. Functional programming can be thought of as a mode of thinking, and we often hear about programming paradigms, as well as process-oriented and object-oriented programming.

The way of thinking about functional programming is abstracting things from the real world, and the relationships between things, into the program world.

Let’s first explain the nature of the program, is according to the input and then according to a certain operation to obtain the corresponding output, the program in the process of development will involve a lot of functions such as and output, functional programming is the abstraction of these operations.

If we have an input x that can be changed to y by a mapping, that mapping is a function in functional programming.

About functional programming we note that the function of functional programming, not in the program function or method, not to say that we in the process of programming using the function or method is functional programming, functional programming in the function, is actually is a function in mathematics and mathematics of the function is used to describe the mapping relation, For example, the function y is equal to sine of x, sine of x is the relationship between x and y. When x is equal to 1, y is determined, which means that when x is determined, y must be determined.

In functional programming we want the same input to always get the same output, which is a purely functional concept.

Functional programming is an abstraction of the process of computation. Let’s use a piece of code to experience functional programming.

For example, if we want to calculate the sum of two numbers and print the result, we usually define two variables num1 and num2, and then add the two variables, and finally print the result.

let num1 = 2;
let num2 = 3;
let num = num1 + num2;
console.log(sum)
Copy the code

So this is non-functional. If we were to use functional thinking, it would look something like this. First we want to abstract the add function, which takes two arguments, N1 and n2, and returns the result when it executes. In other words, functions in functional programming must have inputs and outputs.

function add (n1, n2) {
    return n1 + n2;
}
let sum = add(2.3);
console.log(sum);
Copy the code

As you can see, when we use functional programming will have some function, these functions are the follow-up can be reused, the countless times so functional programming one advantage is that can make the code reuse, and in the process of functional programming, abstracting function are fine-grained, the combination of these functions can again in the future to success can be more powerful function.

Functional programming is not to write a few functions is functional development, he is using mathematical thinking mode with the help of JS grammar to some code development, so functional he is a set of mathematical rules.

So what’s the difference between him and us writing code? When we use functional programming, we can’t use if, and there is no else, because there is no if and else in mathematics, as well as no variables and while. The whole thing is mathematical thinking, and then we use JS syntax to continue. You can use recursion because recursion is a mathematical concept.

The function is a first-class citizen

First-class citizenship means that functions are equal to other data types and can be assigned to other variables, either as parameters or as return values.

In functional programming, variables cannot be modified. All variables can be assigned only once, and all values are handled by passing arguments.

So in simple terms, functions are first-class citizens, can be assigned to variables, can be passed as arguments, can be returned.

In functional programming, you can only use expressions, not sentences, because there are no statements in mathematics.

Because variables can only be assigned once and cannot change their value, there are no side effects and no state can be changed.

Functions run with arguments that can’t be modified, so references are transparent.

Higher-order functions

The definition of A higher-order function is simple: if A function A can take another function B as A parameter, then it is called A higher-order function. Simply put, the argument list contains functions.

The idea of functional programming is to abstract operations into functions that can then be reused anywhere.

The abstraction helps us to mask the details of the implementation, and we only need to focus on our goals when we call these functions. The higher-order functions help us to abstract away these general problems.

Let’s take a simple example. Let’s say we want to iterate over every element in a print array if we use procedural programming code like this.

You can see that we’re going to write a loop to do something like this, and we’re going to care about the length of the array, and we’re going to control that the variable is not larger than the length of the array, and we’re going to care about a lot of things.

// let array = [1, 2, 3, 4]; for (let i = 0; i < array.length; i++) { console.log(array[i]); }Copy the code

When we use forEach function of Array, we do not need to pay attention to the specific implementation of the loop, that is, we do not need to pay attention to the details of the loop, nor do we need to control variables, we just need to know that forEach function can help us complete the loop.

// let array = [1, 2, 3, 4]; array.forEach(item => { console.log(item); })Copy the code

ForEach here is an abstraction of a general problem, and we can see that using forEach is much cleaner than using a for loop, so our use of functional programming has the added benefit of making our code much cleaner.

In JS, array forEach, map, filter, every, some,find, findIndex, reduce, sort, etc. are all higher-order functions because they can all take a function as an argument.

closure

A function is bound with references to its surrounding state, and a function inside that function can be called in another scope and members of that function scope can be accessed.

The concept of closure is not complicated, but its definition is a bit convoluted, let’s go through a code to understand the concept of closure.

First, we define a makeFn function. In this function, we define a variable MSG. When this function is called, MSG is released.

function makeFn () {
    let msg = 'Hello';
}

maknFn();
Copy the code

If we return a function in makeFn that also calls MSG, that’s a closure.

Instead, when we call makeFn, it will return a function. The received FN is actually the function that received the makeFn return, which means that the external FN has a reference to the MSG inside the function.

So when we call fn, we call the internal function, we’re going to access MSG, the variable in makeFn.

function makeFn () {
    let msg = 'Hello';
    return function() {
        console.log(msg); }}const fn = maknFn();

fn();
Copy the code

So a closure is a function that can be called inside a function (the function returned inside makeFn) in another scope (global in this case), and that can access members of that function’s (makeFn) scope.

As described above, the core function of the closure is to extend the scope of the internal member in our makeFn. Normally, the MSG will be freed after the makeFn completes execution, but it is not freed because the external element continues to reference the MSG.

Let’s look at the following example to see what closures can do.

We have a function called once, which controls fn to execute only once. How do we control fn to execute only once? Here we need a flag to indicate whether the function was executed or not. Here we define a local variable done, which is false by default, meaning fn was not executed.

Once returns a function inside the newly returned function. If done is false, mark it as true, and return the fn call.

When once is executed, we create a done and return a function. This is the function we assign to pay.

When we call pay, we access the external done, determine whether done is false, if done is true, and execute fn. The next time pay is called, it will not be executed again because done is already true.

function once(fn) { let done = false; return function() { if (! done) { done = true; return fn.apply(this, arguments); } } } let pay = once(function(money) { console.log(`${money}`); }); // It will only be executed once. pay(1); pay(2);Copy the code

The essence of closures is that functions are placed on an execution stack at execution time and removed from the stack when the function completes execution, but the scoped members on the heap cannot be freed because they are referenced externally, so the inner function can still access the members of the external function.