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

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.

主站蜘蛛池模板: 新巴尔虎右旗| 霍州市| 永善县| 黔西| 武功县| 商南县| 桑植县| 仙游县| 北票市| 洛隆县| 大埔县| 登封市| 盐城市| 柞水县| 大新县| 扬中市| 和平区| 江川县| 鹤山市| 准格尔旗| 增城市| 黄陵县| 淳安县| 临武县| 平邑县| 谢通门县| 肥乡县| 全椒县| 十堰市| 黑水县| 丹凤县| 凯里市| 石家庄市| 诸城市| 依兰县| 张家口市| 孝感市| 台安县| 饶阳县| 习水县| 庆元县|