Why does JavaScript use functional programming?

青灯夜游
Release: 2022-09-30 15:10:14
Original
1524 people have browsed it

Reasons: 1. The syntax of js is borrowed from the functional programming language Scheme. 2. As far as the browser is concerned, with the development of various single-page frameworks, the processing capabilities of the client continue to improve, and more and more business logic is placed on the client, resulting in more and more states to be maintained by the client. ;The ensuing problem is that if you are not careful, you will use a large number of functions that depend on external variables. These functions continue to increase with the business logic, resulting in a sharp increase in logical branches, making the status difficult to track, poor code readability, and difficult to maintain. , and functional programming has a good solution.

Why does JavaScript use functional programming?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. What is functional programming?

Functional programming (FP), referred to as FP, is not a library or framework, as opposed to procedural programming (Procedural programming), but a programming paradigm. FP avoids or minimizes the side effects of function calls on external states and systems by declaring pure function abstract data processing.

The so-called side effects generally include changing the system state outside the function, throwing exceptions, processing user operations, modifying input parameters, database query operations, DOM operations, etc., which may cause system errors.

2. Why use functional programming ideas in JavaScript

##2.1 From the perspective of language characteristics

JavaScript's initial syntax was borrowed from the functional programming language Scheme. With the advancement of language standards, the functionality of the language itself is constantly enriched. Functions such as closures, arrow functions, higher-order functions, array iteration, etc. all make it easy to implement FP in JavaScript. Here are a few features:

2.1.1. Lambda expression

The lambda expression is actually an anonymous function that uses arrows to clearly represent the mapping relationship between input and output. JavaScript uses arrow functions to implement this.

const multiply = x => x * x
multiply(6) // 36
Copy after login

2.1.2 Higher-order functions

Higher-order functions can accept one or more functions as input parameters and output a function.

Write two simple examples

const add = x => y => x + y
const add10 = add(10)
add10(5) // 15
const compose = (...fns) => x =>  fns.reduce((acc, fn) => fn(acc), x)
const a = x => x + 1
const b = x => x + 2
const composedFn = compose(a, b)
composedFn(1) // 1 + 1 + 2 = 4
Copy after login

2.1.3 filter map forEach reduce iteration

The filter map forEach reduce under Array.prototype are all high-order functions because of the input parameters is a function.

const flatten = (arr = []) => arr.reduce(
  (acc, val)=> accconcat(Array.isArray(val) ? flatten(val) : val),
  []
)
let arr = [1,[ 4, 5 ], 2, 3];
flatten(arr)  // [1, 4, 5, 2, 3]
Copy after login

2.2 From the perspective of actual needs

As far as the browser is concerned, with the development of various single-page frameworks, the processing capabilities of the client continue to improve. More and more business logic is being placed on the client, resulting in more and more states to be maintained by the client. The problem that arises is that if we are not careful, we will use a large number of functions that depend on external variables. These functions continue to increase with the business logic, resulting in a sharp increase in logical branches, making the status difficult to track, poor code readability, and difficult to maintain. , and FP just has a good solution.

In addition, now mainstream programming languages ​​have basically introduced functional programming features. Even Java, which is famous for its object-oriented approach, can still practice functional programming ideas by using stream lambda expressions, and Spring5 is more It uses Reactive as the main selling point. In short, FP is very popular recently.

The functional programming ecosystem of JS is also constantly enriched, and frameworks such as RxJS and circleJS are increasingly used in front-end production lines.

3. Advantages of using functional programming

Using FP programming has the following main advantages:

  • Separate data and processing logic, the code is more concise, modular and readable

  • Easy to test, the test environment is easy to simulate

  • Strong reusability of logic code

4. Concepts related to functional programming

Functional programming The implementation mainly relies on:

  • Declarative programming

  • Pure function

  • Immutable data

4.1 Declarative programming

Declarative programming only describes the nature of the target, thereby abstracting the formal logic, Tell the computer what to calculate rather than how to calculate it step by step. For example, regular, SQL, FP, etc.

Imperative Programming Imperative Programming Tell the computer the calculation operation of each step

The simplest, the same array processing, using a for loop is imperative, using map and the like The operation is declarative. Using declarative programming simplifies code, improves reuse, and leaves room for refactoring.

4.2 Pure function

A brief summary of pure function has two characteristics:

  • The output of the function is only related to the input, The output produced by the same input is consistent and does not depend on external conditions

  • Function calls will not change the status or variables outside the function domain and will not have side effects on the system

看个简单的例子:

let counter = 0
const increment = () => ++counter
const increment = counter => ++counter
Copy after login

前一个函数每次调用都会修改外部变量的值,返回值也依赖于外部变量;后一个函数对于同一输入值每次返回的结果都相同,并且不会对外部状态造成影响。所以后一个是纯函数。

为什么要追求函数的纯度,这就涉及到一个称为引用透明性的概念。

4.2.1 引用透明性

纯函数的这种函数的返回值只依赖于其输入值的特性,被称为引用透明性(referential transparency),纯函数都是可以进行缓存的。

const memorize(pureFn) {
  const _cache = {}
  return (...args) => {
    const key = JSON.stringify(args)
    return _cache[key] || (_cache[key] = purFu.apply(null, args))
  }
}
Copy after login

4.3 Immutable Data

「可变的全局状态是万恶之源」(其实从功能代码的角度看,局部和全局是相对而言的),简而言之可变状态会让程序的运行变得不可预测,代码可读性差,难以维护。

在 JS 中,当函数入参是对象类型的数据时,我们拿到的其实是个引用,所以即使在函数内部我们也是可以修改对象内部的属性,这种情景依然会产生副作用。

所以这个时候就需要引入 Immutable 的概念。 Immutable 即 unchangeable, Immutable data在初始化创建后就不能被修改了,每次对于 Immutable data 的操作都会返回一个新的 Immutable data。 所以并不会对原来的状态形成改变(当然不是简单的深拷贝再修改)。

Immutable 比较流行的 JS 实现有 immutable-js 和 seamless-immutable; 对于 React 党来说, immutable-js 一点都不陌生, immutable-js 配合 Redux 就是一种很好的 FP 实践。

const map1 = Immutable.Map({a:1, b: {d:2}, c:3});
const map2 = map1.set('a', 50);
map1 === map2 // false
const mapb1 = map1.get('b')
const mapb2 = map2.get('b')
mapb1===mapb2 // true
Copy after login

【相关推荐:javascript视频教程编程视频

The above is the detailed content of Why does JavaScript use functional programming?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template