search
HomeWeb Front-endJS TutorialUnderstanding 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

Programming language

. 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

// 数组中每个单词,首字母大写


// 一般写法
const arr = ['apple', 'pen', 'apple-pen'];
for(const i in arr){
  const c = arr[i][0];
  arr[i] = c.toUpperCase() + arr[i].slice(1);
}

console.log(arr);


// 函数式写法一
function upperFirst(word) {
  return word[0].toUpperCase() + word.slice(1);
}

function wordToUpperCase(arr) {
  return arr.map(upperFirst);
}

console.log(wordToUpperCase(['apple', 'pen', 'apple-pen']));


// 函数式写法二
console.log(arr.map(['apple', 'pen', 'apple-pen'], word => word[0].toUpperCase() + word.slice(1)));

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
  1. poor reusability, which will generate more code
  2. will generate a lot of intermediate
  3. variables

  4. Functional programming solves the above problems very well. First, refer to
Functional writing method 1

, 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 1

and 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 2

we 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.

// 计算数字之和


// 一般写法
console.log(1 + 2 + 3 - 4)


// 函数式写法
function sum(a, b) {
  return a + b;
}

function sub(a, b) {
  return a - b;
}

console.log(sub(sum(sum(1, 2), 3), 4);
This example only shows an extreme case of

horizontal extension

. 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

.

// 优化写法 (嗯,你没看错,这就是 lodash 的链式写法)
const utils = {
  chain(a) {
    this._temp = a;
    return this;
  },
  sum(b) {
    this._temp += b;
    return this;
  },
  sub(b) {
    this._temp -= b;
    return this;
  },
  value() {
    const _temp = this._temp;
    this._temp = undefined;
    return _temp;
  }
};

console.log(utils.chain(1).sum(2).sum(3).sub(4).value());
After rewriting in this way, the overall structure will become clearer, and what each link of the chain is doing can be easily displayed. Another good example of the comparison between function nesting and chaining is

Callback function and Promise pattern.

// 顺序请求两个接口

// 回调函数
import $ from 'jquery';
$.post('a/url/to/target', (rs) => {
  if(rs){
    $.post('a/url/to/another/target', (rs2) => {
      if(rs2){
        $.post('a/url/to/third/target');
      }
    });
  }
});


// Promise
import request from 'catta';  // catta 是一个轻量级请求工具,支持 fetch,jsonp,ajax,无依赖
request('a/url/to/target')
  .then(rs => rs ? $.post('a/url/to/another/target') : Promise.reject())
  .then(rs2 => rs2 ? $.post('a/url/to/third/target') : Promise.reject());
As the nested level of callback functions and the complexity of a single layer increase, it will become bloated and difficult to maintain. However, the chain structure of Promise can still expand vertically when the complexity is high, and The separation of levels is clear.

Common functional programming model

Closure

A block of code that can retain local variables and not be released is called a closure

The 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:

// 创建一个闭包
function makeCounter() {
  let k = 0;

  return function() {
    return ++k;
  };
}

const counter = makeCounter();

console.log(counter());  // 1
console.log(counter());  // 2

  makeCounter 这个函数的代码块,在返回的函数中,对局部变量 k ,进行了引用,导致局部变量无法在函数执行结束后,被系统回收掉,从而产生了闭包。而这个闭包的作用就是,“保留住“ 了局部变量,使内层函数调用时,可以重复使用该变量;而不同于全局变量,该变量只能在函数内部被引用。

  换句话说,闭包其实就是创造出了一些函数私有的 ”持久化变量“。

  所以从这个例子,我们可以总结出,闭包的创造条件是:

  1. 存在内、外两层函数

  2. 内层函数对外层函数的局部变量进行了引用

  闭包的用途

  闭包的主要用途就是可以定义一些作用域局限的持久化变量,这些变量可以用来做缓存或者计算的中间量等等。

// 简单的缓存工具
// 匿名函数创造了一个闭包
const cache = (function() {
  const store = {};
  
  return {
    get(key) {
      return store[key];
    },
    set(key, val) {
      store[key] = val;
    }
  }
}());

cache.set('a', 1);
cache.get('a');  // 1

  上面例子是一个简单的缓存工具的实现,匿名函数创造了一个闭包,使得 store 对象 ,一直可以被引用,不会被回收。

  闭包的弊端

  持久化变量不会被正常释放,持续占用内存空间,很容易造成内存浪费,所以一般需要一些额外手动的清理机制。

  高阶函数

接受或者返回一个函数的函数称为高阶函数

  听上去很高冷的一个词汇,但是其实我们经常用到,只是原来不知道他们的名字而已。JavaScript 语言是原生支持高阶函数的,因为 JavaScript 的函数是一等公民,它既可以作为参数又可以作为另一个函数的返回值使用。

  我们经常可以在 JavaScript 中见到许多原生的高阶函数,例如 Array.map , Array.reduce , Array.filter

  下面以 map 为例,我们看看他是如何使用的

  map (映射)

映射是对集合而言的,即把集合的每一项都做相同的变换,产生一个新的集合

  map 作为一个高阶函数,他接受一个函数参数作为映射的逻辑

// 数组中每一项加一,组成一个新数组


// 一般写法
const arr = [1,2,3];
const rs = [];
for(const n of arr){
  rs.push(++n);
}
console.log(rs)


// map改写
const arr = [1,2,3];
const rs = arr.map(n => ++n);

  上面一般写法,利用 for...of 循环的方式遍历数组会产生额外的操作,而且有改变原数组的风险

  而 map 函数封装了必要的操作,使我们仅需要关心映射逻辑的函数实现即可,减少了代码量,也降低了副作用产生的风险。

  柯里化(Currying)

给定一个函数的部分参数,生成一个接受其他参数的新函数

  可能不常听到这个名词,但是用过 undescore 或 lodash 的人都见过他。

  有一个神奇的 _.partial 函数,它就是柯里化的实现

// 获取目标文件对基础路径的相对路径

// 一般写法
const BASE = '/path/to/base';
const relativePath = path.relative(BASE, '/some/path');


// _.parical 改写
const BASE = '/path/to/base';
const relativeFromBase = _.partial(path.relative, BASE);

const relativePath = relativeFromBase('/some/path');

  通过 _.partial ,我们得到了新的函数 relativeFromBase ,这个函数在调用时就相当于调用 path.relative ,并默认将第一个参数传入 BASE ,后续传入的参数顺序后置。

  本例中,我们真正想完成的操作是每次获得相对于 BASE 的路径,而非相对于任何路径。柯里化可以使我们只关心函数的部分参数,使函数的用途更加清晰,调用更加简单。

  组合(Composing)

将多个函数的能力合并,创造一个新的函数

  同样你第一次见到他可能还是在 lodash 中,compose 方法(现在叫 flow)

// 数组中每个单词大写,做 Base64

// 一般写法 (其中一种)
const arr = ['pen', 'apple', 'applypen'];
const rs = [];
for(const w of arr){
  rs.push(btoa(w.toUpperCase()));
}
console.log(rs);


// _.flow 改写
const arr = ['pen', 'apple', 'applypen'];
const upperAndBase64 = _.partialRight(_.map, _.flow(_.upperCase, btoa));
console.log(upperAndBase64(arr));

  _.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!

Statement
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
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor