官术网_书友最值得收藏!

Purity

An important aspect of FP is to write pure functions. You will encounter this concept very often in the React ecosystem, especially if you look into libraries such as Redux.

What does it mean for a function to be pure?

A function is pure when there are no side-effects, which means that the function does not change anything that is not local to the functions itself.

For example, a function that changes the state of an application, or modifies variables defined in the upper scope, or a function that touches external entities, such as the DOM, is considered impure. Impure functions are harder to debug, and most of the time it is not possible to apply them multiple times and expect to get the same result.

For example, the following function is pure:

const add = (x, y) => x + y;

It can be run multiple times, always getting the same result, because nothing is stored anywhere and nothing gets modified.

The following function is not pure:

let x = 0;
const add = y => (x = x + y);

Running add(1) twice, we get two different results. The first time we get 1, but the second time we get 2, even if we call the same function with the same parameter. The reason we get that behavior is that the global state gets modified after every execution.

主站蜘蛛池模板: 蓝田县| 信阳市| 东光县| 大港区| 尼勒克县| 崇左市| 额尔古纳市| 和龙市| 谢通门县| 临漳县| 乐陵市| 汾阳市| 梧州市| 太保市| 井冈山市| 新津县| 云龙县| 松原市| 耒阳市| 赤壁市| 西和县| 隆林| 宽城| 呼图壁县| 剑河县| 黄陵县| 紫阳县| 华坪县| 建阳市| 新巴尔虎右旗| 定边县| 鹤峰县| 九台市| 无为县| 搜索| 赫章县| 内黄县| 环江| 中牟县| 英吉沙县| 望谟县|