search
HomeWeb Front-endFront-end Q&AWhy does JavaScript use functional programming?

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

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

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]

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

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

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

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))
  }
}

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

【相关推荐: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!

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
React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)