未加星标

What Is a Pure Function in JavaScript?

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

Pure functions are the atomic building blocks in functional programming. They are adored for their simplicity and testability.

This post covers a quick checklist to tell if a function’s pure or not.


What Is a Pure Function in JavaScript?
The Checklist

A function must pass two tests to be considered “pure”:

Same inputs always return same outputs No side-effects

Let’s zoom in on each one.

1. Same Input => SameOutput

Compare this:

const add = (x, y) => x + y; add(2, 4); // 6

To this:

let x = 2; const add = (y) => { x += y; }; add(4); // x === 6 (the first time) Pure Functions = Consistent Results

The first example returns a value based on the given parameters, regardless of where/when you call it.

If you pass 2 and 4 , you’ll always get 6 .

Nothing else affects the output.

Impure Functions = Inconsistent Results

The second example returns nothing. It relies on shared state to do its job by incrementing a variable outside of its own scope.

This pattern is a developer’s nightmare fuel.

Shared stateintroduces a time dependency. You get different results depending on when you called the function. The first time results in 6 , next time is 10 and so on.

Which Version’s Easier to ReasonAbout?

Which one’s less likely to breed bugs that happen only under certain conditions?

Which one’s more likely to succeed in a multi-threaded environment where time dependencies can break the system?

Definitely the first one.

2. No Side-Effects
What Is a Pure Function in JavaScript?

This test itself is a checklist. A few examples of side-effects are

console.log

Basically any work a function performs that isn’t related to calculating the final output.

I recommend watching this snippet by Uncle Bob Martin on the problem of state. It starts around 15 min.

Here’s an impure function with a side-effect.

Not SoBad const impureDouble = (x) => {
console.log('doubling', x); return x * 2; }; const result = impureDouble(4); console.log({ result });

console.log is the side-effect here but, in all practicality, it won’t harm us. We’ll still get the same outputs, given the same inputs.

This , however, may cause a problem.

“Impurely” Changing anObject const impureAssoc = (key, value, object) => { object[key] = value; }; const person = { name: 'Bobo' }; const result = impureAssoc('shoeSize', 400, person); console.log({ person, result });

The variable, person , has been forever changed because our function introduced an assignment statement.

Shared state means impureAssoc 's impact isn’t fully obvious anymore. Understanding its effect on a system now involves tracking down every variable it’s ever touched and knowing their histories.

Shared state = timing dependencies.

We can purify impureAssoc by simply returning a new object with our desired properties.

Purifying ItUp const pureAssoc = (key, value, object) => ({ ...object, [key]: value }); const person = { name: 'Bobo' }; const result = pureAssoc('shoeSize', 400, person); console.log({ person, result });

Now pureAssoc returns a testable result and we’ll never worry if it quietly mutated something elsewhere.

You could even do the following and remain pure:

Another PureWay const pureAssoc = (key, value, object) => {
const newObject = { ...object }; newObject[key] = value; return newObject; }; const person = { name: 'Bobo' }; const result = pureAssoc('shoeSize', 400, person); console.log({ person, result });

Mutating your input can be dangerous, but mutating a copy of it is no problem. Our end result is still a testable, predictable function that works no matter where/when you call it.

The mutation’s limited to that small scope and you’re still returning a value.

Summary
What Is a Pure Function in JavaScript?
A function’s pure if it’s free from side-effects and returns the same output, given the same input. Side-effects include: mutating input, HTTP calls, writing to disk, printing to the screen. You can safely clone , then mutate , your input. Just leave the original one untouched. Spread syntax ( … syntax) is the easiest way to clone objects and arrays. My FreeCourse

This tutorial was from my completely free course on Educative.io, Functional Programming Patterns With RamdaJS !

Please consider taking/sharing it if you enjoyed this content.

It’s full of lessons, graphics, exercises, and runnable code samples to teach you a basic functional programming style using RamdaJS.

I’m also on Twitter if you’d like to talk. Until next time!

Take care,

Yazeed Bzadough

http://yazeedb.com/

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:What Is a Pure Function in JavaScript?
本站链接:https://www.codesec.net/view/628364.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(91)