0

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.

asked Aug 20, 2021 at 5:52

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.