Front-end engineering

Pure functions

Pure functions are functions that always return the same output for the same input. Code is pure function is faster to read since the scope of the function is limited to its arguments and the return value. Pure functions are also easier to test since they don't have side effects.

In javascript, pure functions are easy to use thanks to anonymous functions and arrow functions.

So pure functions should be used as much as possible, for example to manipulate arrays.

For example:

// BAD
let numberOfEvenNumbers = 0

for (let i = 0; i < array.length; i++) {
  if (array[i] % 2 === 0) {
    numberOfEvenNumbers++
  }
}

// GOOD
const numberOfEvenNumbers = array.filter((number) => number % 2 === 0).length

// Event BETTER
const isEven = (number) => number % 2 === 0
const numberOfEvenNumbers = array.filter(isEven).length

It makes the code easier to read and also easier to test since you can extract the pure function and test it separately.


Resources

Javascript provides a lot of functions requiring a pure function as argument like:

Previous
Server-side rendering
Next
Style