What is Pure function in javascript ES6 ?

A pure function is a function that returns a value that is computed based on its arguments. Pure functions take at least one argument and always return a value or another function. They do not cause side effects, set global variables, or change anything about application state. They treat their arguments as immutable data

Example of Impure function

selfEducate function is not a pure function. It does not take any arguments, and it does not return a value or a function. it also modify a variable outside of its scope e.g frederick and this is causes side effect

var frederick = {
 name: "Frederick Douglass",
 canRead: false,
 canWrite: false
}
const selfEducate = (person) => {
 person.canRead = true
 person.canWrite = true
 return person
}
console.log( selfEducate(frederick) )
 // {name: "Frederick Douglass", canRead: true, canWrite: true}
console.log( frederick )
 // {name: "Frederick Douglass", canRead: true, canWrite: true}


Example of Pure Function

const frederick = {
 name: "Frederick Douglass",
 canRead: false,
 canWrite: false
}
const selfEducate = person =>
 ({
 ...person,
 canRead: true,
 canWrite: true
 })
console.log( selfEducate(frederick) )
console.log( frederick )
// {name: "Frederick Douglass", canRead: true, canWrite: true} 
// {name: "Frederick Douglass", canRead: false, canWrite: false}

this version of selfEducate is a pure function. It computes a value based on the argument that was sent to it: the person. It returns a new person object without mutating the argument sent to it and therefore has no side effects.

Pure functions are naturally testable. They do not change anything about their environment or “world,” and therefore do not require a complicated test setup or teardown. Everything a pure function needs to operate it accesses via arguments. When testing a pure function, you control the arguments, and thus you can estimate the outcome

Leave a Comment