Reputation: 43
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.
the console.log(res) prints '[function: res]' I would expect res to have the value of the bigger int passed to the function.
I'm writing in VSC and the arguments are not marked as being used meaning that there is shadowing of num1 and num2 - why?
how do I solve this elegantly?
Upvotes: 0
Views: 49
Reputation: 36574
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.
Upvotes: 3
Reputation: 38114
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));
Upvotes: 0
Reputation: 386604
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);
Upvotes: 1