0

Is it possible to call function which calls pure function can be called pure function? How I understand 'pure function' is the function that always give same output on same input. Then let's do image this case.

const function1 = name => {
   console.log(`${name}`);
};

const function2 = name => {
   function1(name);
   console.log('you')
}

I know it's possible to look bit stupid, but what confused me is the example what I've seen as example of pure function. Because usually example was like this.

var c = 10;
function add2(a,b){
    return a + b + c;
}
console.log(add2(10,3)); // same
console.log(add2(10,3)); // same
c = 20;
console.log(add2(10,3)); // different

Then like we changed c on last code, if we change function1 on the first example, then function2 will be different as well. This simple thing make me curious how can I define 'pure function' strictly.

  • edited)
const function1 = name => {
   return `hi, ${name}`;
};

const function2 = name => {
   return `${function1('Alice')} and ${name}`};
}
lcpnine
  • 477
  • 1
  • 7
  • 16
  • 3
    actually they are not pure. the access things outside of their scope like `function1` or `c`. Both are outside. as you said `pure function is the function that always give same output on same input` and in your second example you have 3 times the same input but different output – bill.gates Aug 04 '20 at 06:14
  • 1
    Yes, a pure function can only call pure functions. Calling non-pure functions will make it non-pure as well. – Bergi Aug 04 '20 at 07:14
  • @Bergi Then can function2 on the first example be pure function because function1 is pure? – lcpnine Aug 04 '20 at 07:23
  • 1
    @유택이 No, `function1` is not pure because it has a [side effect](https://stackoverflow.com/q/54992302/1048572) (logging to the console), so `function2` is not pure either. And notice it's only a necessary, but not sufficient conditions that all called functions are pure for the function itself being pure - [the rules](https://stackoverflow.com/q/210835/1048572) are more than just that. – Bergi Aug 04 '20 at 07:59
  • @Bergi Ok, then for the last, I edited the question, if i use 'return' instead of console.log, like the last one, it doesn't have any side effect so we can call function2 as pure function as well, and pretty sure function1 is pure function. – lcpnine Aug 04 '20 at 09:45
  • yep just agree, both functions are not pure, because name can be different so result can be always different as well – Anna Vlasenko Aug 04 '20 at 09:48
  • @AnnaVlasenko I thought first one is definitely pure function because it always give same output on same input, isn't it? I got lost – lcpnine Aug 04 '20 at 11:27
  • 1
    @유택이 Yes, your updated functions that `return` a value based on the arguments are both pure – Bergi Aug 04 '20 at 12:33
  • @AnnaVlasenko `name` is a parameter, not a global mutable variable like `c`. The functions are pure, even if they are not constant functions. – Bergi Aug 04 '20 at 12:33

0 Answers0