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}`}; } 
9
  • 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 Commented Aug 4, 2020 at 6:14
  • 1
    Yes, a pure function can only call pure functions. Calling non-pure functions will make it non-pure as well. Commented Aug 4, 2020 at 7:14
  • @Bergi Then can function2 on the first example be pure function because function1 is pure? Commented Aug 4, 2020 at 7:23
  • 1
    @유택이 No, function1 is not pure because it has a side effect (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 are more than just that. Commented Aug 4, 2020 at 7:59
  • 1
    @유택이 Yes, your updated functions that return a value based on the arguments are both pure Commented Aug 4, 2020 at 12:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.