OOP(object-oriented) and FP(functional) competition has never stopped, everyone is in the middle, there is no better or worse, only suitable or not.

FP seems to be gaining the upper hand these days in terms of being in tune with The Times, but it still feels like it takes a bit of time and experience to understand the ideas of functional programming and apply them proficiently to development, not as intuitive and easy to learn as OOP.

Also, different languages have different levels of OOP and FP support, and depending on their talents, languages are better suited to either approach. Whether OOP or FP is better is not the focus of today’s discussion.

Today we’ll take a look at whether javascript is better suited for FP or OOP, and how to apply FP to our projects in real development.

We won’t explain why FP is suitable for javascript. Let’s take a look at the problem of OOP in javascript applications.

With the rapid rise of javascript in the past two years, many backend developers have been transitioning to front-end developers.

It could be a developer who has transitioned from Java or NET. They are more or less OOP people who came into the world of javascript and brought OOP to javascript. Organizing code for development in OOP is typically done by implementing classes in a variety of ways, as well as various design patterns in OOP.

But at the core of javascript is the function, prototype chain is the basis of javascript OOP, if you do not understand or understand javascript prototype chain is still so thorough, check the information yourself, Learning javascript well requires a deep understanding of javascript’s prototype chain.

So javascript is fundamentally different from other OOP languages like Java in that javascript emulates classes and relationships between classes in prototype chains and other ways, and ultimately functions rather than classes. Java, on the other hand, is an object-based implementation of classes and class relationships.

Ok, so javascript is not suited to OOP.

Talking about functional programming in javascript, profit is what drives us to learn and work. What is the motivation for learning and applying functional programming? Is it cool? Not cool, of course, because functional programming can well meet the needs of modern Web front-end application development, easy to maintain and expand the program, reduce the cost of testing.

  • motivation
  • technology
  • Functional programming is applied in JS

When we learn a language, we need to learn its syntax and semantics. In javascript language, we have more syntax and semantics to be familiar with and memorize. For example, the difference between equal and true equal in javascript. Javascript variables are also scoped at the function rather than block level.

Now we have Jshint, which can give us a lot of friendly hints about some of the problems our code has.

Also, today’s frameworks, such as Angular or React, have their own syntax and semantics. In addition to javascript language semantics, we need to remember the syntax and semantics of these frameworks.

Having developed an application module in Typescript yourself, you have a background in c# development and want to switch to javascript. You can learn typescript because it’s javascript super, some of typescript is like c# or Java, some of the thinking also applies, and then it gets compiled into javascript. And make it easy to implement OOP into your typescript code.

class Greeter {
    greeting: string;
    constructor(message:string){
        this.greeting = message;
    }
    greet(){
        return "Hello," + this.greeting; }}var greeter = new Greeter("world")
Copy the code

But I mean why are we beating around the bush? Do we really need OOP in a language where javascript functions are first-class citizens? Of course there was no need. We consider the nature of the language, or whether functional programming is better for javascript.

Here are some of the most popular frameworks that implement functional programming.

  • Rxjs
  • React

The combination of simple data structures, higher-order functions, and generalization and reuse of javascript features lends itself well to functional programming.

  • Simple data structure
  • Higher-order functions
  • Generalization and reuse

In functional programming code is much more explicit, so let’s compare the following code styles: Imperative and functional. The latter, of course, is much clearer and makes it easier for us to read the code, which means that print is used on each element of the array. Imperative, which is more familiar, does take some time to read the code meaning.

function printArray(array){
    for(var i = 0; i < array.length; i++)
        print(array[i]);
}

//
forEach(["hello"."functional"."programming"],print);

Copy the code

So let’s take a look at the map function, the set that gets input is also the set that gets output, and the function that goes into the map as an argument is going to operate on each element of the set. The advantage is that the collection logic processing can be shared, providing reusability.

If you’ve studied Rxjs, you’ll be familiar with this diagram. A map takes a set and then operates on each element of the set, either by transforming another element, or by manipulating data structures, and all of the elements make up the set that we output. Think of it as a function where you put in a variable and you put out a variable, and their values correspond to each other.

To help you understand the reduce function, the elements in our collection are wrapped layer by layer on top of the previous value until the final result.

Let’s now take a look at the code, where we reference a lightweight javascript library underscore. Underscore is a favorite javascript library and highly recommended, even if you do not use functional programming, understanding and using underscore will make your work easier and easier. We prepared some vegetables, and then we cut the vegetables. The way below is a traditional Imperative way to write the way.

Let’s take this one step further and do it in a circular array by dicing and preparing the vegetables we’ve bought.

Now it’s time for our functional map, which takes two arguments. The first argument is our array, and the second argument is a function that operates on each element of the array. Each element is then printed as an array.

Ok, we have successfully taken the first step to transform our Imperative program into a functional one.

When the pre-cut dishes are ready, they can be put into the Pot and put into the Pot for boiling. Besides materials, we need two parameters: time and heat. Temperature and duration are used here to indicate temperature and time. SetStoveTemp sets the temperature

Before we start cooking, we need to mix up the ingredients, add in the end we need to put the chopped ingredients (array) into the pot,

So building on the last result, we can think of reduce, which takes three arguments, the first is the array of inputs, and the second is our function, which takes two arguments

Let’s take a simple example to illustrate how reduce is used. The first parameter of reduce is that we accept arrayOfNums. The second parameter is a function that takes two parameters. We sum up the memo by adding I to it, and the last parameter is the initial value of reduce, 0.

For cookGravy, we can set the temperature and time parameters and then call the cookInPot method to cook the gravy according to the setting.

Here we can use partial, we define partial functions, partial functions return a function, pass prepared arguments to the return function.

So let’s look at a simple partial function, sum is the sum that takes two parameters a and b, what if we add 2 to the input, we can change that

Partial functions aim to reduce the number of arguments in our function. For example, funa takes three arguments (a,b,c). We can use a function called funcurry that takes a,b, and c and then returns the function that takes C. So we can reduce the number of arguments to funa. CookStew nested cookInPot and cookStewCurry instead accepted a function that returned _. Partial.

We also create other partial functions.

In the cookInPot method, we make addIngredientsToPot and we make ingredients that we cook in a container. The two steps are in a certain order, in which the result of the first function is requested as an argument to the second function.

In the previous section we looked at partial functions and learned that compose uses a combination of functions in a way that first executes the right-most function and results in the left-most function

The component in underscore returns a composite function composed of functions, that is, a function executes and assigns the returned result as an argument to the next function for execution. And so on. In mathematics, the combination of functions f(), g(), and h() yields the compound function f(g(h())).