17

Having seen a lot of pure functions and how they have no side effects, what would be an example of an impure function, which is always been antagonized as unstable and major source of error?

JJJ
  • 32,902
  • 20
  • 89
  • 102
user2167582
  • 5,986
  • 13
  • 64
  • 121

6 Answers6

22

For example an impure function that has a side effect on a variable outside of its own scope:

var count = 0;

function increaseCount(val) {
    count += val;
}

Or a function that returns different values for the same input because it evaluates a variable that is not given as parameter:

var count = 0;

function getSomething() {
    return count > 0;
}
crackmigg
  • 5,571
  • 2
  • 30
  • 40
  • 1
    I like this example as this is currently my biggest pitfall. I'm all for API like JavaScript calls (that keep functions pure), however, I'm also for using JavaScript with OOP in mind, which may include impure functions like MyStringClass.length(). – Osmund Francis Mar 06 '16 at 09:30
  • The idea behind pure functions is to not use OOP. If you want to build a "class" that holds state you will always have impure functions. But as long as they are all part of the same "class" this is the tradeoff you have to make for OOP. – crackmigg Mar 06 '16 at 09:38
7

A pure function doesn’t depend on and doesn’t modify the states of variables out of its scope.

Concretely, that means a pure function always returns the same result given same parameters. Its execution doesn’t 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 );
// Now `values.a` is 3, the impure function modifies it.

Here we modify the attributes of the given object. Hence we modify the object which lies outside of the scope of our function: the function is impure.

var values = { a: 1 };

function pureFunction ( a ) {
  var b = 1;

  a = a * b + 2;

  return a;
}

var c = pureFunction( values.a );

we simply modify the parameter which is in the scope of the function, nothing is modified outside!

var values = { a: 1 };
var b = 1;

function impureFunction ( a ) {
  a = a * b + 2;

  return a;
}

var c = impureFunction( values.a );
// Actually, the value of `c` will depend on the value of `b`.
// In a bigger codebase, you may forget about that, which may 
// surprise you because the result can vary implicitly.

Here, b is not in the scope of the function. The result will depend on the context: surprises expected!

var values = { a: 1 };
var b = 1;

function pureFunction ( a, c ) {
  a = a * c + 2;

  return a;
}

var c = pureFunction( values.a, b );
// Here it's made clear that the value of `c` will depend on
// the value of `b`.

Reference : For more details, click here

abhiagNitk
  • 1,047
  • 10
  • 19
3

Math.random() is an impure function; it changes the internal state of the Math object so you get different values on successive calls. console.log() and alert() are impure functions because they have side effects (although they generate the same behavior and always return the same value for identical calls).

Any function that changes the internal state of one of its arguments or the value of some external variable is an impure function. This includes closures where calling a method changes the internal state of the closure itself:

let nextInt = (function() {
    var i = 0;
    return function() {
        return i++;
    };
})();

let a = nextInt(); // sets a to 0
let b = nextInt(); // sets b to 1
                   // etc.

Where'd you get the idea that impure functions are always considered a bad thing?

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • How `console.log()` is impure function? Could you please give some idea? – Sourav Apr 19 '17 at 13:24
  • @Sourav - I explained why: every call to `console.log()` has a side effect (specifically, the output that it writes to the console). Any function call that generates output is, by definition, an impure function. (See, for example, the [Wikipedia article _Pure function_](https://en.wikipedia.org/wiki/Pure_function).) – Ted Hopp Apr 19 '17 at 14:30
  • 1
    It behooves me to say that the nomenclature suggests that impure functions should be avoided, though I now realize this may not always be the case – goonerify Jul 27 '18 at 20:34
1
  1. Impure functon is a function which returns different result for same input parameters, that is to say that it depends on some state;
  2. Function that may return same result for same input parameters, but that mutates other state object. object that it does not depends but others do // causes side effects

example:

1)

 var toggled = false; /* state */

    /*impure function*/
    function  impureFn(number){
     if(number%2 == 0)
      toggled = true;
     return toggled;
    }

    /*Execute this in order */
    impureFn(5) // returns false
    impureFn(2) //returns true
    impureFn(5) // now returns true
Davit Tvildiani
  • 1,915
  • 3
  • 19
  • 29
0

An example i can think of (that is indeed quite confusing) is Array#reverse(). Instead of returning a new array, it modifies it in place while returning the original array.

Some other array functions do this as well, such as splice, push, shift, pop, unshift.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

pure function (get argument and return new value):

function (objectArgument) {
   return {
       value: objectArgument.value + 123,
       // other arguments
   };
}

impure function (get argument, modified it and return modified object):

function (objectArgument) {
   objectArgument.value += 123;
   return objectArgument;
}
Dmitriy
  • 3,745
  • 16
  • 24