JavaScript — Pure and Impure Functions

jayesh shinde
2 min readOct 12, 2019

--

One of the most favourite question in the JavaScript interview is Pure and Impure Functions. There is much more information available on the web about functional programming that probably every developer knows what a pure function is. But questions come why it is needed and do we really have practical example of it.

I would love to define a pure function as a function that doesn’t have an internal state. It means that all operations it performs are not affected by that state and given the same input parameters and produces the same deterministic output.

/ Pure Functionconst sumPure = (a, b) => {
return a + b;
};

After calling pure function it produces below output, which means for every function call it produces same output.

sumPure(1, 1); // OutPut: 2sumPure(1, 1); // OutPut: 2
sumPure(1, 1); // OutPut: 2

On the opposite side, Impure function produces different output for every function call.

// Impure Function

const sumImpure = (() => {
let state = 0
return (v) => {
return state += v
}
})();

sumImpure(1) // OutPut: 1
sumImpure(1) // OutPut: 2
sumImpure(1) // OutPut: 3

Key takeaway here is that even if the input doesn’t change the impure function can produce different output.

Pure Function:

  • Can be shared across many instances without affecting out put results.
class Calculator {

constructor(addFn) {
this.addFn = addFn;
}

add(a, b) {
return this.addFn(a, b);
}
}

const c1 = new Calculator(add);
const c2 = new Calculator(add);

c1.add(1, 1); // OutPut: 2
c2.add(1, 1); // OutPut: 2

Conclusion: If the function is pure and doesn’t have a state it can be safely shared with many instances of the Calculator classes:

Impure Function:

  • Cannot be shared because the internal state can be affected from outside
const add = (() => {
let state = 0;
return (v) => {
return state += v;
}

})();


class Calculator {
constructor(addFn) {
this.addFn = addFn;
}

add(a, b) {
return (this.addFn(a), this.addFn(b));
}
}


const c1 = new Calculator(add);
const c2 = new Calculator(add);

c1.add(1, 1); // 2
c2.add(1, 1); // 4 <------ here we have `4` instead of `2`

Conclusion: The function that is not pure can’t be shared. This is because the operations performed by one instance of Calculator will affect the function state and consequently the result of operations performed by the other instance of Calculator.

Practical Use Cases:

--

--

jayesh shinde
jayesh shinde

Written by jayesh shinde

Full Stack Developer | React| Angular| Swift| Node| AWS

No responses yet