简体   繁体   中英

JavaScript commutative behavior for function call. Needed pointers for what exactly happens behind scenes

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM