I have following code and want to check commutative property with impure functions. Can anyone explain why the first two console log print 3, 3 and why the direct function call print 3 and -3?
var multi = 1;
const f = x =>{
multi = -multi;
return x * multi;
}
let a = f(2);
let b = f(5);
console.log("a+b:: ",a+b);
console.log("a+b:: ",b+a);
console.log("a+b:: ",f(2) + f(5));
console.log("a+b:: ",f(5) + f(2));
Any suggestions/explanation is appreciated.
1 Answer 1
For the first two logs, you're only invoking the functions twice - in these lines:
let a = f(2);
let b = f(5);
after which a and b don't change. 5 + -3 is the same as -3 + 5.
For the last two logs, you invoke the functions four times, and the signs invert each time the function is called, resulting in
f(2) + f(5) // -2 + 5
f(5) + f(2) // -5 + 2
answered Aug 20, 2021 at 5:55
CertainPerformance
374k55 gold badges354 silver badges359 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js