A pure function is independent of and does not change the state of variables from the scope.
Specifically, this means that a pure function always returns the same result with the same parameters. Its implementation does not depend on the state of the system.
var values = { a: 1 }; function impureFunction ( items ) { var b = 1; items.a = items.a * b + 2; return items.a; } var c = impureFunction( values );
Here we change the attributes of this object. Therefore, we modify an object that lies outside the scope of our function: the function is unclean.
var values = { a: 1 }; function pureFunction ( a ) { var b = 1; a = a * b + 2; return a; } var c = pureFunction( values.a );
we just change the parameter that is in the scope of the function, nothing changes outside!
var values = { a: 1 }; var b = 1; function impureFunction ( a ) { a = a * b + 2; return a; } var c = impureFunction( values.a );
Here b is not included in the scope of the function. The outcome will depend on the context: expected surprises!
var values = { a: 1 }; var b = 1; function pureFunction ( a, c ) { a = a * c + 2; return a; } var c = pureFunction( values.a, b );
Link: For more information, click here.
source share