Understanding JavaScript Functional Programming
JavaScript FunctionFormProgramming is an existence It has been a topic for a long time, but it seems that since 2016, it has become more and more popular. This may be because ES6 syntax is more friendly to functional programming, or it may be due to the popularity of functional frameworks such as RxJS (ReactiveX).
I have seen many explanations about functional programming, but most of them are at the theoretical level, and some are only for pure users such as Haskell. Functional
. The purpose of this article is to talk about the specific practice of functional programming in JavaScript in my eyes. The reason why it is "in my eyes" means that what I say only represents my personal opinion, which may conflict with some strict concepts. This article will omit a lot of formal concept introduction, and focus on showing what functional code is in JavaScript, what is the difference between functional code and general writing, and what functional code can bring us What are the benefits and what are some common functional
models. I understand functional programming
I think functional programming can be understood as,
A programming method that uses functions as the main carrier, using functions to disassemble and abstract general Expression Compared with imperative expression, what are the advantages of doing this? The main points are as follows:
- The semantics are clearer
- The reusability is higher
- Better maintainability
- Limited scope, fewer side effects
- Basic functional programming
The following example is A specific functional expression
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
When the situation becomes more complicated, the way of writing the expression will encounter several problems:
- The meaning is not obvious, and gradually becomes It is difficult to maintain
- poor reusability, which will generate more code
- will generate a lot of intermediate
- variables Functional programming solves the above problems very well. First, refer to
, which uses function encapsulation to dismantle functions (the granularity is not unique), encapsulate them into different functions, and then use combined calls to achieve the purpose. This makes the expression clear and easy to maintain, reuse and extend. Secondly, using higher-order functions, Array.map replaces for...of for array traversal, reducing intermediate variables and operations. The main difference between
Functional Writing Method 1and Functional Writing Method 2 is that you can consider whether the function has the possibility of reuse in the future. If not, then The latter is better. Chain optimization
From the above
Functional writing method 2we can see that during the writing process of functional code, it is easy to cause horizontal extension , that is, multiple levels of nesting are generated. Let’s take a more extreme example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
. As the number of nested layers of functions continues to increase, the readability of the code will decrease significantly, and it is easy to cause mistake. In this case, we can consider a variety of optimization methods, such as the following
Chain optimization.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Callback function and Promise pattern.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Common functional programming model
Closure
A block of code that can retain local variables and not be released is called a closureThe concept of closure is relatively abstract. I believe everyone knows and uses this feature more or less
So what benefits can closure bring to us?
Let’s first look at how to create a closure:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
makeCounter 这个函数的代码块,在返回的函数中,对局部变量 k ,进行了引用,导致局部变量无法在函数执行结束后,被系统回收掉,从而产生了闭包。而这个闭包的作用就是,“保留住“ 了局部变量,使内层函数调用时,可以重复使用该变量;而不同于全局变量,该变量只能在函数内部被引用。
换句话说,闭包其实就是创造出了一些函数私有的 ”持久化变量“。
所以从这个例子,我们可以总结出,闭包的创造条件是:
存在内、外两层函数
内层函数对外层函数的局部变量进行了引用
闭包的用途
闭包的主要用途就是可以定义一些作用域局限的持久化变量,这些变量可以用来做缓存或者计算的中间量等等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
上面例子是一个简单的缓存工具的实现,匿名函数创造了一个闭包,使得 store 对象 ,一直可以被引用,不会被回收。
闭包的弊端
持久化变量不会被正常释放,持续占用内存空间,很容易造成内存浪费,所以一般需要一些额外手动的清理机制。
高阶函数
接受或者返回一个函数的函数称为高阶函数
听上去很高冷的一个词汇,但是其实我们经常用到,只是原来不知道他们的名字而已。JavaScript 语言是原生支持高阶函数的,因为 JavaScript 的函数是一等公民,它既可以作为参数又可以作为另一个函数的返回值使用。
我们经常可以在 JavaScript 中见到许多原生的高阶函数,例如 Array.map , Array.reduce , Array.filter
下面以 map 为例,我们看看他是如何使用的
map (映射)
映射是对集合而言的,即把集合的每一项都做相同的变换,产生一个新的集合
map 作为一个高阶函数,他接受一个函数参数作为映射的逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
上面一般写法,利用 for...of 循环的方式遍历数组会产生额外的操作,而且有改变原数组的风险
而 map 函数封装了必要的操作,使我们仅需要关心映射逻辑的函数实现即可,减少了代码量,也降低了副作用产生的风险。
柯里化(Currying)
给定一个函数的部分参数,生成一个接受其他参数的新函数
可能不常听到这个名词,但是用过 undescore 或 lodash 的人都见过他。
有一个神奇的 _.partial 函数,它就是柯里化的实现
1 2 3 4 5 6 7 8 9 10 11 12 |
|
通过 _.partial ,我们得到了新的函数 relativeFromBase ,这个函数在调用时就相当于调用 path.relative ,并默认将第一个参数传入 BASE ,后续传入的参数顺序后置。
本例中,我们真正想完成的操作是每次获得相对于 BASE 的路径,而非相对于任何路径。柯里化可以使我们只关心函数的部分参数,使函数的用途更加清晰,调用更加简单。
组合(Composing)
将多个函数的能力合并,创造一个新的函数
同样你第一次见到他可能还是在 lodash 中,compose 方法(现在叫 flow)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
_.flow 将转大写和转 Base64 的函数的能力合并,生成一个新的函数。方便作为参数函数或后续复用。
自己的观点
我理解的 JavaScript 函数式编程,可能和许多传统概念不同。我并不只认为 高阶函数 算函数式编程,其他的诸如普通函数结合调用、链式结构等,我都认为属于函数式编程的范畴,只要他们是以函数作为主要载体的。
而我认为函数式编程并不是必须的,它也不应该是一个强制的规定或要求。与面向对象或其他思想一样,它也是其中一种方式。我们更多情况下,应该是几者的结合,而不是局限于概念。
The above is the detailed content of Understanding JavaScript Functional Programming. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to remove duplicate values from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Build browser-based applications with Golang Golang combines with JavaScript to build dynamic front-end experiences. Install Golang: Visit https://golang.org/doc/install. Set up a Golang project: Create a file called main.go. Using GorillaWebToolkit: Add GorillaWebToolkit code to handle HTTP requests. Create HTML template: Create index.html in the templates subdirectory, which is the main template.

Through GoGet, you can quickly and easily obtain Go modules. The steps are as follows: Run in the terminal: goget[module-path], where module-path is the module path. GoGet automatically downloads the module and its dependencies. The location of the installation is specified by the GOPATH environment variable.

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).
