Pure functions

A pure function is a function that does not have a side-effect. Nothing the function does will ever affect a variable outside of it. This means that the input argument, when used in a computation, should not cause a side-effect, such as talking to the filesystem or opening a network connection, for example. Let's look at an example:

function notAPureFunction(filePath) {  const fileContent = fs.readFileSync(filePath);  const rows = fileContent.split(',');  let sum = 0;  rows.forEach(row => { sum += row; });  return sum;}

As we can see, our function opens up a file, loops through its rows, and calculates a sum of all the row contents. Unfortunately, the function talks to the filesystem, which is considered a side-effect. It may look ...

Get Architecting Angular Applications with Redux, RxJS, and NgRx now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.