简体   繁体   中英

understanding the anonymous function scope and return value

I have a function the receives two ints, I want another variable to be initialized with the larger one.

this is the code part:

 function findCommonDev(num1, num2) { var res = ((num1, num2) => { if (num1 > num2) { return num1; } else { return num2; } }); console.log(res); } findCommonDev(10,12) 

Now the questions arising from this are not related to the specific code.

  1. the console.log(res) prints '[function: res]' I would expect res to have the value of the bigger int passed to the function.

  2. I'm writing in VSC and the arguments are not marked as being used meaning that there is shadowing of num1 and num2 - why?

  3. how do I solve this elegantly?

You need to called the function and pass num1 and num2 as parameters.

 function findCommonDev(num1, num2) { var res = ((num1, num2) => { if (num1 > num2) { return num1; } else { return num2; } })(num1,num2); console.log(res); } findCommonDev(4,6) 

Also notice that if you don't pass num1 and num2 the code won't work because inside the the function num1 and num2 are local variables and not the variables of outer function.

The expected arguments of function are just like local variables. They are created whether parameters are passed or not.

Beside the returning of a new function (which is the real function for giving the wanted value), you could just take the max value.

 function findCommonDev(num1, num2) { var res = Math.max(num1, num2); console.log(res); } findCommonDev(3, 42); 

You are giving to console a function reference. However, of you want to run function, then specify parameters:

 function findCommonDev(num1, num2) { var res = ((num1, num2) => { if (num1 > num2) { return num1; } else { return num2; } }); return res(num1, num2); }; console.log(findCommonDev(1,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